fern-api 4.86.0 → 4.86.1
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/cli.cjs +6 -6
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1584,7 +1584,7 @@ ${o.mark.snippet}`)),o.mark!=null&&(o.reason==="bad indentation of a mapping ent
|
|
|
1584
1584
|
`),l=o.mark.line>=0&&o.mark.line<u.length?u[o.mark.line]:void 0;l!=null&&/:\s+@/.test(l)&&(a+=`
|
|
1585
1585
|
|
|
1586
1586
|
Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in quotes.
|
|
1587
|
-
Example: package-name: "@scope/package"`)}t.failAndThrow(a,void 0,{code:j.Code.ConfigError})}else throw o}}async function m6({absolutePathToWorkspace:e,context:t,lenient:r}){let n=await fYe({absolutePathToWorkspace:e,context:t,lenient:r});if(n==null)return;let i=await A0e({absolutePathToWorkspace:e});if(i!=null)return IGa({absolutePathToGeneratorsConfiguration:i,rawGeneratorsConfiguration:n,context:t})}async function A0e({absolutePathToWorkspace:e}){let t=$e(e,Te.of(nf)),r=$e(e,Te.of(LGe));if(await cr(t))return t;if(await cr(r))return r}Jt();var dYe=Ie(require("path"),1),FGa=require("url");var TGa=Ie(require("process"),1),OGa=Ie(require("path"),1),qOr=Ie(require("fs"),1),PGa=require("url");var jHi=class{value;next;constructor(t){this.value=t}},vkt=class{#e;#t;#r;constructor(){this.clear()}enqueue(t){let r=new jHi(t);this.#e?(this.#t.next=r,this.#t=r):(this.#e=r,this.#t=r),this.#r++}dequeue(){let t=this.#e;if(t)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),t.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let t=this.#e;for(;t;)yield t.value,t=t.next}*drain(){for(;this.#e;)yield this.dequeue()}};function zOr(e){if(!((Number.isInteger(e)||e===Number.POSITIVE_INFINITY)&&e>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let t=new vkt,r=0,n=()=>{r--,t.size>0&&t.dequeue()()},i=async(a,c,u)=>{r++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},o=(a,c,u)=>{t.enqueue(i.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),r<e&&t.size>0&&t.dequeue()()))()},s=(a,...c)=>new Promise(u=>{o(a,u,c)});return Object.defineProperties(s,{activeCount:{get:()=>r},pendingCount:{get:()=>t.size},clearQueue:{value:()=>{t.clear()}}}),s}var VOr=class extends Error{constructor(t){super(),this.value=t}},vSf=async(e,t)=>t(await e),CSf=async e=>{let t=await Promise.all(e);if(t[1]===!0)throw new VOr(t[0]);return!1};async function MHi(e,t,{concurrency:r=Number.POSITIVE_INFINITY,preserveOrder:n=!0}={}){let i=zOr(r),o=[...e].map(a=>[a,i(vSf,a,t)]),s=zOr(n?1:Number.POSITIVE_INFINITY);try{await Promise.all(o.map(a=>s(CSf,a)))}catch(a){if(a instanceof VOr)return a.value;throw a}}var DGa={directory:"isDirectory",file:"isFile"};function xSf(e){if(!Object.hasOwnProperty.call(DGa,e))throw new Error(`Invalid type specified: ${e}`)}var wSf=(e,t)=>t[DGa[e]](),SSf=e=>e instanceof URL?(0,PGa.fileURLToPath)(e):e;async function LHi(e,{cwd:t=TGa.default.cwd(),type:r="file",allowSymlinks:n=!0,concurrency:i,preserveOrder:o}={}){xSf(r),t=SSf(t);let s=n?qOr.promises.stat:qOr.promises.lstat;return MHi(e,async a=>{try{let c=await s(OGa.default.resolve(t,a));return wSf(r,c)}catch{return!1}},{concurrency:i,preserveOrder:o})}var RGa=Ie(require("fs"),1);var _Sf=e=>e instanceof URL?(0,FGa.fileURLToPath)(e):e,BSf=Symbol("findUpStop");async function TSf(e,t={}){let r=dYe.default.resolve(_Sf(t.cwd)||""),{root:n}=dYe.default.parse(r),i=dYe.default.resolve(r,t.stopAt||n),o=t.limit||Number.POSITIVE_INFINITY,s=[e].flat(),a=async u=>{if(typeof e!="function")return LHi(s,u);let l=await e(u.cwd);return typeof l=="string"?LHi([l],u):l},c=[];for(;;){let u=await a({...t,cwd:r});if(u===BSf||(u&&c.push(dYe.default.resolve(r,u)),r===i||c.length>=o))break;r=dYe.default.dirname(r)}return c}async function bd(e,t={}){return(await TSf(e,{...t,limit:1}))[0]}async function FA(e){let t=await bd(e??xA,{type:"directory"});if(t==null)return;let r=$t.of(t);if(await cr($e(r,Te.of(tI))))return r}Jt();function kGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.definitionFile?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("webhookSignature"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function NGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.packageMarker?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("export"),...i("navigation")}}function QGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.rootApiFile?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}var UHi={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(nDe(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&hg(e.request.body)){let r=[];for(let[n,i]of Object.entries(e.request.body.properties??{}))typeof i!="string"&&i["content-type"]!=null&&r.push({severity:"fatal",message:`${n} has content-type, but the request is not multipart`});return r}return[]}}})};Wi();function Ckt({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Gx.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return sDe(e.auth,{single:n=>{let i=jGa({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Gx.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:Gx.Any,schemes:n.map(i=>jGa({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))}),endpointSecurity:()=>({docs:r,requirement:Gx.EndpointSecurity,schemes:[]})})}function jGa({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let n=(o,s)=>{let a=t?.[o];if(a==null)throw new Error("Unknown auth scheme: "+o);return aDe(a,{header:c=>Gp.header({key:o,docs:s,name:r.generateNameAndWireValue({name:c.name??o,wireValue:c.header}),valueType:kr.primitive({v1:fs.String,v2:$n.string({default:void 0,validation:void 0})}),prefix:c.prefix,headerEnvVar:c.env}),basic:c=>MGa({key:o,casingsGenerator:r,docs:s,rawScheme:c}),tokenBearer:c=>GOr({key:o,casingsGenerator:r,docs:s,rawScheme:c}),inferredBearer(c){return GOr({key:o,casingsGenerator:r,docs:s,rawScheme:void 0})},oauth:c=>GOr({key:o,casingsGenerator:r,docs:s,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return GOr({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return MGa({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function GOr({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return Gp.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function MGa({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return Gp.basic({key:e,docs:r,username:t.generateName(n?.username?.name??"username"),usernameEnvVar:n?.username?.env,usernameOmit:n?.username?.omit,password:t.generateName(n?.password?.name??"password"),passwordEnvVar:n?.password?.env,passwordOmit:n?.password?.omit})}function ob(e){let t=PSf(e),{value:r,done:n}=zHi(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...OSf(t)]}}function*OSf(e){let t;do{let{value:r}=zHi(e,"}"),n=zHi(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*PSf(e){for(let t of e)yield t}function zHi(e,t){let r="",n=e.next();for(;n.done!==!0&&n.value!==t;)r+=n.value,n=e.next();return{value:r,done:n.done??!1}}Wi();function xkt({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:iH(n,{singleBaseUrl:()=>q0.singleBaseUrl(DSf({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q0.multipleBaseUrls(RSf({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,o])=>[i,iH(o,{singleBaseUrl:s=>[...typeof s=="string"?[]:s.audiences??[]],multipleBaseUrls:s=>[...s.audiences??[]]})]))}}}function DSf({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>iH(n,{singleBaseUrl:i=>{let o=typeof i=="string",s=o?void 0:i["default-url"],a=o?void 0:i["url-template"],c=o?void 0:i.variables;return{docs:o?void 0:i.docs,id:r,name:t.generateName(r),url:WOr(o?i:i.url),audiences:o?void 0:i.audiences,defaultUrl:s?WOr(s):void 0,urlTemplate:a,urlVariables:c?.map(u=>({id:u.id,name:t.generateName(u.id),default:u.default,values:u.values}))}},multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function RSf({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>iH(i,{multipleBaseUrls:o=>{let s=o["url-templates"],a=o["default-urls"],c=o.variables,u=s&&Object.keys(s).length>0?s:void 0,l=a&&Object.keys(a).length>0?ep(a,d=>WOr(d)):void 0,p=c&&Object.keys(c).length>0?Object.fromEntries(Object.entries(c).map(([d,f])=>[d,f.map(m=>({id:m.id,name:r.generateName(m.id),default:m.default,values:m.values}))])):void 0;return{docs:o.docs,id:n,name:r.generateName(n),urls:ep(o.urls,d=>WOr(d)),audiences:o.audiences,defaultUrls:l,urlTemplates:u,urlVariables:p}},singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function WOr(e){return e.endsWith("/")?e.slice(0,-1):e}Rt();function y0e(e){let t=2166136261;function r(o){t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}function n(o){for(let s=0,a=o.length;s<a;s++)r(o.charCodeAt(s))}function i(o,s){if(typeof o=="object"&&o!=null){if(s>64){n("[MaxDepthExceeded]");return}if(Array.isArray(o)){r(91);for(let a=0;a<o.length;a++)a>0&&r(44),i(o[a],s+1);r(93)}else{r(123);let a=Object.keys(o).sort(),c=a.length;for(let u=0;u<c;u++)u>0&&r(44),n(a[u]??""),r(58),i(o[a[u]??""],s+1);r(125)}}else n(String(o))}return i(e,0),t.toString(16)}function mY({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}Wi();Wi();var LGa={[Rn.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,Fu(e)])),[Rn.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Rn.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Rn.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[Rn.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","internal","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Rn.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[Rn.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Rn.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[Rn.GenerationLanguage.SWIFT]:new Set([])};var FSf=["go","ruby"];function mYe(e,t,r){let{generationLanguage:n,keywords:i,smartCasing:o}=r,s=VSf(e),a=A=>({unsafeName:A,safeName:kSf({name:A,keywords:NSf({generationLanguage:n,keywords:i})})}),c=t.preserveUnderscores===!0,u=c?(A,b)=>VHi(A,b):(A,b)=>b(A),l=u(s,Wn),p=c?VHi(s,A=>Fu(Wn(A))):Fu(l),d=u(s,TPe),{leading:f,trailing:m}=c?UGa(s):{leading:"",trailing:""},h=jwt(l);if(o){!MSf(h)&&(n==null||FSf.includes(n))&&(l=f+h.map((b,v)=>{if(v>0){let x=$Or(b);if(x!=null)return x;if(HOr(b))return b.toUpperCase()}return b}).join("")+m,p=Fu(f+h.map((b,v)=>{let x=$Or(b);return x??(HOr(b)?b.toUpperCase():v===0?Fu(b):b)}).join("")+m));let A=b=>b.split(" ").map(v=>v.split(/(\d+)/).map(TPe).join("")).join("_");d=c?VHi(s,A):A(s)}return{originalName:e,camelCase:a(t.casingOverrides?.camel??l),snakeCase:a(t.casingOverrides?.snake??d),screamingSnakeCase:a(t.casingOverrides?.["screaming-snake"]??d.toUpperCase()),pascalCase:a(t.casingOverrides?.pascal??p)}}function sw({generationLanguage:e,keywords:t,smartCasing:r}){let n={generationLanguage:e,keywords:t,smartCasing:r};return{generateName:(i,o)=>o?.casingOverrides!=null?mYe(i,o,n):i,generateNameAndWireValue:({name:i,wireValue:o,opts:s})=>s?.casingOverrides!=null?{wireValue:o,name:mYe(i,s,n)}:o===i?o:{wireValue:o,name:i}}}function b0e({generationLanguage:e,keywords:t,smartCasing:r}){let n={generationLanguage:e,keywords:t,smartCasing:r};return{generateName:(i,o)=>{if(typeof i=="string")return mYe(i,o??{},n);if("wireValue"in i){let s=i.name;return typeof s=="string"?mYe(s,o??{},n):s}return i},generateNameAndWireValue:(i,o)=>{if(typeof i=="string")return{wireValue:i,name:mYe(i,o??{},n)};let{name:s,wireValue:a}=i,c=typeof s=="string"?mYe(s,o??{},n):s;return{wireValue:a,name:c}}}}function kSf({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":jSf(e)?"_"+e:e}function NSf({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return LGa[e]}var QSf=/^[0-9]/;function jSf(e){return QSf.test(e)}function MSf(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=$Or(n)!=null||HOr(n),o=$Or(t)!=null||HOr(t);return i&&o})}function $Or(e){return USf.get(e.toUpperCase())}function HOr(e){return LSf.has(e.toUpperCase())}var LSf=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),USf=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),zSf=[[/\[\]/g,"Array"]];function VSf(e){return zSf.reduce((t,[r,n])=>t.replace(r,n),e)}function UGa(e){let t=e.match(/^(_+)/),r=e.match(/(_+)$/),n=t?.[1]??"",i=r?.[1]??"";if(n.length+i.length>=e.length)return{leading:e,trailing:"",core:""};let o=e.slice(n.length,e.length-i.length||void 0);return{leading:n,trailing:i,core:o}}function VHi(e,t){let{leading:r,trailing:n,core:i}=UGa(e);return r===""&&n===""?t(e):`${r}${t(i)}${n}`}function qSf(e){return"wireValue"in e&&!("originalName"in e)}function KOr(e){return typeof e=="string"?e:qSf(e)?e.name:e}function Vr(e){let t=KOr(e);return typeof t=="string"?t:t.originalName}function Xt(e){return typeof e=="string"?e:e.wireValue}function JOr(e){return typeof e=="string"?e:e.name}function GHi(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).snakeCase.unsafeName:t.snakeCase.unsafeName}var qHi;function WHi(){return qHi==null&&(qHi=b0e({generationLanguage:void 0,keywords:void 0,smartCasing:!0})),qHi}function $Hi(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).camelCase.unsafeName:t.camelCase.unsafeName}function wkt(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).pascalCase.unsafeName:t.pascalCase.unsafeName}Rt();function zGa({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s}){if(n>=r)return l7({containerType:t});switch(t.type){case"list":{let a=Wd({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.list({list:[a.example,a.example],itemType:t.list}),jsonExample:[a.jsonExample,a.jsonExample]}}case"literal":return{type:"success",example:hl.literal({literal:t.literal._visit({boolean:a=>Ci.boolean(a),string:a=>Ci.string({original:a}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:a=>a,string:a=>a,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(o)return l7({containerType:t});let a=Wd({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.optional({optional:a.example,valueType:t.optional}),jsonExample:a.jsonExample}}case"nullable":{if(o)return l7({containerType:t});let a=Wd({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.nullable({nullable:a.example,valueType:t.nullable}),jsonExample:a.jsonExample}}case"set":{let a=Wd({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.set({set:[a.example],itemType:t.set}),jsonExample:[a.jsonExample]}}case"map":{let a=Wd({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s}),c=Wd({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"||c.type==="failure"?l7({containerType:t}):{type:"success",example:hl.map({map:[{key:a.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[a.jsonExample]:c.jsonExample}}}default:Ce(t)}}function l7({containerType:e}){switch(e.type){case"list":return{type:"success",example:hl.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:hl.literal({literal:e.literal._visit({boolean:t=>Ci.boolean(t),string:t=>Ci.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:hl.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:hl.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:hl.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:hl.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ce(e)}}Rt();function HHi({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return KSf({fieldName:e,default_:GSf(t.v2),validation:WSf(t.v2)});case"BASE_64":return{type:"success",example:Ci.base64(ki.BASE64),jsonExample:ki.BASE64};case"BOOLEAN":return{type:"success",example:Ci.boolean(ki.BOOLEAN),jsonExample:ki.BOOLEAN};case"DATE":return{type:"success",example:Ci.date(ki.DATE),jsonExample:ki.DATE};case"DATE_TIME":return{type:"success",example:Ci.datetime({datetime:new Date(ki.DATE_TIME),raw:ki.DATE_TIME}),jsonExample:ki.DATE_TIME};case"DOUBLE":return JSf({fieldName:e,validation:$Sf(t.v2)});case"FLOAT":return{type:"success",example:Ci.float(ki.FLOAT),jsonExample:ki.FLOAT};case"INTEGER":return YSf({fieldName:e,validation:HSf(t.v2)});case"UINT_64":return{type:"success",example:Ci.uint64(ki.INT64),jsonExample:ki.INT64};case"UINT":return{type:"success",example:Ci.uint(ki.UINT),jsonExample:ki.UINT};case"BIG_INTEGER":return{type:"success",example:Ci.bigInteger(ki.INT64.toString()),jsonExample:`${ki.INT64}`};case"LONG":return{type:"success",example:Ci.long(ki.INT64),jsonExample:ki.INT64};case"UUID":return{type:"success",example:Ci.uuid(ki.UUID),jsonExample:ki.UUID};case"DATE_TIME_RFC_2822":return{type:"success",example:Ci.datetimeRfc2822({datetime:new Date(ki.DATE_TIME_RFC_2822),raw:ki.DATE_TIME_RFC_2822}),jsonExample:ki.DATE_TIME_RFC_2822};default:Ce(t.v1)}}function GSf(e){if(e?.type==="string")return e.default}function WSf(e){if(e?.type==="string")return e.validation}function $Sf(e){if(e?.type==="double")return e.validation}function HSf(e){if(e?.type==="integer")return e.validation}function VGa(e){if(e<=0)return"";if(e<=ki.SAMPLE_STRINGS.length){let t=ki.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return ki.SAMPLE_STRINGS[ki.SAMPLE_STRINGS.length-1]+".".repeat(e-ki.SAMPLE_STRINGS.length)}function KSf({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Ci.string({original:t}),jsonExample:t};if(r){let i=r.minLength,o=r.maxLength;if(i){let s=VGa(i);return{type:"success",example:Ci.string({original:s}),jsonExample:s}}else if(o!=null&&o<10){let s=VGa(o);return{type:"success",example:Ci.string({original:s}),jsonExample:s}}}let n=e??ki.STRING;return{type:"success",example:Ci.string({original:n}),jsonExample:n}}function JSf({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:Ci.double(r),jsonExample:r};if(n)return{type:"success",example:Ci.double(n),jsonExample:n}}return{type:"success",example:Ci.double(ki.DOUBLE),jsonExample:ki.DOUBLE}}function YSf({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:Ci.integer(r),jsonExample:r};if(n)return{type:"success",example:Ci.integer(n),jsonExample:n}}return{type:"success",example:Ci.integer(ki.INT),jsonExample:ki.INT}}function XSf(e,t){if(e.type==="primitive"||e.type==="container"&&e.container.type==="literal")return!0;if(e.type==="named"){let r=t[e.typeId];if(r!=null&&r.shape.type==="enum")return!0}return!1}function Y2e({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s}){switch(r.shape.type){case"alias":{let a=Wd({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s});if(a.type==="failure")return a;let{example:c,jsonExample:u}=a;return{type:"success",example:Qu.alias({value:c}),jsonExample:u}}case"enum":{let a=r.shape.values[0];return a==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Qu.enum({value:a.name}),jsonExample:Xt(a.name)}}case"object":{let a={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let d of r.shape.extends){let f=t[d.typeId];if(f==null)continue;let m=Y2e({fieldName:e,typeDeclaration:f,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});m!=null&&m.type==="success"&&m.example.type==="object"&&(Object.assign(a,m.jsonExample),c.push(...m.example.properties))}let u=ZSf({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(u.type==="failure")return u;let{example:l,jsonExample:p}=u;return{type:"success",example:Qu.object({properties:[...c,...l.properties],extraProperties:l.extraProperties}),jsonExample:Object.assign({},a,p)}}case"undiscriminatedUnion":{let a=r.shape.members;if(a.every(l=>XSf(l.type,t))){let l=a.findIndex(p=>{if(p.type.type==="container"&&p.type.container.type==="literal")return!0;if(p.type.type==="named"){let d=t[p.type.typeId];if(d!=null&&d.shape.type==="enum")return d.shape.values.length>0}return!1});if(l!==-1){let p=a[l];if(p!=null){let d=Wd({fieldName:e,typeReference:p.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(d.type==="success"){let{example:f,jsonExample:m}=d;return{type:"success",example:Qu.undiscriminatedUnion({index:l,singleUnionType:f}),jsonExample:m}}}}}let u=0;for(let l of a){let p=Wd({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(p.type==="failure"){++u;continue}let{example:d,jsonExample:f}=p;return{type:"success",example:Qu.undiscriminatedUnion({index:u,singleUnionType:d}),jsonExample:f}}break}case"union":{let a=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let p of r.shape.baseProperties){let d=Wd({fieldName:Xt(p.name),typeReference:p.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});d.type==="success"&&(c[Xt(p.name)]=d.jsonExample)}let u=r.shape.baseProperties.map(p=>{let d=Wd({fieldName:Xt(p.name),typeReference:p.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(d.type==="failure")throw new Error(`Failed to generate example for union base property ${Xt(p.name)}`);let{example:f}=d;return{name:p.name,value:f}}),l=r.shape.extends.flatMap(p=>{let d=t[p.typeId];if(d==null)throw new Error(`Failed to find extended type declaration with id ${p.typeId}`);let f=Y2e({fieldName:e,typeDeclaration:d,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(f==null||f.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${d.name.typeId}`);if(f.example.type!=="object")throw new Error(`Extended type declaration ${d.name.typeId} is not an object`);return f.example.properties});for(let p of r.shape.types){let d=p.shape._visit({noProperties:()=>({type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.noProperties()},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),...c}}),samePropertiesAsObject:f=>{let m=t[f.typeId];if(m==null)return{type:"failure",message:`Failed to find type declaration with id ${f.typeId}`};let h=Y2e({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:m,typeDeclarations:t,skipOptionalProperties:o,visitedTypes:s});if(h==null)return{type:"failure",message:"Failed to generate example for type reference"};if(h.type==="failure")return h;let{example:A,jsonExample:b}=h;return{type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeId:m.name.typeId,object:A.type==="object"?A:{properties:[],extraProperties:void 0}})},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),...typeof b=="object"?b:{},...c}}},singleProperty:f=>{let m=Wd({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:f.type,typeDeclarations:t,skipOptionalProperties:o,visitedTypes:s});if(m.type==="failure")return m;let{example:h,jsonExample:A}=m;return{type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.singleProperty(h)},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),[Xt(f.name)]:A,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function ZSf({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:o,skipOptionalProperties:s,visitedTypes:a}){let c={},u=[];for(let l of[...r.properties??[],...r.extendedProperties??[]]){let p=Wd({fieldName:Xt(l.name),typeReference:l.valueType,typeDeclarations:n,currentDepth:o+1,maxDepth:i,skipOptionalProperties:s,visitedTypes:a});if(p.type==="failure"&&!mY({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${Xt(l.name)} b/c ${p.message}`};if(p.type==="failure")continue;let{example:d,jsonExample:f}=p;u.push({name:l.name,originalTypeDeclaration:t.name,value:d,propertyAccess:l.propertyAccess}),c[Xt(l.name)]=f}return{type:"success",example:Qu.object({properties:u,extraProperties:void 0}),jsonExample:c}}function Wd({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s}){if(i>n)return{type:"failure",message:`Exceeded max depth of ${n}`};switch(t.type){case"named":{let a=r[t.typeId];if(a==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=s??new Map,u=c.get(t.typeId)??0;if(u>=2){let m=new Set([t.typeId]);return JHi({typeDeclaration:a,typeDeclarations:r,visitedMinimalTypes:m})}c.set(t.typeId,u+1);let l=Y2e({fieldName:e,typeDeclaration:a,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:c}),p=(c.get(t.typeId)??1)-1;if(p<=0?c.delete(t.typeId):c.set(t.typeId,p),l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:f}=l;return{type:"success",example:{jsonExample:f,shape:mo.named({shape:d,typeName:a.name})},jsonExample:f}}case"container":{let a=zGa({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s});if(a.type==="failure"){let{example:l,jsonExample:p}=l7({containerType:t.container});return{type:"success",example:{jsonExample:p,shape:mo.container(l)},jsonExample:p}}let{example:c,jsonExample:u}=a;return{type:"success",example:{jsonExample:u,shape:mo.container(c)},jsonExample:u}}case"primitive":{let{jsonExample:a,example:c}=HHi({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:a,shape:mo.primitive(c)},jsonExample:a}}case"unknown":{let a={key:"value"};return{type:"success",example:{jsonExample:a,shape:mo.unknown(a)},jsonExample:a}}}}function KHi(e,t){switch(e.type){case"primitive":case"unknown":return!0;case"named":return t[e.typeId]?.shape.type==="enum";case"container":switch(e.container.type){case"literal":return!0;case"optional":return KHi(e.container.optional,t);case"nullable":return KHi(e.container.nullable,t);default:return!1}}}function JHi({typeDeclaration:e,typeDeclarations:t,visitedMinimalTypes:r}){let n=r??new Set;switch(n.add(e.name.typeId),e.shape.type){case"object":{let i={},o=[];for(let a of[...e.shape.properties??[],...e.shape.extendedProperties??[]])if(KHi(a.valueType,t)){let c=Wd({fieldName:Xt(a.name),typeReference:a.valueType,typeDeclarations:t,currentDepth:0,maxDepth:3,skipOptionalProperties:!0});if(c.type==="failure")continue;o.push({name:a.name,originalTypeDeclaration:e.name,value:c.example,propertyAccess:a.propertyAccess}),i[Xt(a.name)]=c.jsonExample}else if(a.valueType.type==="named"&&!n.has(a.valueType.typeId)){let c=t[a.valueType.typeId];if(c!=null){let u=JHi({typeDeclaration:c,typeDeclarations:t,visitedMinimalTypes:n});u.type==="success"&&(o.push({name:a.name,originalTypeDeclaration:e.name,value:u.example,propertyAccess:a.propertyAccess}),i[Xt(a.name)]=u.jsonExample)}}else if(a.valueType.type==="container"){let{example:c,jsonExample:u}=l7({containerType:a.valueType.container});o.push({name:a.name,originalTypeDeclaration:e.name,value:{jsonExample:u,shape:mo.container(c)},propertyAccess:a.propertyAccess}),i[Xt(a.name)]=u}let s=Qu.object({properties:o,extraProperties:void 0});return{type:"success",example:{jsonExample:i,shape:mo.named({shape:s,typeName:e.name})},jsonExample:i}}case"enum":{let i=e.shape.values[0];if(i==null)return{type:"failure",message:"No enum values present for recursive type stub"};let o=Xt(i.name),s=Qu.enum({value:i.name});return{type:"success",example:{jsonExample:o,shape:mo.named({shape:s,typeName:e.name})},jsonExample:o}}case"alias":{let i=e.shape.aliasOf;if(i.type==="primitive"){let{jsonExample:s,example:a}=HHi({fieldName:void 0,primitiveType:i.primitive});return{type:"success",example:{jsonExample:s,shape:mo.named({shape:Qu.alias({value:{jsonExample:s,shape:mo.primitive(a)}}),typeName:e.name})},jsonExample:s}}if(i.type==="named"){let s=t[i.typeId];if(s!=null&&s.name.typeId!==e.name.typeId)return JHi({typeDeclaration:s,typeDeclarations:t,visitedMinimalTypes:n})}let o={};return{type:"success",example:{jsonExample:o,shape:mo.named({shape:Qu.alias({value:{jsonExample:o,shape:mo.unknown(o)}}),typeName:e.name})},jsonExample:o}}case"union":{let i=e.shape.discriminant;for(let o of e.shape.types)if(o.shape._visit({noProperties:()=>!0,samePropertiesAsObject:()=>!1,singleProperty:()=>!1,_other:()=>!1})){let a={[Xt(i)]:Xt(o.discriminantValue)};return{type:"success",example:{jsonExample:a,shape:mo.named({shape:Qu.union({discriminant:i,singleUnionType:{wireDiscriminantValue:o.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.noProperties()},baseProperties:[],extendProperties:[]}),typeName:e.name})},jsonExample:a}}return{type:"failure",message:`No simple variant available for recursive union ${e.name.typeId}`}}case"undiscriminatedUnion":return{type:"failure",message:`Cannot generate stub for recursive undiscriminated union ${e.name.typeId}`}}}function X2e(e,t){let r=[];for(let n of e){let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;let o=i.example.jsonExample;if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean"){let s=Vr(n.name);r.push({name:n.name,value:{jsonExample:s,shape:mo.primitive(Ci.string({original:s}))}})}else r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function hYe(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&mY({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function YOr(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&mY({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,shape:n.allowMultiple?Wx.exploded():Wx.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var YHi=kr.primitive({v1:fs.String,v2:$n.string({default:void 0,validation:void 0})});function gYe({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:o}){let s={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:gg.ok(vA.body(void 0)),docs:void 0},a=X2e(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;s.endpointPathParameters=a.example;let c=X2e(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;s.servicePathParameters=c.example;let u=X2e(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;s.rootPathParameters=u.example;let l=YOr(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;s.queryParameters=l.example;let p=hYe(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(p.type==="failure")return p;s.endpointHeaders=p.example;let d=hYe(r.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;if(s.serviceHeaders=d.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let f={},m=[];if(t.requestBody.extends!=null)for(let h of t.requestBody.extends){let A=n[h.typeId];if(A==null)throw new Error(`Failed to find extended type declaration with id ${h.typeId}`);let b=Y2e({typeDeclaration:A,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});b!=null&&b.type==="success"&&Object.assign(f,b.jsonExample)}for(let h of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let A=Wd({fieldName:Xt(h.name),typeReference:h.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(A.type==="failure"&&!mY({typeDeclarations:n,typeReference:h.valueType}))return{type:"failure",message:`Failed to generate required property ${Xt(h.name)} b/c ${A.message}`};if(A.type==="failure")continue;let{example:b,jsonExample:v}=A;m.push({name:h.name,originalTypeDeclaration:void 0,value:b}),f[Xt(h.name)]=v}s.request=JT.inlinedRequestBody({jsonExample:f,properties:m,extraProperties:void 0});break}case"reference":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(f.type==="failure")return f;let{example:m}=f;s.request=JT.reference(m);break}default:Ce(t.requestBody)}if(o.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"streamParameter":{let f;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1});break;default:Ce(t.response.body.nonStreamResponse)}if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"streaming":{let f;switch(t.response.body.value.type){case"sse":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f,A=t.response.body.value.payload,b="";if(A.type==="named"){let v=n[A.typeId];if(v?.shape.type==="union"&&v.shape.discriminatorContext===dse.Protocol){let x=v.shape.types[0];x!=null&&(b=Xt(x.discriminantValue))}}s.response=gg.ok(vA.sse([{data:{...m,jsonExample:h},event:b}]));break}case"json":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.stream([{...m,jsonExample:h}]));break}case"text":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.stream([{...m,jsonExample:h}]));break}default:Ce(t.response.body.value)}break}case"text":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1});if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ce(t.response.body)}else if(o.type==="error")if(o.declaration.type==null)s.response=gg.error({body:void 0,error:o.declaration.name});else{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:o.declaration.type,skipOptionalProperties:i});if(f.type==="failure")return f;let{example:m}=f;s.response=gg.error({body:m,error:o.declaration.name})}try{return{type:"success",example:{id:y0e(s),url:e_f(t,s),...s},jsonExample:void 0}}catch(f){return{type:"failure",message:`Parse failure with exceptions ${f}`}}}function e_f(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let o=i.value.jsonExample,s=typeof o=="string"?o:JSON.stringify(o);r[Vr(i.name)]=s});let n=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function XHi({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},o=X2e(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let s=X2e(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;i.pathParameters.push(...s.example);let a=YOr(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(a.type==="failure")return a;i.queryParameters=a.example;let c=hYe(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;i.headers.push(...c.example);let u=hYe(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(u.type==="failure")return u;i.headers.push(...u.example);let p=t.messages.filter(m=>m.origin==="client")[0];if(p!=null){let m=qGa({message:p,typeDeclarations:r,skipOptionalRequestProperties:n});m!=null&&i.messages.push({type:p.type,body:m})}let f=t.messages.filter(m=>m.origin==="server")[0];if(f!=null){let m=qGa({message:f,typeDeclarations:r,skipOptionalRequestProperties:n});m!=null&&i.messages.push({type:f.type,body:m})}return{type:"success",example:{...i,url:t_f(t,i)},jsonExample:void 0}}function qGa({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=Wd({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return qM.reference(n.example)}function t_f(e,t){let r={};[...t.pathParameters].forEach(i=>{let o=i.value.jsonExample,s=typeof o=="string"?o:JSON.stringify(o);r[Vr(i.name)]=s});let n=e.path.head+e.path.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}Wi();Rt();function AYe(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function E0e(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function GGa({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let n=e.types,i={pathParameters:{},queryParameters:{},headers:{}};for(let s of t.pathParameters){let{userExample:a,autoExample:c}=AYe(s.v2Examples);a!==void 0?i.pathParameters[Vr(s.name)]=a:c!==void 0&&(i.pathParameters[Vr(s.name)]=c)}for(let s of t.queryParameters){let{userExample:a,autoExample:c}=AYe(s.v2Examples);if(a!==void 0)i.queryParameters[Vr(s.name)]=a;else if(c!==void 0){if(r&&mY({typeReference:s.valueType,typeDeclarations:n}))continue;i.queryParameters[Vr(s.name)]=c}}let o=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let s of o){let{userExample:a,autoExample:c}=AYe(s.v2Examples);if(a!==void 0)i.headers[Xt(s.name)]=a;else if(c!==void 0){if(r&&mY({typeReference:s.valueType,typeDeclarations:n}))continue;i.headers[Xt(s.name)]=c}}return i}function WGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:o}=GGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s={},a={},c={endpoint:{method:e.method,path:r_f(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:i,headers:o,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}case"inlinedRequestBody":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}case"reference":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}default:Ce(e.requestBody)}return{userRequestExamples:s,autoRequestExamples:a,baseExample:c}}function r_f(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:o}=AYe(n.v2Examples),s=i??o,a;s==null?a=Vr(n.name):a=typeof s=="string"?s:JSON.stringify(s),t[Vr(n.name)]=a});let r=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${t[n.pathParameter]}`)+n.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}Rt();function XOr({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,n={},i={},o={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:o};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...o,body:CC.json(Skt(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:o};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let s=r.body,{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a)){let p=e.source?.type==="openrpc"?Skt(l):l;n[u]={...o,body:CC.json(p)}}for(let[u,l]of Object.entries(c)){let p=e.source?.type==="openrpc"?Skt(l):l;i[u]={...o,body:CC.json(p)}}break}case"json":{let s=r.body.value;if(s.type==="response"){let{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a)){let p=e.source?.type==="openrpc"?Skt(l):l;n[u]={...o,body:CC.json(p)}}for(let[u,l]of Object.entries(c)){let p=e.source?.type==="openrpc"?Skt(l):l;i[u]={...o,body:CC.json(p)}}}break}case"streaming":{let s=r.body.value;if(s.type==="json"){let{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a))n[u]={...o,body:CC.stream([l])};for(let[u,l]of Object.entries(c))i[u]={...o,body:CC.stream([l])}}break}case"streamParameter":break;default:Ce(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:o}}function Skt(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var yYe=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},n_f=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function ZOr({key:e,displayName:t,request:r,response:n,exampleStore:i,userOrAutoStore:o}){if(!i.has(e)){let s={displayName:t,request:r,response:n,codeSamples:void 0};return o[e]=s,n_f({exampleStore:i,key:e,example:s}),!0}return!1}function $Ga({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let n={},i={},o=new Map,{userRequestExamples:s,autoRequestExamples:a,baseExample:c}=WGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u=Object.keys(s)[0],l=Object.values(s)[0],p=Object.keys(a)[0],d=Object.values(a)[0],f=i_f({endpoint:e,userRequestExamples:s,baseRequestExample:c,firstUserRequestName:u,firstUserRequestExample:l,firstAutoRequestName:p,firstAutoRequestExample:d,userResults:n,autoResults:i,exampleStore:o});if(o_f({endpoint:e,userRequestExamples:s,requestExamplesUsed:f,userResults:n,exampleStore:o}),Object.keys(n).length===0&&Object.keys(i).length===0){let{baseExample:m}=XOr({endpoint:e}),h=yYe(p??"base","base",void 0);ZOr({key:h,displayName:p??"base",request:d??c,response:m,exampleStore:o,userOrAutoStore:i})}return{userFullExamples:n,autoFullExamples:i}}function i_f({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:n,firstUserRequestExample:i,firstAutoRequestName:o,firstAutoRequestExample:s,userResults:a,autoResults:c,exampleStore:u}){let l=e.v2Responses?.responses??[e.response],p=new Set;for(let d of l){let f=!1,{userResponseExamples:m,autoResponseExamples:h,baseExample:A}=XOr({endpoint:e,responseObject:d}),b=Object.keys(h)[0],v=Object.values(h)[0];for(let[x,C]of Object.entries(m)){let w,B;t[x]?(B=t[x],p.add(x),w=yYe(x,x,d?.statusCode)):s&&o?(B=s,w=yYe(o,x,d?.statusCode)):(B=r,w=yYe("base",x,d?.statusCode)),ZOr({key:w,displayName:x,request:B,response:C,exampleStore:u,userOrAutoStore:a})&&(f=!0)}if(!f){let x=Wn(`${Vr(e.name)}_example`);n&&i&&p.add(n);let C=yYe(n??o??"base",b??"base",d?.statusCode);ZOr({key:C,displayName:n??o??x,request:i??s??r,response:v??A,exampleStore:u,userOrAutoStore:c})&&(f=!0)}}return p}function o_f({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:o,autoResponseExamples:s,baseExample:a}=XOr({endpoint:e}),c=Object.values(o)[0],u=Object.keys(o)[0],l=Object.keys(s)[0],p=Object.values(s)[0],d=Object.entries(t).filter(([f])=>!r.has(f));for(let[f,m]of d){let h=yYe(f,u??l??"base",c?c.statusCode:p?p.statusCode:a.statusCode);ZOr({key:h,displayName:f,request:m,response:c??p??a,exampleStore:i,userOrAutoStore:n})}}function _kt({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let o of i.endpoints){let s=[];if(o.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let a=gYe({ir:e,service:i,endpoint:o,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});a.type==="success"&&s.push({example:a.example})}if(o.userSpecifiedExamples.filter(a=>a.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let a of o.errors){let c=e.errors[a.error.errorId];if(!c)continue;let u=gYe({ir:e,service:i,endpoint:o,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:c}});u.type==="success"&&s.push({example:u.example})}o.autogeneratedExamples=s}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let o=XHi({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(o.type==="failure")continue;let{example:s}=o;i.examples=[...i.examples,s]}return e}function ZHi({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let o of i.endpoints){o.v2Examples==null&&(o.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:s,autoFullExamples:a}=$Ga({endpoint:o,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(o.v2Examples.userSpecifiedExamples).length>0){if(Object.values(o.v2Examples.userSpecifiedExamples).some(u=>u.request!=null||u.response!=null))continue;let c=Object.values(o.v2Examples.userSpecifiedExamples).filter(u=>u!=null).flatMap(u=>u.codeSamples??[]);for(let[u,l]of Object.entries(a))a[u]={...l,codeSamples:c};for(let[u,l]of Object.entries(s))s[u]={...l,codeSamples:c}}o.v2Examples.autogeneratedExamples=a,o.v2Examples.userSpecifiedExamples=s}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let o=XHi({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(o.type==="failure")continue;let{example:s}=o;i.examples=[...i.examples,s]}return e}Wi();Rt();function KGa({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,Xt(i.name))).map(i=>({...i,value:oE({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Yt.ExampleSingleUnionTypeProperties.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=oE({filteredIr:e,exampleTypeReference:r});return n!==void 0?Yt.ExampleSingleUnionTypeProperties.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function oE({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:mo.container(hl.list({...n,list:n.list.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:mo.container(hl.set({...n,set:n.set.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?oE({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:mo.container(hl.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?oE({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:mo.container(hl.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:mo.container(hl.map({...n,map:n.map.map(i=>{let o=oE({filteredIr:e,exampleTypeReference:i.key}),s=oE({filteredIr:e,exampleTypeReference:i.value});return o!==void 0&&s!==void 0?{key:o,value:s}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=oE({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:mo.named({...r,shape:Qu.enum(n)})}),object:n=>({...t,shape:mo.named({...r,shape:Qu.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,Xt(i.name))).map(i=>({...i,value:oE({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=KGa({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=oE({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function eKi({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function s_f({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function HGa({filteredIr:e,headers:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function a_f({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,Xt(n.name)):!0).map(n=>{let i=oE({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=oE({filteredIr:e,exampleTypeReference:r});return n!==void 0?JT.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function c_f({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>gg.ok(vA.body(n!=null?oE({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>gg.ok(vA.stream(n.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(Ra))),sse:n=>gg.ok(vA.sse(n.map(({event:i,data:o})=>{let s=oE({filteredIr:e,exampleTypeReference:o});return s!==void 0?{event:i,data:s}:void 0}).filter(Ra))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>gg.error({error:r,body:n!=null?oE({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function tKi({filteredIr:e,example:t}){return{...t,rootPathParameters:eKi({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:eKi({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:eKi({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:HGa({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:HGa({filteredIr:e,headers:t.endpointHeaders}),queryParameters:s_f({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?a_f({filteredIr:e,requestBody:t.request}):void 0,response:c_f({filteredIr:e,response:t.response})}}function JGa({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:Qu.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:Qu.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,Xt(n.name))).map(n=>({...n,value:oE({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=KGa({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:Qu.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=oE({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:Qu.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function rKi(e,t){if(t==null)return e;let r=BPe(e.types,a=>t.hasType(a)),n=Object.fromEntries(Object.entries(r).map(([a,c])=>{let u=[];if(c.userProvidedExamples=c.userProvidedExamples.map(l=>JGa({filteredIr:t,exampleType:l})).filter(l=>l!==void 0),c.shape.type==="object"){for(let l of c.shape.properties)t.hasProperty(a,Xt(l.name))&&u.push(l);return[a,{...c,shape:vc.object({...c.shape,properties:u})}]}return[a,c]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([a,c])=>{let u=c.filter(l=>t.hasWebhook(l)).map(l=>{let p=l.id;return l.payload.type==="inlinedPayload"&&p!=null&&(l.payload={...l.payload,properties:l.payload.properties.filter(d=>t.hasWebhookPayloadProperty(p,Xt(d.name)))}),l});return[a,u]})),o=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([a])=>t.hasChannel(a)).map(([a,c])=>[a,{...c}])):{},s=e.environments;if(s){switch(s.environments.type){case"singleBaseUrl":{s.environments.environments=s.environments.environments.filter(a=>t.hasEnvironmentId(a.id));break}case"multipleBaseUrls":{s.environments.environments=s.environments.environments.filter(a=>t.hasEnvironmentId(a.id));break}}s.defaultEnvironment&&(t.hasEnvironmentId(s.defaultEnvironment)||(s.defaultEnvironment=void 0))}return{...e,environments:s,types:n,errors:BPe(e.errors,a=>t.hasError(a)),services:ep(BPe(e.services,a=>t.hasService(a)),a=>({...a,endpoints:a.endpoints.filter(c=>t.hasEndpoint(c)).map(c=>(c.autogeneratedExamples=c.autogeneratedExamples.map(u=>({...u,example:tKi({filteredIr:t,example:u.example})})),c.userSpecifiedExamples=c.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?tKi({filteredIr:t,example:u.example}):void 0})),c.queryParameters.length>0&&(c.queryParameters=c.queryParameters.filter(u=>t.hasQueryParameter(c.id,Xt(u.name)))),c.requestBody?.type==="inlinedRequestBody"?{...c,requestBody:{...c.requestBody,properties:c.requestBody.properties.filter(u=>t.hasRequestProperty(c.id,Xt(u.name)))}}:c))})),websocketChannels:o,webhookGroups:i,serviceTypeReferenceInfo:u_f(e.serviceTypeReferenceInfo,t)}}function u_f(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(o=>t.hasTypeId(o)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}function Z2e(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}Rt();function h6(e){return e.allParts.map(t=>Vr(t)).join("/")}var Kl={generateTypeId:e=>`type_${h6(e.fernFilepath)}:${Vr(e.name)}`,generateErrorId:e=>`error_${h6(e.fernFilepath)}:${Vr(e.name)}`,generateServiceId:e=>`service_${h6(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${h6(e)}`,generateSubpackageId:e=>`subpackage_${h6(e)}`,generateEndpointId:(e,t)=>{let r=h6(e.fernFilepath),n=Vr(t.name);return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${h6(e)}`,generateWebhookId:(e,t)=>`webhooks_${h6(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${h6(e)}`};function bYe(e){return e.type!=null}var ePr=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:o,endpoints:s,webhooks:a,subpackages:c,queryParameters:u,requestProperties:l,webhookPayloadProperties:p,channels:d}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=o,this.endpoints=s,this.webhooks=a,this.webhookPayloadProperties=p,this.subpackages=c,this.requestProperties=l,this.queryParameters=u,this.channels=d}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Kl.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=Kl.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Kl.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var eNe=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=l_f(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:o}){let s=Kl.generateTypeId(t),a={typeId:s,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[s]=a,this.typesReferencedByService[s]==null&&(this.typesReferencedByService[s]=new Set),this.properties[s]={typeId:s,propertiesByAudience:o}}markTypeForAudiences(t,r){let n=Kl.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Kl.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&sb(t.type,n,i);let o={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=o}addEndpoint(t,r,n){let i=Kl.generateServiceId(t.name),o=r.id,s=new Set,a=new Set,c=new Set;for(let u of[...t.headers,...r.headers])sb(u.valueType,s,c);for(let u of[...t.pathParameters,...r.pathParameters])sb(u.valueType,s,c);for(let u of r.queryParameters)sb(u.valueType,s,c);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=Z2e(n.request["query-parameters"]??{});this.queryParameters[o]={endpointId:o,parametersByAudience:u}}r.requestBody!=null&&fd._visit(r.requestBody,{inlinedRequestBody:u=>{for(let l of u.extends)tPr(l,s,c);for(let l of u.properties)sb(l.valueType,s,c);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&hg(n.request.body)){let l=Z2e(n.request.body.properties??{});this.requestProperties[o]={endpointId:o,propertiesByAudience:l}}},reference:({requestBodyType:u})=>{sb(u,s,c)},fileUpload:({properties:u})=>{for(let l of u)xC._visit(l,{file:yt,bodyProperty:({valueType:p})=>{sb(p,s,c)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+l.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&yu._visit(r.response.body,{fileDownload:yt,json:u=>{sb(u.responseBodyType,s,c)},streaming:u=>{u._visit({sse:l=>sb(l.payload,s,c),json:l=>sb(l.payload,s,c),text:yt,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:l=>sb(l.payload,s,c),json:l=>sb(l.payload,s,c),text:yt,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&sb(u.nonStreamResponse.value.responseBodyType,s,c)},text:yt,bytes:yt,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{a.add(Kl.generateErrorId(u.error)),c.add(u.error.fernFilepath)}),this.endpoints[o]={endpointId:o,serviceId:i,referencedTypes:s,referencedErrors:a,referencedSubpackages:c}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=Kl.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(o=>{let s=o.id;this.endpointsNeededForAudience.add(s),this.endpoints[s]?.referencedSubpackages.forEach(a=>{this.addSubpackages(a)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,n){let i=r.id;if(i==null)return;let o=new Set,s=new Set;r.payload!=null&&lS._visit(r.payload,{inlinedPayload:a=>{for(let c of a.extends)tPr(c,o,s);for(let c of a.properties)sb(c.valueType,o,s);if(n?.payload!=null&&typeof n.payload=="object"&&!bYe(n.payload)){let c=Z2e(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:c}}},reference:({payloadType:a})=>{sb(a,o,s)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),s.add(t),this.webhooks[i]={webhookId:i,referencedTypes:o,referencedSubpackages:s}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t))}addChannel(t,r,n,i){if(r==null)return;let o=new Set,s=new Set;for(let a of n.messages)Z1._visit(a.body,{reference:({bodyType:c})=>{sb(c,o,s)},inlinedBody:c=>{for(let u of c.extends)tPr(u,o,s);for(let u of c.properties)sb(u.valueType,o,s)},_other:()=>{}});for(let a of n.queryParameters)sb(a.valueType,o,s);s.add(t),this.channels[r]={channelId:r,referencedTypes:o,referencedSubpackages:s}}markChannelForAudiences(t,r,n){r!=null&&this.hasAudience(n)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let a of this.endpointsNeededForAudience.keys()){let c=this.getEndpointNode(a);for(let u of c.referencedErrors){if(r.has(u))continue;r.add(u);let l=this.getErrorNode(u);this.addReferencedTypes(t,l.referencedTypes)}this.addReferencedTypes(t,c.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let a of this.webhooksNeededForAudience.keys()){let c=this.getWebhookNode(a);this.addReferencedTypes(t,c.referencedTypes)}for(let a of this.channelsNeededForAudience.keys()){let c=this.getChannelNode(a);this.addReferencedTypes(t,c.referencedTypes)}let n={},i={},o={},s={};if(this.audiences.type==="filtered"){for(let[a,c]of Object.entries(this.properties)){if(!t.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}u.size>0&&(n[a]=u),n[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}i[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.parametersByAudience[l];p?.forEach(d=>{u.add(d)})}o[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}s[a]=u.size>0?u:void 0}}return new ePr({types:t,properties:n,errors:r,requestProperties:i,queryParameters:o,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:s,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t]??=new Set;if(n.has(r))return;n.add(r);let i=this.getTypeNode(t);for(let o of i.allDescendants)this.markTypeForService(o,r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let o of this.audiences.audiences){let s=i.descendantsByAudience[o];if(s!=null)s.forEach(a=>{t.add(a)});else{i.allDescendants.forEach(a=>{t.add(a)});break}}else i.allDescendants.forEach(o=>{t.add(o)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:Ce(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Kl.generateSubpackageId(n))}}};function l_f(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ce(e)}}function sb(e,t,r){kr._visit(e,{container:n=>{p_f(n,t,r)},named:n=>{tPr(n,t,r)},primitive:yt,unknown:yt,_other:yt})}function tPr(e,t,r){t.add(Kl.generateTypeId(e)),r.add(e.fernFilepath)}function p_f(e,t,r){Qs._visit(e,{list:n=>{sb(n,t,r)},map:n=>{sb(n.keyType,t,r),sb(n.valueType,t,r)},optional:n=>{sb(n,t,r)},nullable:n=>{sb(n,t,r)},set:n=>{sb(n,t,r)},literal:yt,_other:yt})}Rt();var f_f=[Yt.AvailabilityStatus.GeneralAvailability];function Vce(e){return e!=null&&!f_f.includes(e.status)}var nKi=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},Bkt=class{errors;constructor(){this.errors=new nKi}async check({from:t,to:r}){let n=this.toInternalIr(t),i=this.toInternalIr(r),o=y0e(n),s=y0e(i);if(o===s)return{bump:"no_change",isBreaking:!1,errors:[]};let a=this.checkBreaking({from:n,to:i});return{bump:a.isBreaking?"major":"minor",isBreaking:a.isBreaking,errors:a.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let n=this.errors.hasErrors();return{bump:n?"major":"minor",isBreaking:n,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(Vce(i.availability))continue;let o=r[n];if(!o){this.errors.add(`Type "${n}" was removed.`);continue}if(Vce(o.availability)){this.errors.add(`Type "${n}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:i,to:o})||this.errors.add(`Type "${n}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){let o=Object.values(r).find(s=>s.name.errorId===i.name.errorId);if(!o){this.errors.add(`Error "${i.name.errorId}" with status code "${i.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:i,to:o})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(Vce(i.availability)||(i.endpoints?.every(s=>Vce(s.availability))??!1))continue;let o=r[n];if(!o){this.errors.add(`Service "${n}" was removed.`);continue}if(Vce(o.availability)){this.errors.add(`Service "${n}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:n,from:i,to:o})}}checkServiceBreakingChanges({id:t,from:r,to:n}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:n})}checkEndpointsBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.endpoints.map(s=>[s.id,s])),o=Object.fromEntries(n.endpoints.map(s=>[s.id,s]));for(let[s,a]of Object.entries(i)){if(Vce(a.availability))continue;let c=o[s];if(!c){this.errors.add(`Endpoint "${s}" was removed.`);continue}if(Vce(c.availability)){this.errors.add(`Endpoint "${s}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:s,from:a,to:c})}}checkEndpointBreakingChanges({id:t,from:r,to:n}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:n.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:n.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:n.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:n.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),r.requestBody!=null&&(n.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:n.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(n.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:n.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&n.pagination==null||r.pagination==null&&n.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Vr(s.name),s])),o=Object.fromEntries(n.map(s=>[Vr(s.name),s]));for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Path parameter "${s}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Path parameter "${s}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Xt(s.name),s])),o=Object.fromEntries(n.map(s=>[Xt(s.name),s]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([s,a])=>[s,a.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,a])=>[s,a.valueType]))});for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Query parameter "${s}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Query parameter "${s}" type changed in endpoint "${t}".`),a.allowMultiple!==c.allowMultiple&&this.errors.add(`Query parameter "${s}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Xt(s.name),s])),o=Object.fromEntries(n.map(s=>[Xt(s.name),s]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([s,a])=>[s,a.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,a])=>[s,a.valueType]))});for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Header "${s}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Header "${s}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:n}){r!==n&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:n}){this.areHttpPathsCompatible({from:r,to:n})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let n=0;n<t.parts.length;n++){let i=t.parts[n];if(i==null)return!1;let o=r.parts[n];if(o==null||i.pathParameter!==o.pathParameter||i.tail!==o.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:n}){switch(r.type){case"inlinedRequestBody":if(n.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:n}))return;break;case"reference":if(n.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:n}))return;break;case"fileUpload":if(n.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:n}))return;break;case"bytes":if(n.type==="bytes")return;break;default:Ce(r)}this.errors.add(`Request body type changed from "${r.type}" to "${n.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let n=this.getInlinedRequestBody(t),i=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:n,to:i}),Object.entries(n).every(([o,s])=>{let a=i[o];return a?this.areTypeReferencesCompatible({from:s,to:a}):(this.errors.add(`Request body property "${o}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let n=this.getFileUploadRequest(t.properties),i=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:n,to:i});for(let[o,s]of Object.entries(n)){let a=i[o];if(!a)return this.errors.add(`File upload property "${o}" was removed.`),!1;if(s==="file"&&a!=="file")return this.errors.add(`File upload property "${o}" type changed.`),!1;if(s==="fileArray"&&a!=="fileArray")return this.errors.add(`File upload property "${o}" type changed.`),!1;if(s!=="file"&&s!=="fileArray"&&a!=="file"&&a!=="fileArray"&&!this.areTypeReferencesCompatible({from:s,to:a}))return this.errors.add(`File upload property "${o}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:n}){if(r.statusCode!==n.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${n.statusCode}".`),!(r.body==null&&n.body==null)){if(r.body==null||n.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(n.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"fileDownload":if(n.body.type==="fileDownload")return;break;case"text":if(n.body.type==="text")return;break;case"bytes":if(n.body.type==="bytes")return;break;case"streaming":if(n.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"streamParameter":if(n.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:n.body.streamResponse});return}break;default:Ce(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${n.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ce(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return Vce(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ce(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let n=Object.fromEntries(t.values.map(o=>[Xt(o.name),o])),i=Object.fromEntries(r.values.map(o=>[Xt(o.name),o]));return Object.keys(n).length!==Object.keys(i).length?!1:Object.values(n).every(o=>{let s=i[Xt(o.name)];return s?this.areNameAndWireValuesCompatible({from:o.name,to:s.name}):(this.errors.add(`Enum value "${Xt(o.name)}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let n=Object.fromEntries([...t.properties.map(o=>[Xt(o.name),o]),...t.extendedProperties?.map(o=>[Xt(o.name),o])??[]]),i=Object.fromEntries([...r.properties.map(o=>[Xt(o.name),o]),...r.extendedProperties?.map(o=>[Xt(o.name),o])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,s])=>[o,s.valueType])),to:Object.fromEntries(Object.entries(i).map(([o,s])=>[o,s.valueType]))}),Object.values(n).every(o=>{let s=i[Xt(o.name)];return s?this.areObjectPropertiesCompatible({from:o,to:s}):(this.errors.add(`Object property "${Xt(o.name)}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${Xt(t.discriminant)}" changed.`),!1;let n=new Set(t.extends.map(u=>this.getKeyForDeclaration(u))),i=new Set(r.extends.map(u=>this.getKeyForDeclaration(u)));for(let u of n)if(!i.has(u))return this.errors.add(`Extended type "${u}" was removed.`),!1;let o=Object.fromEntries(t.baseProperties.map(u=>[Xt(u.name),u])),s=Object.fromEntries(r.baseProperties.map(u=>[Xt(u.name),u]));for(let u of Object.values(o)){let l=s[Xt(u.name)];if(!l)return this.errors.add(`Union type with discriminant value "${Xt(u.name)}" no longer has a property named "${Xt(u.name)}".`),!1;if(!this.areObjectPropertiesCompatible({from:u,to:l}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(o).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(s).map(([u,l])=>[u,l.valueType]))});let a=Object.fromEntries(t.types.map(u=>[Xt(u.discriminantValue),u])),c=Object.fromEntries(r.types.map(u=>[Xt(u.discriminantValue),u]));return Object.values(a).every(u=>{let l=c[Xt(u.discriminantValue)];return l?this.areSingleUnionTypesCompatible({from:u.shape,to:l.shape}):(this.errors.add(`Union type for discriminant value "${Xt(u.discriminantValue)}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ce(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((n,i)=>{let o=r.members[i];return o?this.areTypeReferencesCompatible({from:n.type,to:o.type}):(this.errors.add(`Undiscriminated union member at index ${i} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||i==="file"||i==="fileArray"||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ce(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ce(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:JOr(t),to:JOr(r)})&&Xt(t)===Xt(r)}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ce(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((n,i)=>{let o=r.allParts[i];return o==null?!1:this.areNamesCompatible({from:n,to:o})})}areNamesCompatible({from:t,to:r}){return Vr(t)===Vr(r)}getInlinedRequestBody(t){let r={};for(let n of[...t.extendedProperties??[],...t.properties])r[Xt(n.name)]=n.valueType;return r}getFileUploadRequest(t){let r={};for(let n of t)switch(n.type){case"file":r[Xt(n.value.key)]="file";break;case"bodyProperty":r[Xt(n.name)]=n.valueType;break;default:Ce(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>Vr(i)).join(".")}.${Vr(t)}`}};function tNe(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:o}=m_f(e.environments,t.environments,r),{services:s,websocketChannels:a}=h_f(e,t,i,o);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:XGa([...e.headers??[],...t.headers??[]]),environments:n,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:s,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:d_f(e.subpackages,t.subpackages),websocketChannels:a,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(c=>!e.rootPackage.subpackages?.includes(c))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:XGa([...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]]),pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]],generationMetadata:e.generationMetadata??t.generationMetadata,apiPlayground:e.apiPlayground??t.apiPlayground,casingsConfig:e.casingsConfig??t.casingsConfig}}function d_f(e,t){let r=e;for(let[n,i]of Object.entries(t))r[n]==null?r[n]=i:r[n]={name:i.name,displayName:i.displayName,fernFilepath:i.fernFilepath,hasEndpointsInTree:r[n].hasEndpointsInTree||i.hasEndpointsInTree,navigationConfig:r[n].navigationConfig??i.navigationConfig,docs:r[n].docs??i.docs,service:r[n].service??i.service,subpackages:[...r[n].subpackages??[],...(i.subpackages??[]).filter(o=>!r[n]?.subpackages?.includes(o))],webhooks:r[n].webhooks??i.webhooks,websocket:r[n].websocket??i.websocket,errors:[...r[n].errors??[],...i.errors??[]],types:[...r[n].types??[],...i.types??[]]};return r}function m_f(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let n=YGa(e),i=YGa(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:q0.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let o=n?t.defaultEnvironment:e.defaultEnvironment,s=e.environments,a=t.environments;if(s.type==="singleBaseUrl"&&a.type==="singleBaseUrl"){let c=n?a:s,u=n?s:a,l={},{deconflictedEnvironments2:p,changedBaseUrlIds2:d}=g_f(c,u,r);if(c.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let f="Base",m=r.generateName("Base");return c.environments.forEach(h=>{l[h.id]=f}),{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[{id:f,name:m},...p.environments.map(h=>({id:h.id,name:h.name}))],environments:c.environments.map(h=>({id:h.id,name:h.name,urls:{[f]:h.url,...Object.fromEntries(p.environments.map(A=>[A.id,A.url]))},docs:void 0,audiences:h.audiences,defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}))})},changedBaseUrlIds1:n?d:l,changedBaseUrlIds2:n?l:d}}if(s.type==="multipleBaseUrls"&&a.type==="singleBaseUrl"||s.type==="singleBaseUrl"&&a.type==="multipleBaseUrls"){let c=s.type==="singleBaseUrl"?s:a,u=s.type==="multipleBaseUrls"?s:a,{deconflictedEnvironments1:l,changedBaseUrlIds1:p}=A_f(c,u,r);return{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[...u.baseUrls,...l.environments.map(d=>({id:d.id,name:d.name}))],environments:u.environments.map(d=>({...d,urls:{...d.urls,...Object.fromEntries(l.environments.map(f=>[f.id,f.url]))}}))})},changedBaseUrlIds1:s.type==="singleBaseUrl"?p:void 0,changedBaseUrlIds2:s.type==="singleBaseUrl"?void 0:p}}if(s.type==="multipleBaseUrls"&&a.type==="multipleBaseUrls"){let{deconflictedEnvironments:c,changedBaseUrlIds:u}=y_f(s,a,r);return{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[...s.baseUrls,...c.baseUrls],environments:s.environments.flatMap(l=>c.environments.map(p=>({...l,urls:{...l.urls,...p.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:u}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function h_f(e,t,r,n){if(r!=null)for(let[s,a]of Object.entries(r)){for(let c of Object.values(e.services))for(let u of Object.values(c.endpoints))u.baseUrl==s&&(u.baseUrl=a),u.v2BaseUrls?.includes(s)&&(u.v2BaseUrls=u.v2BaseUrls.map(l=>l===s?a:l));for(let c of Object.values(e.websocketChannels??{}))c.baseUrl==s&&(c.baseUrl=a)}if(n!=null)for(let[s,a]of Object.entries(n)){for(let c of Object.values(t.services))for(let u of Object.values(c.endpoints))u.baseUrl==s&&(u.baseUrl=a),u.v2BaseUrls?.includes(s)&&(u.v2BaseUrls=u.v2BaseUrls.map(l=>l===s?a:l));for(let c of Object.values(t.websocketChannels??{}))c.baseUrl==s&&(c.baseUrl=a)}let i=e.services;for(let[s,a]of Object.entries(t.services))i[s]==null?i[s]=a:i[s]={availability:a.availability,name:a.name,displayName:a.displayName,basePath:a.basePath,endpoints:[...i[s].endpoints??[],...a.endpoints],pathParameters:[...i[s].pathParameters??[],...a.pathParameters??[]],headers:[...i[s].headers??[],...a.headers??[]],encoding:a.encoding,transport:a.transport,audiences:[...i[s].audiences??[],...a.audiences??[]]};let o={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:i,websocketChannels:o}}function g_f(e,t,r){let n={},i=new Set(e.environments.map(u=>u.id)),o=new Set(e.environments.map(u=>u.name)),s=new Map(e.environments.map(u=>[u.url,u.id])),a=t.environments.filter(u=>{let l=s.get(u.url);return l!=null?(n[u.id]=l,!1):!0}).map(u=>{if(i.has(u.id)||o.has(u.name)){let l=iKi(u.id,i);return n[u.id]=l,{...u,id:l,name:r.generateName(l)}}return u});return{deconflictedEnvironments2:q0.singleBaseUrl({environments:a}),changedBaseUrlIds2:n}}function A_f(e,t,r){let n={},i=new Set(t.baseUrls.map(c=>c.id)),o=new Set(t.baseUrls.map(c=>c.name)),s=e.environments.map(c=>{if(i.has(c.id)||o.has(c.name)){let u=iKi(c.id,i);return n[c.id]=u,{...c,id:u,name:r.generateName(u)}}return c});return{deconflictedEnvironments1:q0.singleBaseUrl({environments:s}),changedBaseUrlIds1:n}}function y_f(e,t,r){let n={},i=new Set(e.baseUrls.map(u=>u.id)),o=new Set(e.baseUrls.map(u=>u.name)),s=t.baseUrls.map(u=>{if(i.has(u.id)||o.has(u.name)){let l=iKi(u.id,i);return n[u.id]=l,{...u,id:l,name:r.generateName(l)}}return u}),a=t.environments.map(u=>({...u,urls:Object.fromEntries(Object.entries(u.urls).map(([l,p])=>[n[l]??l,p]))}));return{deconflictedEnvironments:q0.multipleBaseUrls({baseUrls:s,environments:a}),changedBaseUrlIds:n}}function YGa(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function XGa(e){let t=new Set;return e.filter(r=>{let n=Xt(r.name).toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function iKi(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}YA();function bN({relativeFilepath:e,casingsGenerator:t}){let r=M3(e),n=qT(e,{stripExtension:!0}),i=r==="."?[]:r.split("/").map(a=>t.generateName(a)),o=n!==TDe?t.generateName(n):void 0,s=[];return s.push(...i),o!=null&&s.push(o),{allParts:s,packagePath:i,file:o}}YA();function I0e({referencedIn:e,importPath:t}){return YE(M3(e),t)}function g6({reference:e,referencedIn:t,imports:r}){let[n,i,...o]=e.split(".");if(n==null||o.length>0)return;if(i==null)return{typeName:n,relativeFilepath:t};let a=r[n];if(a!=null)return{relativeFilepath:I0e({referencedIn:t,importPath:a}),typeName:i}}function JS({typeName:e,file:t}){let r=g6({reference:e,referencedIn:t.relativeFilepath,imports:t.imports});if(r==null)throw new j({message:"Failed to locate type: "+e,code:j.Code.ResolutionError});let n={name:t.casingsGenerator.generateName(r.typeName),fernFilepath:bN({relativeFilepath:r.relativeFilepath,casingsGenerator:t.casingsGenerator}),displayName:void 0};return{...n,typeId:Kl.generateTypeId(n)}}Rt();function Tkt(e){if(e!=null)return e=e.replace(/\*\//g,"* /"),e.endsWith(`
|
|
1587
|
+
Example: package-name: "@scope/package"`)}t.failAndThrow(a,void 0,{code:j.Code.ConfigError})}else throw o}}async function m6({absolutePathToWorkspace:e,context:t,lenient:r}){let n=await fYe({absolutePathToWorkspace:e,context:t,lenient:r});if(n==null)return;let i=await A0e({absolutePathToWorkspace:e});if(i!=null)return IGa({absolutePathToGeneratorsConfiguration:i,rawGeneratorsConfiguration:n,context:t})}async function A0e({absolutePathToWorkspace:e}){let t=$e(e,Te.of(nf)),r=$e(e,Te.of(LGe));if(await cr(t))return t;if(await cr(r))return r}Jt();var dYe=Ie(require("path"),1),FGa=require("url");var TGa=Ie(require("process"),1),OGa=Ie(require("path"),1),qOr=Ie(require("fs"),1),PGa=require("url");var jHi=class{value;next;constructor(t){this.value=t}},vkt=class{#e;#t;#r;constructor(){this.clear()}enqueue(t){let r=new jHi(t);this.#e?(this.#t.next=r,this.#t=r):(this.#e=r,this.#t=r),this.#r++}dequeue(){let t=this.#e;if(t)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),t.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let t=this.#e;for(;t;)yield t.value,t=t.next}*drain(){for(;this.#e;)yield this.dequeue()}};function zOr(e){if(!((Number.isInteger(e)||e===Number.POSITIVE_INFINITY)&&e>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let t=new vkt,r=0,n=()=>{r--,t.size>0&&t.dequeue()()},i=async(a,c,u)=>{r++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},o=(a,c,u)=>{t.enqueue(i.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),r<e&&t.size>0&&t.dequeue()()))()},s=(a,...c)=>new Promise(u=>{o(a,u,c)});return Object.defineProperties(s,{activeCount:{get:()=>r},pendingCount:{get:()=>t.size},clearQueue:{value:()=>{t.clear()}}}),s}var VOr=class extends Error{constructor(t){super(),this.value=t}},vSf=async(e,t)=>t(await e),CSf=async e=>{let t=await Promise.all(e);if(t[1]===!0)throw new VOr(t[0]);return!1};async function MHi(e,t,{concurrency:r=Number.POSITIVE_INFINITY,preserveOrder:n=!0}={}){let i=zOr(r),o=[...e].map(a=>[a,i(vSf,a,t)]),s=zOr(n?1:Number.POSITIVE_INFINITY);try{await Promise.all(o.map(a=>s(CSf,a)))}catch(a){if(a instanceof VOr)return a.value;throw a}}var DGa={directory:"isDirectory",file:"isFile"};function xSf(e){if(!Object.hasOwnProperty.call(DGa,e))throw new Error(`Invalid type specified: ${e}`)}var wSf=(e,t)=>t[DGa[e]](),SSf=e=>e instanceof URL?(0,PGa.fileURLToPath)(e):e;async function LHi(e,{cwd:t=TGa.default.cwd(),type:r="file",allowSymlinks:n=!0,concurrency:i,preserveOrder:o}={}){xSf(r),t=SSf(t);let s=n?qOr.promises.stat:qOr.promises.lstat;return MHi(e,async a=>{try{let c=await s(OGa.default.resolve(t,a));return wSf(r,c)}catch{return!1}},{concurrency:i,preserveOrder:o})}var RGa=Ie(require("fs"),1);var _Sf=e=>e instanceof URL?(0,FGa.fileURLToPath)(e):e,BSf=Symbol("findUpStop");async function TSf(e,t={}){let r=dYe.default.resolve(_Sf(t.cwd)||""),{root:n}=dYe.default.parse(r),i=dYe.default.resolve(r,t.stopAt||n),o=t.limit||Number.POSITIVE_INFINITY,s=[e].flat(),a=async u=>{if(typeof e!="function")return LHi(s,u);let l=await e(u.cwd);return typeof l=="string"?LHi([l],u):l},c=[];for(;;){let u=await a({...t,cwd:r});if(u===BSf||(u&&c.push(dYe.default.resolve(r,u)),r===i||c.length>=o))break;r=dYe.default.dirname(r)}return c}async function bd(e,t={}){return(await TSf(e,{...t,limit:1}))[0]}async function FA(e){let t=await bd(e??xA,{type:"directory"});if(t==null)return;let r=$t.of(t);if(await cr($e(r,Te.of(tI))))return r}Jt();function kGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.definitionFile?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("webhookSignature"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function NGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.packageMarker?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("export"),...i("navigation")}}function QGa({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=(a,c)=>{for(let{name:u,visitors:l}of r){let p=l.rootApiFile?.[o];if(p!=null){let d=p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:u,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}var UHi={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(nDe(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&hg(e.request.body)){let r=[];for(let[n,i]of Object.entries(e.request.body.properties??{}))typeof i!="string"&&i["content-type"]!=null&&r.push({severity:"fatal",message:`${n} has content-type, but the request is not multipart`});return r}return[]}}})};Wi();function Ckt({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:Gx.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return sDe(e.auth,{single:n=>{let i=jGa({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:Gx.All,schemes:[i]}},any:({any:n})=>({docs:r,requirement:Gx.Any,schemes:n.map(i=>jGa({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))}),endpointSecurity:()=>({docs:r,requirement:Gx.EndpointSecurity,schemes:[]})})}function jGa({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let n=(o,s)=>{let a=t?.[o];if(a==null)throw new Error("Unknown auth scheme: "+o);return aDe(a,{header:c=>Gp.header({key:o,docs:s,name:r.generateNameAndWireValue({name:c.name??o,wireValue:c.header}),valueType:kr.primitive({v1:fs.String,v2:$n.string({default:void 0,validation:void 0})}),prefix:c.prefix,headerEnvVar:c.env}),basic:c=>MGa({key:o,casingsGenerator:r,docs:s,rawScheme:c}),tokenBearer:c=>GOr({key:o,casingsGenerator:r,docs:s,rawScheme:c}),inferredBearer(c){return GOr({key:o,casingsGenerator:r,docs:s,rawScheme:void 0})},oauth:c=>GOr({key:o,casingsGenerator:r,docs:s,rawScheme:void 0})})},i=typeof e=="string"?e:e.scheme;switch(i){case"bearer":case"oauth":return GOr({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return MGa({key:i,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return n(i,typeof e!="string"?e.docs:void 0)}}function GOr({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return Gp.bearer({key:e,docs:r,token:t.generateName(n?.token?.name??"token"),tokenEnvVar:n?.token?.env})}function MGa({key:e,casingsGenerator:t,docs:r,rawScheme:n}){return Gp.basic({key:e,docs:r,username:t.generateName(n?.username?.name??"username"),usernameEnvVar:n?.username?.env,usernameOmit:n?.username?.omit,password:t.generateName(n?.password?.name??"password"),passwordEnvVar:n?.password?.env,passwordOmit:n?.password?.omit})}function ob(e){let t=PSf(e),{value:r,done:n}=zHi(t,"{");return n?{head:r,parts:[]}:{head:r,parts:[...OSf(t)]}}function*OSf(e){let t;do{let{value:r}=zHi(e,"}"),n=zHi(e,"{");t=n.done,yield{pathParameter:r,tail:n.value}}while(!t)}function*PSf(e){for(let t of e)yield t}function zHi(e,t){let r="",n=e.next();for(;n.done!==!0&&n.value!==t;)r+=n.value,n=e.next();return{value:r,done:n.done??!1}}Wi();function xkt({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:iH(n,{singleBaseUrl:()=>q0.singleBaseUrl(DSf({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q0.multipleBaseUrls(RSf({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([i,o])=>[i,iH(o,{singleBaseUrl:s=>[...typeof s=="string"?[]:s.audiences??[]],multipleBaseUrls:s=>[...s.audiences??[]]})]))}}}function DSf({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>iH(n,{singleBaseUrl:i=>{let o=typeof i=="string",s=o?void 0:i["default-url"],a=o?void 0:i["url-template"],c=o?void 0:i.variables;return{docs:o?void 0:i.docs,id:r,name:t.generateName(r),url:WOr(o?i:i.url),audiences:o?void 0:i.audiences,defaultUrl:s?WOr(s):void 0,urlTemplate:a,urlVariables:c?.map(u=>({id:u.id,name:t.generateName(u.id),default:u.default,values:u.values}))}},multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function RSf({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>iH(i,{multipleBaseUrls:o=>{let s=o["url-templates"],a=o["default-urls"],c=o.variables,u=s&&Object.keys(s).length>0?s:void 0,l=a&&Object.keys(a).length>0?ep(a,d=>WOr(d)):void 0,p=c&&Object.keys(c).length>0?Object.fromEntries(Object.entries(c).map(([d,f])=>[d,f.map(m=>({id:m.id,name:r.generateName(m.id),default:m.default,values:m.values}))])):void 0;return{docs:o.docs,id:n,name:r.generateName(n),urls:ep(o.urls,d=>WOr(d)),audiences:o.audiences,defaultUrls:l,urlTemplates:u,urlVariables:p}},singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function WOr(e){return e.endsWith("/")?e.slice(0,-1):e}Rt();function y0e(e){let t=2166136261;function r(o){t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}function n(o){for(let s=0,a=o.length;s<a;s++)r(o.charCodeAt(s))}function i(o,s){if(typeof o=="object"&&o!=null){if(s>64){n("[MaxDepthExceeded]");return}if(Array.isArray(o)){r(91);for(let a=0;a<o.length;a++)a>0&&r(44),i(o[a],s+1);r(93)}else{r(123);let a=Object.keys(o).sort(),c=a.length;for(let u=0;u<c;u++)u>0&&r(44),n(a[u]??""),r(58),i(o[a[u]??""],s+1);r(125)}}else n(String(o))}return i(e,0),t.toString(16)}function mY({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}Wi();Wi();var LGa={[Rn.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,Fu(e)])),[Rn.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Rn.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Rn.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[Rn.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","internal","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Rn.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[Rn.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Rn.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[Rn.GenerationLanguage.SWIFT]:new Set([])};var FSf=["go","ruby"];function mYe(e,t,r){let{generationLanguage:n,keywords:i,smartCasing:o}=r,s=VSf(e),a=A=>({unsafeName:A,safeName:kSf({name:A,keywords:NSf({generationLanguage:n,keywords:i})})}),c=t.preserveUnderscores===!0,u=c?(A,b)=>VHi(A,b):(A,b)=>b(A),l=u(s,Wn),p=c?VHi(s,A=>Fu(Wn(A))):Fu(l),d=u(s,TPe),{leading:f,trailing:m}=c?UGa(s):{leading:"",trailing:""},h=jwt(l);if(o){!MSf(h)&&(n==null||FSf.includes(n))&&(l=f+h.map((b,v)=>{if(v>0){let x=$Or(b);if(x!=null)return x;if(HOr(b))return b.toUpperCase()}return b}).join("")+m,p=Fu(f+h.map((b,v)=>{let x=$Or(b);return x??(HOr(b)?b.toUpperCase():v===0?Fu(b):b)}).join("")+m));let A=b=>b.split(" ").map(v=>v.split(/(\d+)/).map(TPe).join("")).join("_");d=c?VHi(s,A):A(s)}return{originalName:e,camelCase:a(t.casingOverrides?.camel??l),snakeCase:a(t.casingOverrides?.snake??d),screamingSnakeCase:a(t.casingOverrides?.["screaming-snake"]??d.toUpperCase()),pascalCase:a(t.casingOverrides?.pascal??p)}}function sw({generationLanguage:e,keywords:t,smartCasing:r}){let n={generationLanguage:e,keywords:t,smartCasing:r};return{generateName:(i,o)=>o?.casingOverrides!=null?mYe(i,o,n):i,generateNameAndWireValue:({name:i,wireValue:o,opts:s})=>s?.casingOverrides!=null?{wireValue:o,name:mYe(i,s,n)}:o===i?o:{wireValue:o,name:i}}}function b0e({generationLanguage:e,keywords:t,smartCasing:r}){let n={generationLanguage:e,keywords:t,smartCasing:r};return{generateName:(i,o)=>{if(typeof i=="string")return mYe(i,o??{},n);if("wireValue"in i){let s=i.name;return typeof s=="string"?mYe(s,o??{},n):s}return i},generateNameAndWireValue:(i,o)=>{if(typeof i=="string")return{wireValue:i,name:mYe(i,o??{},n)};let{name:s,wireValue:a}=i,c=typeof s=="string"?mYe(s,o??{},n):s;return{wireValue:a,name:c}}}}function kSf({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":jSf(e)?"_"+e:e}function NSf({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return LGa[e]}var QSf=/^[0-9]/;function jSf(e){return QSf.test(e)}function MSf(e){return e.some((t,r)=>{if(r===0)return!1;let n=e[r-1];if(n==null)return!1;let i=$Or(n)!=null||HOr(n),o=$Or(t)!=null||HOr(t);return i&&o})}function $Or(e){return USf.get(e.toUpperCase())}function HOr(e){return LSf.has(e.toUpperCase())}var LSf=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),USf=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),zSf=[[/\[\]/g,"Array"]];function VSf(e){return zSf.reduce((t,[r,n])=>t.replace(r,n),e)}function UGa(e){let t=e.match(/^(_+)/),r=e.match(/(_+)$/),n=t?.[1]??"",i=r?.[1]??"";if(n.length+i.length>=e.length)return{leading:e,trailing:"",core:""};let o=e.slice(n.length,e.length-i.length||void 0);return{leading:n,trailing:i,core:o}}function VHi(e,t){let{leading:r,trailing:n,core:i}=UGa(e);return r===""&&n===""?t(e):`${r}${t(i)}${n}`}function qSf(e){return"wireValue"in e&&!("originalName"in e)}function KOr(e){return typeof e=="string"?e:qSf(e)?e.name:e}function Vr(e){let t=KOr(e);return typeof t=="string"?t:t.originalName}function Xt(e){return typeof e=="string"?e:e.wireValue}function JOr(e){return typeof e=="string"?e:e.name}function GHi(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).snakeCase.unsafeName:t.snakeCase.unsafeName}var qHi;function WHi(){return qHi==null&&(qHi=b0e({generationLanguage:void 0,keywords:void 0,smartCasing:!0})),qHi}function $Hi(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).camelCase.unsafeName:t.camelCase.unsafeName}function wkt(e){let t=KOr(e);return typeof t=="string"?WHi().generateName(t).pascalCase.unsafeName:t.pascalCase.unsafeName}Rt();function zGa({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s}){if(n>=r)return l7({containerType:t});switch(t.type){case"list":{let a=Wd({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.list({list:[a.example,a.example],itemType:t.list}),jsonExample:[a.jsonExample,a.jsonExample]}}case"literal":return{type:"success",example:hl.literal({literal:t.literal._visit({boolean:a=>Ci.boolean(a),string:a=>Ci.string({original:a}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:a=>a,string:a=>a,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(o)return l7({containerType:t});let a=Wd({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.optional({optional:a.example,valueType:t.optional}),jsonExample:a.jsonExample}}case"nullable":{if(o)return l7({containerType:t});let a=Wd({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.nullable({nullable:a.example,valueType:t.nullable}),jsonExample:a.jsonExample}}case"set":{let a=Wd({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"?l7({containerType:t}):{type:"success",example:hl.set({set:[a.example],itemType:t.set}),jsonExample:[a.jsonExample]}}case"map":{let a=Wd({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s}),c=Wd({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:o,visitedTypes:s});return a.type==="failure"||c.type==="failure"?l7({containerType:t}):{type:"success",example:hl.map({map:[{key:a.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[a.jsonExample]:c.jsonExample}}}default:Ce(t)}}function l7({containerType:e}){switch(e.type){case"list":return{type:"success",example:hl.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:hl.literal({literal:e.literal._visit({boolean:t=>Ci.boolean(t),string:t=>Ci.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:hl.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:hl.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:hl.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:hl.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Ce(e)}}Rt();function HHi({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return KSf({fieldName:e,default_:GSf(t.v2),validation:WSf(t.v2)});case"BASE_64":return{type:"success",example:Ci.base64(ki.BASE64),jsonExample:ki.BASE64};case"BOOLEAN":return{type:"success",example:Ci.boolean(ki.BOOLEAN),jsonExample:ki.BOOLEAN};case"DATE":return{type:"success",example:Ci.date(ki.DATE),jsonExample:ki.DATE};case"DATE_TIME":return{type:"success",example:Ci.datetime({datetime:new Date(ki.DATE_TIME),raw:ki.DATE_TIME}),jsonExample:ki.DATE_TIME};case"DOUBLE":return JSf({fieldName:e,validation:$Sf(t.v2)});case"FLOAT":return{type:"success",example:Ci.float(ki.FLOAT),jsonExample:ki.FLOAT};case"INTEGER":return YSf({fieldName:e,validation:HSf(t.v2)});case"UINT_64":return{type:"success",example:Ci.uint64(ki.INT64),jsonExample:ki.INT64};case"UINT":return{type:"success",example:Ci.uint(ki.UINT),jsonExample:ki.UINT};case"BIG_INTEGER":return{type:"success",example:Ci.bigInteger(ki.INT64.toString()),jsonExample:`${ki.INT64}`};case"LONG":return{type:"success",example:Ci.long(ki.INT64),jsonExample:ki.INT64};case"UUID":return{type:"success",example:Ci.uuid(ki.UUID),jsonExample:ki.UUID};case"DATE_TIME_RFC_2822":return{type:"success",example:Ci.datetimeRfc2822({datetime:new Date(ki.DATE_TIME_RFC_2822),raw:ki.DATE_TIME_RFC_2822}),jsonExample:ki.DATE_TIME_RFC_2822};default:Ce(t.v1)}}function GSf(e){if(e?.type==="string")return e.default}function WSf(e){if(e?.type==="string")return e.validation}function $Sf(e){if(e?.type==="double")return e.validation}function HSf(e){if(e?.type==="integer")return e.validation}function VGa(e){if(e<=0)return"";if(e<=ki.SAMPLE_STRINGS.length){let t=ki.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return ki.SAMPLE_STRINGS[ki.SAMPLE_STRINGS.length-1]+".".repeat(e-ki.SAMPLE_STRINGS.length)}function KSf({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Ci.string({original:t}),jsonExample:t};if(r){let i=r.minLength,o=r.maxLength;if(i){let s=VGa(i);return{type:"success",example:Ci.string({original:s}),jsonExample:s}}else if(o!=null&&o<10){let s=VGa(o);return{type:"success",example:Ci.string({original:s}),jsonExample:s}}}let n=e??ki.STRING;return{type:"success",example:Ci.string({original:n}),jsonExample:n}}function JSf({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:Ci.double(r),jsonExample:r};if(n)return{type:"success",example:Ci.double(n),jsonExample:n}}return{type:"success",example:Ci.double(ki.DOUBLE),jsonExample:ki.DOUBLE}}function YSf({fieldName:e,validation:t}){if(t){let r=t.max,n=t.min;if(r)return{type:"success",example:Ci.integer(r),jsonExample:r};if(n)return{type:"success",example:Ci.integer(n),jsonExample:n}}return{type:"success",example:Ci.integer(ki.INT),jsonExample:ki.INT}}function XSf(e,t){if(e.type==="primitive"||e.type==="container"&&e.container.type==="literal")return!0;if(e.type==="named"){let r=t[e.typeId];if(r!=null&&r.shape.type==="enum")return!0}return!1}function Y2e({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s}){switch(r.shape.type){case"alias":{let a=Wd({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s});if(a.type==="failure")return a;let{example:c,jsonExample:u}=a;return{type:"success",example:Qu.alias({value:c}),jsonExample:u}}case"enum":{let a=r.shape.values[0];return a==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Qu.enum({value:a.name}),jsonExample:Xt(a.name)}}case"object":{let a={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let d of r.shape.extends){let f=t[d.typeId];if(f==null)continue;let m=Y2e({fieldName:e,typeDeclaration:f,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});m!=null&&m.type==="success"&&m.example.type==="object"&&(Object.assign(a,m.jsonExample),c.push(...m.example.properties))}let u=ZSf({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(u.type==="failure")return u;let{example:l,jsonExample:p}=u;return{type:"success",example:Qu.object({properties:[...c,...l.properties],extraProperties:l.extraProperties}),jsonExample:Object.assign({},a,p)}}case"undiscriminatedUnion":{let a=r.shape.members;if(a.every(l=>XSf(l.type,t))){let l=a.findIndex(p=>{if(p.type.type==="container"&&p.type.container.type==="literal")return!0;if(p.type.type==="named"){let d=t[p.type.typeId];if(d!=null&&d.shape.type==="enum")return d.shape.values.length>0}return!1});if(l!==-1){let p=a[l];if(p!=null){let d=Wd({fieldName:e,typeReference:p.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(d.type==="success"){let{example:f,jsonExample:m}=d;return{type:"success",example:Qu.undiscriminatedUnion({index:l,singleUnionType:f}),jsonExample:m}}}}}let u=0;for(let l of a){let p=Wd({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(p.type==="failure"){++u;continue}let{example:d,jsonExample:f}=p;return{type:"success",example:Qu.undiscriminatedUnion({index:u,singleUnionType:d}),jsonExample:f}}break}case"union":{let a=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let p of r.shape.baseProperties){let d=Wd({fieldName:Xt(p.name),typeReference:p.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});d.type==="success"&&(c[Xt(p.name)]=d.jsonExample)}let u=r.shape.baseProperties.map(p=>{let d=Wd({fieldName:Xt(p.name),typeReference:p.valueType,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(d.type==="failure")throw new Error(`Failed to generate example for union base property ${Xt(p.name)}`);let{example:f}=d;return{name:p.name,value:f}}),l=r.shape.extends.flatMap(p=>{let d=t[p.typeId];if(d==null)throw new Error(`Failed to find extended type declaration with id ${p.typeId}`);let f=Y2e({fieldName:e,typeDeclaration:d,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:o,visitedTypes:s});if(f==null||f.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${d.name.typeId}`);if(f.example.type!=="object")throw new Error(`Extended type declaration ${d.name.typeId} is not an object`);return f.example.properties});for(let p of r.shape.types){let d=p.shape._visit({noProperties:()=>({type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.noProperties()},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),...c}}),samePropertiesAsObject:f=>{let m=t[f.typeId];if(m==null)return{type:"failure",message:`Failed to find type declaration with id ${f.typeId}`};let h=Y2e({currentDepth:i,maxDepth:n,fieldName:e,typeDeclaration:m,typeDeclarations:t,skipOptionalProperties:o,visitedTypes:s});if(h==null)return{type:"failure",message:"Failed to generate example for type reference"};if(h.type==="failure")return h;let{example:A,jsonExample:b}=h;return{type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.samePropertiesAsObject({typeId:m.name.typeId,object:A.type==="object"?A:{properties:[],extraProperties:void 0}})},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),...typeof b=="object"?b:{},...c}}},singleProperty:f=>{let m=Wd({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:f.type,typeDeclarations:t,skipOptionalProperties:o,visitedTypes:s});if(m.type==="failure")return m;let{example:h,jsonExample:A}=m;return{type:"success",example:Qu.union({discriminant:a,singleUnionType:{wireDiscriminantValue:p.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.singleProperty(h)},baseProperties:u,extendProperties:l}),jsonExample:{[Xt(a)]:Xt(p.discriminantValue),[Xt(f.name)]:A,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function ZSf({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:o,skipOptionalProperties:s,visitedTypes:a}){let c={},u=[];for(let l of[...r.properties??[],...r.extendedProperties??[]]){let p=Wd({fieldName:Xt(l.name),typeReference:l.valueType,typeDeclarations:n,currentDepth:o+1,maxDepth:i,skipOptionalProperties:s,visitedTypes:a});if(p.type==="failure"&&!mY({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${Xt(l.name)} b/c ${p.message}`};if(p.type==="failure")continue;let{example:d,jsonExample:f}=p;u.push({name:l.name,originalTypeDeclaration:t.name,value:d,propertyAccess:l.propertyAccess}),c[Xt(l.name)]=f}return{type:"success",example:Qu.object({properties:u,extraProperties:void 0}),jsonExample:c}}function Wd({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s}){if(i>n)return{type:"failure",message:`Exceeded max depth of ${n}`};switch(t.type){case"named":{let a=r[t.typeId];if(a==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=s??new Map,u=c.get(t.typeId)??0;if(u>=2){let m=new Set([t.typeId]);return JHi({typeDeclaration:a,typeDeclarations:r,visitedMinimalTypes:m})}c.set(t.typeId,u+1);let l=Y2e({fieldName:e,typeDeclaration:a,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:c}),p=(c.get(t.typeId)??1)-1;if(p<=0?c.delete(t.typeId):c.set(t.typeId,p),l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:f}=l;return{type:"success",example:{jsonExample:f,shape:mo.named({shape:d,typeName:a.name})},jsonExample:f}}case"container":{let a=zGa({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:o,visitedTypes:s});if(a.type==="failure"){let{example:l,jsonExample:p}=l7({containerType:t.container});return{type:"success",example:{jsonExample:p,shape:mo.container(l)},jsonExample:p}}let{example:c,jsonExample:u}=a;return{type:"success",example:{jsonExample:u,shape:mo.container(c)},jsonExample:u}}case"primitive":{let{jsonExample:a,example:c}=HHi({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:a,shape:mo.primitive(c)},jsonExample:a}}case"unknown":{let a={key:"value"};return{type:"success",example:{jsonExample:a,shape:mo.unknown(a)},jsonExample:a}}}}function KHi(e,t){switch(e.type){case"primitive":case"unknown":return!0;case"named":return t[e.typeId]?.shape.type==="enum";case"container":switch(e.container.type){case"literal":return!0;case"optional":return KHi(e.container.optional,t);case"nullable":return KHi(e.container.nullable,t);default:return!1}}}function JHi({typeDeclaration:e,typeDeclarations:t,visitedMinimalTypes:r}){let n=r??new Set;switch(n.add(e.name.typeId),e.shape.type){case"object":{let i={},o=[];for(let a of[...e.shape.properties??[],...e.shape.extendedProperties??[]])if(KHi(a.valueType,t)){let c=Wd({fieldName:Xt(a.name),typeReference:a.valueType,typeDeclarations:t,currentDepth:0,maxDepth:3,skipOptionalProperties:!0});if(c.type==="failure")continue;o.push({name:a.name,originalTypeDeclaration:e.name,value:c.example,propertyAccess:a.propertyAccess}),i[Xt(a.name)]=c.jsonExample}else if(a.valueType.type==="named"&&!n.has(a.valueType.typeId)){let c=t[a.valueType.typeId];if(c!=null){let u=JHi({typeDeclaration:c,typeDeclarations:t,visitedMinimalTypes:n});u.type==="success"&&(o.push({name:a.name,originalTypeDeclaration:e.name,value:u.example,propertyAccess:a.propertyAccess}),i[Xt(a.name)]=u.jsonExample)}}else if(a.valueType.type==="container"){let{example:c,jsonExample:u}=l7({containerType:a.valueType.container});o.push({name:a.name,originalTypeDeclaration:e.name,value:{jsonExample:u,shape:mo.container(c)},propertyAccess:a.propertyAccess}),i[Xt(a.name)]=u}let s=Qu.object({properties:o,extraProperties:void 0});return{type:"success",example:{jsonExample:i,shape:mo.named({shape:s,typeName:e.name})},jsonExample:i}}case"enum":{let i=e.shape.values[0];if(i==null)return{type:"failure",message:"No enum values present for recursive type stub"};let o=Xt(i.name),s=Qu.enum({value:i.name});return{type:"success",example:{jsonExample:o,shape:mo.named({shape:s,typeName:e.name})},jsonExample:o}}case"alias":{let i=e.shape.aliasOf;if(i.type==="primitive"){let{jsonExample:s,example:a}=HHi({fieldName:void 0,primitiveType:i.primitive});return{type:"success",example:{jsonExample:s,shape:mo.named({shape:Qu.alias({value:{jsonExample:s,shape:mo.primitive(a)}}),typeName:e.name})},jsonExample:s}}if(i.type==="named"){let s=t[i.typeId];if(s!=null&&s.name.typeId!==e.name.typeId)return JHi({typeDeclaration:s,typeDeclarations:t,visitedMinimalTypes:n})}let o={};return{type:"success",example:{jsonExample:o,shape:mo.named({shape:Qu.alias({value:{jsonExample:o,shape:mo.unknown(o)}}),typeName:e.name})},jsonExample:o}}case"union":{let i=e.shape.discriminant;for(let o of e.shape.types)if(o.shape._visit({noProperties:()=>!0,samePropertiesAsObject:()=>!1,singleProperty:()=>!1,_other:()=>!1})){let a={[Xt(i)]:Xt(o.discriminantValue)};return{type:"success",example:{jsonExample:a,shape:mo.named({shape:Qu.union({discriminant:i,singleUnionType:{wireDiscriminantValue:o.discriminantValue,shape:Yt.ExampleSingleUnionTypeProperties.noProperties()},baseProperties:[],extendProperties:[]}),typeName:e.name})},jsonExample:a}}return{type:"failure",message:`No simple variant available for recursive union ${e.name.typeId}`}}case"undiscriminatedUnion":return{type:"failure",message:`Cannot generate stub for recursive undiscriminated union ${e.name.typeId}`}}}function X2e(e,t){let r=[];for(let n of e){let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;let o=i.example.jsonExample;if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean"){let s=Vr(n.name);r.push({name:n.name,value:{jsonExample:s,shape:mo.primitive(Ci.string({original:s}))}})}else r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function hYe(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&mY({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,value:i.example})}return{type:"success",example:r,jsonExample:void 0}}function YOr(e,t){let r=[];for(let n of e){if(t.skipOptionalRequestProperties&&mY({typeDeclarations:t.typeDeclarations,typeReference:n.valueType}))continue;let i=Wd({fieldName:Vr(n.name),currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:n.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(i.type==="failure")return i;r.push({name:n.name,shape:n.allowMultiple?Wx.exploded():Wx.single(),value:i.example})}return{type:"success",example:r,jsonExample:void 0}}var YHi=kr.primitive({v1:fs.String,v2:$n.string({default:void 0,validation:void 0})});function gYe({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:o}){let s={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:gg.ok(vA.body(void 0)),docs:void 0},a=X2e(t.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;s.endpointPathParameters=a.example;let c=X2e(r.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(c.type==="failure")return c;s.servicePathParameters=c.example;let u=X2e(e.pathParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;s.rootPathParameters=u.example;let l=YOr(t.queryParameters,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;s.queryParameters=l.example;let p=hYe(t.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(p.type==="failure")return p;s.endpointHeaders=p.example;let d=hYe(r.headers,{typeDeclarations:n,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;if(s.serviceHeaders=d.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let f={},m=[];if(t.requestBody.extends!=null)for(let h of t.requestBody.extends){let A=n[h.typeId];if(A==null)throw new Error(`Failed to find extended type declaration with id ${h.typeId}`);let b=Y2e({typeDeclaration:A,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});b!=null&&b.type==="success"&&Object.assign(f,b.jsonExample)}for(let h of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let A=Wd({fieldName:Xt(h.name),typeReference:h.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(A.type==="failure"&&!mY({typeDeclarations:n,typeReference:h.valueType}))return{type:"failure",message:`Failed to generate required property ${Xt(h.name)} b/c ${A.message}`};if(A.type==="failure")continue;let{example:b,jsonExample:v}=A;m.push({name:h.name,originalTypeDeclaration:void 0,value:b}),f[Xt(h.name)]=v}s.request=JT.inlinedRequestBody({jsonExample:f,properties:m,extraProperties:void 0});break}case"reference":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(f.type==="failure")return f;let{example:m}=f;s.request=JT.reference(m);break}default:Ce(t.requestBody)}if(o.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"streamParameter":{let f;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1});break;default:Ce(t.response.body.nonStreamResponse)}if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"streaming":{let f;switch(t.response.body.value.type){case"sse":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f,A=t.response.body.value.payload,b="";if(A.type==="named"){let v=n[A.typeId];if(v?.shape.type==="union"&&v.shape.discriminatorContext===dse.Protocol){let x=v.shape.types[0];x!=null&&(b=Xt(x.discriminantValue))}}s.response=gg.ok(vA.sse([{data:{...m,jsonExample:h},event:b}]));break}case"json":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.stream([{...m,jsonExample:h}]));break}case"text":{if(f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1}),f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.stream([{...m,jsonExample:h}]));break}default:Ce(t.response.body.value)}break}case"text":{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:YHi,skipOptionalProperties:!1});if(f.type==="failure")return f;let{example:m,jsonExample:h}=f;s.response=gg.ok(vA.body({...m,jsonExample:h}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Ce(t.response.body)}else if(o.type==="error")if(o.declaration.type==null)s.response=gg.error({body:void 0,error:o.declaration.name});else{let f=Wd({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:o.declaration.type,skipOptionalProperties:i});if(f.type==="failure")return f;let{example:m}=f;s.response=gg.error({body:m,error:o.declaration.name})}try{return{type:"success",example:{id:y0e(s),url:e_f(t,s),...s},jsonExample:void 0}}catch(f){return{type:"failure",message:`Parse failure with exceptions ${f}`}}}function e_f(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let o=i.value.jsonExample,s=typeof o=="string"?o:JSON.stringify(o);r[Vr(i.name)]=s});let n=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}function XHi({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:n}){let i={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},o=X2e(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(o.type==="failure")return o;i.pathParameters.push(...o.example);let s=X2e(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;i.pathParameters.push(...s.example);let a=YOr(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:10});if(a.type==="failure")return a;i.queryParameters=a.example;let c=hYe(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;i.headers.push(...c.example);let u=hYe(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:n,maxDepth:1});if(u.type==="failure")return u;i.headers.push(...u.example);let p=t.messages.filter(m=>m.origin==="client")[0];if(p!=null){let m=qGa({message:p,typeDeclarations:r,skipOptionalRequestProperties:n});m!=null&&i.messages.push({type:p.type,body:m})}let f=t.messages.filter(m=>m.origin==="server")[0];if(f!=null){let m=qGa({message:f,typeDeclarations:r,skipOptionalRequestProperties:n});m!=null&&i.messages.push({type:f.type,body:m})}return{type:"success",example:{...i,url:t_f(t,i)},jsonExample:void 0}}function qGa({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let n=Wd({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(n.type==="success")return qM.reference(n.example)}function t_f(e,t){let r={};[...t.pathParameters].forEach(i=>{let o=i.value.jsonExample,s=typeof o=="string"?o:JSON.stringify(o);r[Vr(i.name)]=s});let n=e.path.head+e.path.parts.map(i=>encodeURIComponent(`${r[i.pathParameter]}`)+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}Wi();Rt();function AYe(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},n=Object.values(t)[0],i=Object.values(r)[0];return{userExample:n,autoExample:i}}function E0e(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function GGa({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let n=e.types,i={pathParameters:{},queryParameters:{},headers:{}};for(let s of t.pathParameters){let{userExample:a,autoExample:c}=AYe(s.v2Examples);a!==void 0?i.pathParameters[Vr(s.name)]=a:c!==void 0&&(i.pathParameters[Vr(s.name)]=c)}for(let s of t.queryParameters){let{userExample:a,autoExample:c}=AYe(s.v2Examples);if(a!==void 0)i.queryParameters[Vr(s.name)]=a;else if(c!==void 0){if(r&&mY({typeReference:s.valueType,typeDeclarations:n}))continue;i.queryParameters[Vr(s.name)]=c}}let o=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let s of o){let{userExample:a,autoExample:c}=AYe(s.v2Examples);if(a!==void 0)i.headers[Xt(s.name)]=a;else if(c!==void 0){if(r&&mY({typeReference:s.valueType,typeDeclarations:n}))continue;i.headers[Xt(s.name)]=c}}return i}function WGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:n,queryParameters:i,headers:o}=GGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s={},a={},c={endpoint:{method:e.method,path:r_f(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:i,headers:o,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}case"inlinedRequestBody":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}case"reference":{let{userExamples:u,autoExamples:l}=E0e(e.requestBody.v2Examples);for(let[p,d]of Object.entries(u))s[p]={...c,requestBody:d};for(let[p,d]of Object.entries(l))a[p]={...c,requestBody:d};break}default:Ce(e.requestBody)}return{userRequestExamples:s,autoRequestExamples:a,baseExample:c}}function r_f(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(n=>{let{userExample:i,autoExample:o}=AYe(n.v2Examples),s=i??o,a;s==null?a=Vr(n.name):a=typeof s=="string"?s:JSON.stringify(s),t[Vr(n.name)]=a});let r=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${t[n.pathParameter]}`)+n.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}Rt();function XOr({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,n={},i={},o={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:o};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...o,body:CC.json(Skt(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:o};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let s=r.body,{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a)){let p=e.source?.type==="openrpc"?Skt(l):l;n[u]={...o,body:CC.json(p)}}for(let[u,l]of Object.entries(c)){let p=e.source?.type==="openrpc"?Skt(l):l;i[u]={...o,body:CC.json(p)}}break}case"json":{let s=r.body.value;if(s.type==="response"){let{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a)){let p=e.source?.type==="openrpc"?Skt(l):l;n[u]={...o,body:CC.json(p)}}for(let[u,l]of Object.entries(c)){let p=e.source?.type==="openrpc"?Skt(l):l;i[u]={...o,body:CC.json(p)}}}break}case"streaming":{let s=r.body.value;if(s.type==="json"){let{userExamples:a,autoExamples:c}=E0e(s.v2Examples);for(let[u,l]of Object.entries(a))n[u]={...o,body:CC.stream([l])};for(let[u,l]of Object.entries(c))i[u]={...o,body:CC.stream([l])}}break}case"streamParameter":break;default:Ce(r.body)}return{userResponseExamples:n,autoResponseExamples:i,baseExample:o}}function Skt(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var yYe=(e,t,r)=>{let n;return e===t?n=`${e}`:n=`${e}_${t}`,r&&(n=`${n}_${r}`),n},n_f=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function ZOr({key:e,displayName:t,request:r,response:n,exampleStore:i,userOrAutoStore:o}){if(!i.has(e)){let s={displayName:t,request:r,response:n,codeSamples:void 0};return o[e]=s,n_f({exampleStore:i,key:e,example:s}),!0}return!1}function $Ga({endpoint:e,ir:t,skipOptionalRequestProperties:r,logger:n}){let i={},o={},s=new Map,{userRequestExamples:a,autoRequestExamples:c,baseExample:u}=WGa({endpoint:e,ir:t,skipOptionalRequestProperties:r}),l=Object.keys(a)[0],p=Object.values(a)[0],d=Object.keys(c)[0],f=Object.values(c)[0],m=i_f({endpoint:e,userRequestExamples:a,baseRequestExample:u,firstUserRequestName:l,firstUserRequestExample:p,firstAutoRequestName:d,firstAutoRequestExample:f,userResults:i,autoResults:o,exampleStore:s,logger:n});if(o_f({endpoint:e,userRequestExamples:a,requestExamplesUsed:m,userResults:i,exampleStore:s}),Object.keys(i).length===0&&Object.keys(o).length===0){let{baseExample:h}=XOr({endpoint:e}),A=yYe(d??"base","base",void 0);ZOr({key:A,displayName:d??"base",request:f??u,response:h,exampleStore:s,userOrAutoStore:o})}return{userFullExamples:i,autoFullExamples:o}}function i_f({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:n,firstUserRequestExample:i,firstAutoRequestName:o,firstAutoRequestExample:s,userResults:a,autoResults:c,exampleStore:u,logger:l}){let p=e.v2Responses?.responses??[e.response],d=new Set;for(let f of p){let m=!1,{userResponseExamples:h,autoResponseExamples:A,baseExample:b}=XOr({endpoint:e,responseObject:f}),v=Object.keys(A)[0],x=Object.values(A)[0];for(let[C,w]of Object.entries(h)){let B,O;t[C]?(O=t[C],d.add(C),B=yYe(C,C,f?.statusCode)):s&&o?(O=s,B=yYe(o,C,f?.statusCode)):(Object.keys(t).length>0&&l?.warn(`Response example "${C}" on ${e.method.toUpperCase()} ${e.fullPath.head} has no matching request example with the same summary. Falling back to a base request with no body. To pair them, set the request and response example summary fields to the same value.`),O=r,B=yYe("base",C,f?.statusCode)),ZOr({key:B,displayName:C,request:O,response:w,exampleStore:u,userOrAutoStore:a})&&(m=!0)}if(!m){let C=Wn(`${Vr(e.name)}_example`);n&&i&&d.add(n);let w=yYe(n??o??"base",v??"base",f?.statusCode);ZOr({key:w,displayName:n??o??C,request:i??s??r,response:x??b,exampleStore:u,userOrAutoStore:c})&&(m=!0)}}return d}function o_f({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:n,exampleStore:i}){let{userResponseExamples:o,autoResponseExamples:s,baseExample:a}=XOr({endpoint:e}),c=Object.values(o)[0],u=Object.keys(o)[0],l=Object.keys(s)[0],p=Object.values(s)[0],d=Object.entries(t).filter(([f])=>!r.has(f));for(let[f,m]of d){let h=yYe(f,u??l??"base",c?c.statusCode:p?p.statusCode:a.statusCode);ZOr({key:h,displayName:f,request:m,response:c??p??a,exampleStore:i,userOrAutoStore:n})}}function _kt({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[n,i]of Object.entries(e.services))for(let o of i.endpoints){let s=[];if(o.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let a=gYe({ir:e,service:i,endpoint:o,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});a.type==="success"&&s.push({example:a.example})}if(o.userSpecifiedExamples.filter(a=>a.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let a of o.errors){let c=e.errors[a.error.errorId];if(!c)continue;let u=gYe({ir:e,service:i,endpoint:o,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:c}});u.type==="success"&&s.push({example:u.example})}o.autogeneratedExamples=s}for(let[n,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let o=XHi({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(o.type==="failure")continue;let{example:s}=o;i.examples=[...i.examples,s]}return e}function ZHi({ir:e,exampleGeneration:t,logger:r}){let n={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,o]of Object.entries(e.services))for(let s of o.endpoints){s.v2Examples==null&&(s.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:c}=$Ga({endpoint:s,ir:e,skipOptionalRequestProperties:!n.includeOptionalRequestPropertyExamples,logger:r});if(Object.keys(s.v2Examples.userSpecifiedExamples).length>0){if(Object.values(s.v2Examples.userSpecifiedExamples).some(l=>l.request!=null||l.response!=null))continue;let u=Object.values(s.v2Examples.userSpecifiedExamples).filter(l=>l!=null).flatMap(l=>l.codeSamples??[]);for(let[l,p]of Object.entries(c))c[l]={...p,codeSamples:u};for(let[l,p]of Object.entries(a))a[l]={...p,codeSamples:u}}s.v2Examples.autogeneratedExamples=c,s.v2Examples.userSpecifiedExamples=a}for(let[i,o]of Object.entries(e.websocketChannels??{})){if(o.examples.length>0&&n.skipAutogenerationIfManualExamplesExist===!0)continue;let s=XHi({ir:e,channel:o,typeDeclarations:e.types,skipOptionalRequestProperties:!n.includeOptionalRequestPropertyExamples});if(s.type==="failure")continue;let{example:a}=s;o.examples=[...o.examples,a]}return e}Wi();Rt();function KGa({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,Xt(i.name))).map(i=>({...i,value:oE({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Yt.ExampleSingleUnionTypeProperties.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=oE({filteredIr:e,exampleTypeReference:r});return n!==void 0?Yt.ExampleSingleUnionTypeProperties.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function oE({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:mo.container(hl.list({...n,list:n.list.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:mo.container(hl.set({...n,set:n.set.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?oE({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:mo.container(hl.optional({optional:i,valueType:n.valueType}))}:void 0},nullable:n=>{let i=n.nullable!=null?oE({filteredIr:e,exampleTypeReference:n.nullable}):void 0;return i!=null?{...t,shape:mo.container(hl.nullable({nullable:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:mo.container(hl.map({...n,map:n.map.map(i=>{let o=oE({filteredIr:e,exampleTypeReference:i.key}),s=oE({filteredIr:e,exampleTypeReference:i.value});return o!==void 0&&s!==void 0?{key:o,value:s}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=oE({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:mo.named({...r,shape:Qu.enum(n)})}),object:n=>({...t,shape:mo.named({...r,shape:Qu.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,Xt(i.name))).map(i=>({...i,value:oE({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=KGa({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=oE({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:mo.named({...r,shape:Qu.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function eKi({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function s_f({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function HGa({filteredIr:e,headers:t}){return t.map(r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function a_f({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,Xt(n.name)):!0).map(n=>{let i=oE({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=oE({filteredIr:e,exampleTypeReference:r});return n!==void 0?JT.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function c_f({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>gg.ok(vA.body(n!=null?oE({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>gg.ok(vA.stream(n.map(i=>oE({filteredIr:e,exampleTypeReference:i})).filter(Ra))),sse:n=>gg.ok(vA.sse(n.map(({event:i,data:o})=>{let s=oE({filteredIr:e,exampleTypeReference:o});return s!==void 0?{event:i,data:s}:void 0}).filter(Ra))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>gg.error({error:r,body:n!=null?oE({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function tKi({filteredIr:e,example:t}){return{...t,rootPathParameters:eKi({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:eKi({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:eKi({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:HGa({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:HGa({filteredIr:e,headers:t.endpointHeaders}),queryParameters:s_f({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?a_f({filteredIr:e,requestBody:t.request}):void 0,response:c_f({filteredIr:e,response:t.response})}}function JGa({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=oE({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:Qu.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:Qu.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,Xt(n.name))).map(n=>({...n,value:oE({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=KGa({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:Qu.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=oE({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:Qu.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function rKi(e,t){if(t==null)return e;let r=BPe(e.types,a=>t.hasType(a)),n=Object.fromEntries(Object.entries(r).map(([a,c])=>{let u=[];if(c.userProvidedExamples=c.userProvidedExamples.map(l=>JGa({filteredIr:t,exampleType:l})).filter(l=>l!==void 0),c.shape.type==="object"){for(let l of c.shape.properties)t.hasProperty(a,Xt(l.name))&&u.push(l);return[a,{...c,shape:vc.object({...c.shape,properties:u})}]}return[a,c]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([a,c])=>{let u=c.filter(l=>t.hasWebhook(l)).map(l=>{let p=l.id;return l.payload.type==="inlinedPayload"&&p!=null&&(l.payload={...l.payload,properties:l.payload.properties.filter(d=>t.hasWebhookPayloadProperty(p,Xt(d.name)))}),l});return[a,u]})),o=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([a])=>t.hasChannel(a)).map(([a,c])=>[a,{...c}])):{},s=e.environments;if(s){switch(s.environments.type){case"singleBaseUrl":{s.environments.environments=s.environments.environments.filter(a=>t.hasEnvironmentId(a.id));break}case"multipleBaseUrls":{s.environments.environments=s.environments.environments.filter(a=>t.hasEnvironmentId(a.id));break}}s.defaultEnvironment&&(t.hasEnvironmentId(s.defaultEnvironment)||(s.defaultEnvironment=void 0))}return{...e,environments:s,types:n,errors:BPe(e.errors,a=>t.hasError(a)),services:ep(BPe(e.services,a=>t.hasService(a)),a=>({...a,endpoints:a.endpoints.filter(c=>t.hasEndpoint(c)).map(c=>(c.autogeneratedExamples=c.autogeneratedExamples.map(u=>({...u,example:tKi({filteredIr:t,example:u.example})})),c.userSpecifiedExamples=c.userSpecifiedExamples.map(u=>({...u,example:u.example!=null?tKi({filteredIr:t,example:u.example}):void 0})),c.queryParameters.length>0&&(c.queryParameters=c.queryParameters.filter(u=>t.hasQueryParameter(c.id,Xt(u.name)))),c.requestBody?.type==="inlinedRequestBody"?{...c,requestBody:{...c.requestBody,properties:c.requestBody.properties.filter(u=>t.hasRequestProperty(c.id,Xt(u.name)))}}:c))})),websocketChannels:o,webhookGroups:i,serviceTypeReferenceInfo:u_f(e.serviceTypeReferenceInfo,t)}}function u_f(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(o=>t.hasTypeId(o)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}function Z2e(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}Rt();function h6(e){return e.allParts.map(t=>Vr(t)).join("/")}var Kl={generateTypeId:e=>`type_${h6(e.fernFilepath)}:${Vr(e.name)}`,generateErrorId:e=>`error_${h6(e.fernFilepath)}:${Vr(e.name)}`,generateServiceId:e=>`service_${h6(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${h6(e)}`,generateSubpackageId:e=>`subpackage_${h6(e)}`,generateEndpointId:(e,t)=>{let r=h6(e.fernFilepath),n=Vr(t.name);return`endpoint_${r}.${n}`},generateWebhookGroupId:e=>`webhooks_${h6(e)}`,generateWebhookId:(e,t)=>`webhooks_${h6(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${h6(e)}`};function bYe(e){return e.type!=null}var ePr=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:o,endpoints:s,webhooks:a,subpackages:c,queryParameters:u,requestProperties:l,webhookPayloadProperties:p,channels:d}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=o,this.endpoints=s,this.webhooks=a,this.webhookPayloadProperties=p,this.subpackages=c,this.requestProperties=l,this.queryParameters=u,this.channels=d}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Kl.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=Kl.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Kl.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var eNe=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=l_f(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:o}){let s=Kl.generateTypeId(t),a={typeId:s,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[s]=a,this.typesReferencedByService[s]==null&&(this.typesReferencedByService[s]=new Set),this.properties[s]={typeId:s,propertiesByAudience:o}}markTypeForAudiences(t,r){let n=Kl.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Kl.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&sb(t.type,n,i);let o={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=o}addEndpoint(t,r,n){let i=Kl.generateServiceId(t.name),o=r.id,s=new Set,a=new Set,c=new Set;for(let u of[...t.headers,...r.headers])sb(u.valueType,s,c);for(let u of[...t.pathParameters,...r.pathParameters])sb(u.valueType,s,c);for(let u of r.queryParameters)sb(u.valueType,s,c);if(n!=null&&n.request!=null&&typeof n.request!="string"){let u=Z2e(n.request["query-parameters"]??{});this.queryParameters[o]={endpointId:o,parametersByAudience:u}}r.requestBody!=null&&fd._visit(r.requestBody,{inlinedRequestBody:u=>{for(let l of u.extends)tPr(l,s,c);for(let l of u.properties)sb(l.valueType,s,c);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&hg(n.request.body)){let l=Z2e(n.request.body.properties??{});this.requestProperties[o]={endpointId:o,propertiesByAudience:l}}},reference:({requestBodyType:u})=>{sb(u,s,c)},fileUpload:({properties:u})=>{for(let l of u)xC._visit(l,{file:yt,bodyProperty:({valueType:p})=>{sb(p,s,c)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+l.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&yu._visit(r.response.body,{fileDownload:yt,json:u=>{sb(u.responseBodyType,s,c)},streaming:u=>{u._visit({sse:l=>sb(l.payload,s,c),json:l=>sb(l.payload,s,c),text:yt,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.type)}})},streamParameter:u=>{u.streamResponse._visit({sse:l=>sb(l.payload,s,c),json:l=>sb(l.payload,s,c),text:yt,_other:()=>{throw new Error("Unknown streamingResponse type: "+u.streamResponse.type)}}),u.nonStreamResponse.type==="json"&&sb(u.nonStreamResponse.value.responseBodyType,s,c)},text:yt,bytes:yt,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(u=>{a.add(Kl.generateErrorId(u.error)),c.add(u.error.fernFilepath)}),this.endpoints[o]={endpointId:o,serviceId:i,referencedTypes:s,referencedErrors:a,referencedSubpackages:c}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=Kl.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(o=>{let s=o.id;this.endpointsNeededForAudience.add(s),this.endpoints[s]?.referencedSubpackages.forEach(a=>{this.addSubpackages(a)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,n){let i=r.id;if(i==null)return;let o=new Set,s=new Set;r.payload!=null&&lS._visit(r.payload,{inlinedPayload:a=>{for(let c of a.extends)tPr(c,o,s);for(let c of a.properties)sb(c.valueType,o,s);if(n?.payload!=null&&typeof n.payload=="object"&&!bYe(n.payload)){let c=Z2e(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:c}}},reference:({payloadType:a})=>{sb(a,o,s)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),s.add(t),this.webhooks[i]={webhookId:i,referencedTypes:o,referencedSubpackages:s}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t))}addChannel(t,r,n,i){if(r==null)return;let o=new Set,s=new Set;for(let a of n.messages)Z1._visit(a.body,{reference:({bodyType:c})=>{sb(c,o,s)},inlinedBody:c=>{for(let u of c.extends)tPr(u,o,s);for(let u of c.properties)sb(u.valueType,o,s)},_other:()=>{}});for(let a of n.queryParameters)sb(a.valueType,o,s);s.add(t),this.channels[r]={channelId:r,referencedTypes:o,referencedSubpackages:s}}markChannelForAudiences(t,r,n){r!=null&&this.hasAudience(n)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let a of this.endpointsNeededForAudience.keys()){let c=this.getEndpointNode(a);for(let u of c.referencedErrors){if(r.has(u))continue;r.add(u);let l=this.getErrorNode(u);this.addReferencedTypes(t,l.referencedTypes)}this.addReferencedTypes(t,c.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let a of this.webhooksNeededForAudience.keys()){let c=this.getWebhookNode(a);this.addReferencedTypes(t,c.referencedTypes)}for(let a of this.channelsNeededForAudience.keys()){let c=this.getChannelNode(a);this.addReferencedTypes(t,c.referencedTypes)}let n={},i={},o={},s={};if(this.audiences.type==="filtered"){for(let[a,c]of Object.entries(this.properties)){if(!t.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}u.size>0&&(n[a]=u),n[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}i[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.parametersByAudience[l];p?.forEach(d=>{u.add(d)})}o[a]=u.size>0?u:void 0}for(let[a,c]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(a))continue;let u=new Set;for(let l of this.audiences.audiences){let p=c.propertiesByAudience[l];p?.forEach(d=>{u.add(d)})}s[a]=u.size>0?u:void 0}}return new ePr({types:t,properties:n,errors:r,requestProperties:i,queryParameters:o,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:s,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t]??=new Set;if(n.has(r))return;n.add(r);let i=this.getTypeNode(t);for(let o of i.allDescendants)this.markTypeForService(o,r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let o of this.audiences.audiences){let s=i.descendantsByAudience[o];if(s!=null)s.forEach(a=>{t.add(a)});else{i.allDescendants.forEach(a=>{t.add(a)});break}}else i.allDescendants.forEach(o=>{t.add(o)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:Ce(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Kl.generateSubpackageId(n))}}};function l_f(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Ce(e)}}function sb(e,t,r){kr._visit(e,{container:n=>{p_f(n,t,r)},named:n=>{tPr(n,t,r)},primitive:yt,unknown:yt,_other:yt})}function tPr(e,t,r){t.add(Kl.generateTypeId(e)),r.add(e.fernFilepath)}function p_f(e,t,r){Qs._visit(e,{list:n=>{sb(n,t,r)},map:n=>{sb(n.keyType,t,r),sb(n.valueType,t,r)},optional:n=>{sb(n,t,r)},nullable:n=>{sb(n,t,r)},set:n=>{sb(n,t,r)},literal:yt,_other:yt})}Rt();var f_f=[Yt.AvailabilityStatus.GeneralAvailability];function Vce(e){return e!=null&&!f_f.includes(e.status)}var nKi=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},Bkt=class{errors;constructor(){this.errors=new nKi}async check({from:t,to:r}){let n=this.toInternalIr(t),i=this.toInternalIr(r),o=y0e(n),s=y0e(i);if(o===s)return{bump:"no_change",isBreaking:!1,errors:[]};let a=this.checkBreaking({from:n,to:i});return{bump:a.isBreaking?"major":"minor",isBreaking:a.isBreaking,errors:a.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let n=this.errors.hasErrors();return{bump:n?"major":"minor",isBreaking:n,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(Vce(i.availability))continue;let o=r[n];if(!o){this.errors.add(`Type "${n}" was removed.`);continue}if(Vce(o.availability)){this.errors.add(`Type "${n}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:i,to:o})||this.errors.add(`Type "${n}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){let o=Object.values(r).find(s=>s.name.errorId===i.name.errorId);if(!o){this.errors.add(`Error "${i.name.errorId}" with status code "${i.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:i,to:o})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[n,i]of Object.entries(t)){if(Vce(i.availability)||(i.endpoints?.every(s=>Vce(s.availability))??!1))continue;let o=r[n];if(!o){this.errors.add(`Service "${n}" was removed.`);continue}if(Vce(o.availability)){this.errors.add(`Service "${n}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:n,from:i,to:o})}}checkServiceBreakingChanges({id:t,from:r,to:n}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:n})}checkEndpointsBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.endpoints.map(s=>[s.id,s])),o=Object.fromEntries(n.endpoints.map(s=>[s.id,s]));for(let[s,a]of Object.entries(i)){if(Vce(a.availability))continue;let c=o[s];if(!c){this.errors.add(`Endpoint "${s}" was removed.`);continue}if(Vce(c.availability)){this.errors.add(`Endpoint "${s}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:s,from:a,to:c})}}checkEndpointBreakingChanges({id:t,from:r,to:n}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:n.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:n.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:n.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:n.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:n.headers}),r.requestBody!=null&&(n.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:n.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(n.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:n.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&n.pagination==null||r.pagination==null&&n.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Vr(s.name),s])),o=Object.fromEntries(n.map(s=>[Vr(s.name),s]));for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Path parameter "${s}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Path parameter "${s}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Xt(s.name),s])),o=Object.fromEntries(n.map(s=>[Xt(s.name),s]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([s,a])=>[s,a.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,a])=>[s,a.valueType]))});for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Query parameter "${s}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Query parameter "${s}" type changed in endpoint "${t}".`),a.allowMultiple!==c.allowMultiple&&this.errors.add(`Query parameter "${s}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:n}){let i=Object.fromEntries(r.map(s=>[Xt(s.name),s])),o=Object.fromEntries(n.map(s=>[Xt(s.name),s]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([s,a])=>[s,a.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,a])=>[s,a.valueType]))});for(let[s,a]of Object.entries(i)){let c=o[s];if(!c){this.errors.add(`Header "${s}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:a.valueType,to:c.valueType})||this.errors.add(`Header "${s}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:n}){r!==n&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:n}){this.areHttpPathsCompatible({from:r,to:n})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let n=0;n<t.parts.length;n++){let i=t.parts[n];if(i==null)return!1;let o=r.parts[n];if(o==null||i.pathParameter!==o.pathParameter||i.tail!==o.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:n}){switch(r.type){case"inlinedRequestBody":if(n.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:n}))return;break;case"reference":if(n.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:n}))return;break;case"fileUpload":if(n.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:n}))return;break;case"bytes":if(n.type==="bytes")return;break;default:Ce(r)}this.errors.add(`Request body type changed from "${r.type}" to "${n.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let n=this.getInlinedRequestBody(t),i=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:n,to:i}),Object.entries(n).every(([o,s])=>{let a=i[o];return a?this.areTypeReferencesCompatible({from:s,to:a}):(this.errors.add(`Request body property "${o}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let n=this.getFileUploadRequest(t.properties),i=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:n,to:i});for(let[o,s]of Object.entries(n)){let a=i[o];if(!a)return this.errors.add(`File upload property "${o}" was removed.`),!1;if(s==="file"&&a!=="file")return this.errors.add(`File upload property "${o}" type changed.`),!1;if(s==="fileArray"&&a!=="fileArray")return this.errors.add(`File upload property "${o}" type changed.`),!1;if(s!=="file"&&s!=="fileArray"&&a!=="file"&&a!=="fileArray"&&!this.areTypeReferencesCompatible({from:s,to:a}))return this.errors.add(`File upload property "${o}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:n}){if(r.statusCode!==n.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${n.statusCode}".`),!(r.body==null&&n.body==null)){if(r.body==null||n.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(n.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"fileDownload":if(n.body.type==="fileDownload")return;break;case"text":if(n.body.type==="text")return;break;case"bytes":if(n.body.type==="bytes")return;break;case"streaming":if(n.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:n.body.value});return}break;case"streamParameter":if(n.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:n.body.streamResponse});return}break;default:Ce(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${n.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:Ce(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return Vce(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:Ce(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let n=Object.fromEntries(t.values.map(o=>[Xt(o.name),o])),i=Object.fromEntries(r.values.map(o=>[Xt(o.name),o]));return Object.keys(n).length!==Object.keys(i).length?!1:Object.values(n).every(o=>{let s=i[Xt(o.name)];return s?this.areNameAndWireValuesCompatible({from:o.name,to:s.name}):(this.errors.add(`Enum value "${Xt(o.name)}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let n=Object.fromEntries([...t.properties.map(o=>[Xt(o.name),o]),...t.extendedProperties?.map(o=>[Xt(o.name),o])??[]]),i=Object.fromEntries([...r.properties.map(o=>[Xt(o.name),o]),...r.extendedProperties?.map(o=>[Xt(o.name),o])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,s])=>[o,s.valueType])),to:Object.fromEntries(Object.entries(i).map(([o,s])=>[o,s.valueType]))}),Object.values(n).every(o=>{let s=i[Xt(o.name)];return s?this.areObjectPropertiesCompatible({from:o,to:s}):(this.errors.add(`Object property "${Xt(o.name)}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${Xt(t.discriminant)}" changed.`),!1;let n=new Set(t.extends.map(u=>this.getKeyForDeclaration(u))),i=new Set(r.extends.map(u=>this.getKeyForDeclaration(u)));for(let u of n)if(!i.has(u))return this.errors.add(`Extended type "${u}" was removed.`),!1;let o=Object.fromEntries(t.baseProperties.map(u=>[Xt(u.name),u])),s=Object.fromEntries(r.baseProperties.map(u=>[Xt(u.name),u]));for(let u of Object.values(o)){let l=s[Xt(u.name)];if(!l)return this.errors.add(`Union type with discriminant value "${Xt(u.name)}" no longer has a property named "${Xt(u.name)}".`),!1;if(!this.areObjectPropertiesCompatible({from:u,to:l}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(o).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(s).map(([u,l])=>[u,l.valueType]))});let a=Object.fromEntries(t.types.map(u=>[Xt(u.discriminantValue),u])),c=Object.fromEntries(r.types.map(u=>[Xt(u.discriminantValue),u]));return Object.values(a).every(u=>{let l=c[Xt(u.discriminantValue)];return l?this.areSingleUnionTypesCompatible({from:u.shape,to:l.shape}):(this.errors.add(`Union type for discriminant value "${Xt(u.discriminantValue)}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:Ce(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((n,i)=>{let o=r.members[i];return o?this.areTypeReferencesCompatible({from:n.type,to:o.type}):(this.errors.add(`Undiscriminated union member at index ${i} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||i==="file"||i==="fileArray"||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[n,i]of Object.entries(r))t[n]||(i.type!=="container"||i.container.type!=="optional")&&this.errors.add(`Required property "${n}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:Ce(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:Ce(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:JOr(t),to:JOr(r)})&&Xt(t)===Xt(r)}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:Ce(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((n,i)=>{let o=r.allParts[i];return o==null?!1:this.areNamesCompatible({from:n,to:o})})}areNamesCompatible({from:t,to:r}){return Vr(t)===Vr(r)}getInlinedRequestBody(t){let r={};for(let n of[...t.extendedProperties??[],...t.properties])r[Xt(n.name)]=n.valueType;return r}getFileUploadRequest(t){let r={};for(let n of t)switch(n.type){case"file":r[Xt(n.value.key)]="file";break;case"bodyProperty":r[Xt(n.name)]=n.valueType;break;default:Ce(n)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(i=>Vr(i)).join(".")}.${Vr(t)}`}};function tNe(e,t,r){let{environments:n,changedBaseUrlIds1:i,changedBaseUrlIds2:o}=m_f(e.environments,t.environments,r),{services:s,websocketChannels:a}=h_f(e,t,i,o);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:XGa([...e.headers??[],...t.headers??[]]),environments:n,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:s,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:d_f(e.subpackages,t.subpackages),websocketChannels:a,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(c=>!e.rootPackage.subpackages?.includes(c))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:XGa([...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]]),pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]],generationMetadata:e.generationMetadata??t.generationMetadata,apiPlayground:e.apiPlayground??t.apiPlayground,casingsConfig:e.casingsConfig??t.casingsConfig}}function d_f(e,t){let r=e;for(let[n,i]of Object.entries(t))r[n]==null?r[n]=i:r[n]={name:i.name,displayName:i.displayName,fernFilepath:i.fernFilepath,hasEndpointsInTree:r[n].hasEndpointsInTree||i.hasEndpointsInTree,navigationConfig:r[n].navigationConfig??i.navigationConfig,docs:r[n].docs??i.docs,service:r[n].service??i.service,subpackages:[...r[n].subpackages??[],...(i.subpackages??[]).filter(o=>!r[n]?.subpackages?.includes(o))],webhooks:r[n].webhooks??i.webhooks,websocket:r[n].websocket??i.websocket,errors:[...r[n].errors??[],...i.errors??[]],types:[...r[n].types??[],...i.types??[]]};return r}function m_f(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let n=YGa(e),i=YGa(t);if(n&&i&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:q0.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let o=n?t.defaultEnvironment:e.defaultEnvironment,s=e.environments,a=t.environments;if(s.type==="singleBaseUrl"&&a.type==="singleBaseUrl"){let c=n?a:s,u=n?s:a,l={},{deconflictedEnvironments2:p,changedBaseUrlIds2:d}=g_f(c,u,r);if(c.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let f="Base",m=r.generateName("Base");return c.environments.forEach(h=>{l[h.id]=f}),{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[{id:f,name:m},...p.environments.map(h=>({id:h.id,name:h.name}))],environments:c.environments.map(h=>({id:h.id,name:h.name,urls:{[f]:h.url,...Object.fromEntries(p.environments.map(A=>[A.id,A.url]))},docs:void 0,audiences:h.audiences,defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}))})},changedBaseUrlIds1:n?d:l,changedBaseUrlIds2:n?l:d}}if(s.type==="multipleBaseUrls"&&a.type==="singleBaseUrl"||s.type==="singleBaseUrl"&&a.type==="multipleBaseUrls"){let c=s.type==="singleBaseUrl"?s:a,u=s.type==="multipleBaseUrls"?s:a,{deconflictedEnvironments1:l,changedBaseUrlIds1:p}=A_f(c,u,r);return{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[...u.baseUrls,...l.environments.map(d=>({id:d.id,name:d.name}))],environments:u.environments.map(d=>({...d,urls:{...d.urls,...Object.fromEntries(l.environments.map(f=>[f.id,f.url]))}}))})},changedBaseUrlIds1:s.type==="singleBaseUrl"?p:void 0,changedBaseUrlIds2:s.type==="singleBaseUrl"?void 0:p}}if(s.type==="multipleBaseUrls"&&a.type==="multipleBaseUrls"){let{deconflictedEnvironments:c,changedBaseUrlIds:u}=y_f(s,a,r);return{environments:{defaultEnvironment:o,environments:q0.multipleBaseUrls({baseUrls:[...s.baseUrls,...c.baseUrls],environments:s.environments.flatMap(l=>c.environments.map(p=>({...l,urls:{...l.urls,...p.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:u}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function h_f(e,t,r,n){if(r!=null)for(let[s,a]of Object.entries(r)){for(let c of Object.values(e.services))for(let u of Object.values(c.endpoints))u.baseUrl==s&&(u.baseUrl=a),u.v2BaseUrls?.includes(s)&&(u.v2BaseUrls=u.v2BaseUrls.map(l=>l===s?a:l));for(let c of Object.values(e.websocketChannels??{}))c.baseUrl==s&&(c.baseUrl=a)}if(n!=null)for(let[s,a]of Object.entries(n)){for(let c of Object.values(t.services))for(let u of Object.values(c.endpoints))u.baseUrl==s&&(u.baseUrl=a),u.v2BaseUrls?.includes(s)&&(u.v2BaseUrls=u.v2BaseUrls.map(l=>l===s?a:l));for(let c of Object.values(t.websocketChannels??{}))c.baseUrl==s&&(c.baseUrl=a)}let i=e.services;for(let[s,a]of Object.entries(t.services))i[s]==null?i[s]=a:i[s]={availability:a.availability,name:a.name,displayName:a.displayName,basePath:a.basePath,endpoints:[...i[s].endpoints??[],...a.endpoints],pathParameters:[...i[s].pathParameters??[],...a.pathParameters??[]],headers:[...i[s].headers??[],...a.headers??[]],encoding:a.encoding,transport:a.transport,audiences:[...i[s].audiences??[],...a.audiences??[]]};let o={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:i,websocketChannels:o}}function g_f(e,t,r){let n={},i=new Set(e.environments.map(u=>u.id)),o=new Set(e.environments.map(u=>u.name)),s=new Map(e.environments.map(u=>[u.url,u.id])),a=t.environments.filter(u=>{let l=s.get(u.url);return l!=null?(n[u.id]=l,!1):!0}).map(u=>{if(i.has(u.id)||o.has(u.name)){let l=iKi(u.id,i);return n[u.id]=l,{...u,id:l,name:r.generateName(l)}}return u});return{deconflictedEnvironments2:q0.singleBaseUrl({environments:a}),changedBaseUrlIds2:n}}function A_f(e,t,r){let n={},i=new Set(t.baseUrls.map(c=>c.id)),o=new Set(t.baseUrls.map(c=>c.name)),s=e.environments.map(c=>{if(i.has(c.id)||o.has(c.name)){let u=iKi(c.id,i);return n[c.id]=u,{...c,id:u,name:r.generateName(u)}}return c});return{deconflictedEnvironments1:q0.singleBaseUrl({environments:s}),changedBaseUrlIds1:n}}function y_f(e,t,r){let n={},i=new Set(e.baseUrls.map(u=>u.id)),o=new Set(e.baseUrls.map(u=>u.name)),s=t.baseUrls.map(u=>{if(i.has(u.id)||o.has(u.name)){let l=iKi(u.id,i);return n[u.id]=l,{...u,id:l,name:r.generateName(l)}}return u}),a=t.environments.map(u=>({...u,urls:Object.fromEntries(Object.entries(u.urls).map(([l,p])=>[n[l]??l,p]))}));return{deconflictedEnvironments:q0.multipleBaseUrls({baseUrls:s,environments:a}),changedBaseUrlIds:n}}function YGa(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function XGa(e){let t=new Set;return e.filter(r=>{let n=Xt(r.name).toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function iKi(e,t){let r=e,n=1;for(;t.has(r);)r=`${e}-${n}`,n++;return r}YA();function bN({relativeFilepath:e,casingsGenerator:t}){let r=M3(e),n=qT(e,{stripExtension:!0}),i=r==="."?[]:r.split("/").map(a=>t.generateName(a)),o=n!==TDe?t.generateName(n):void 0,s=[];return s.push(...i),o!=null&&s.push(o),{allParts:s,packagePath:i,file:o}}YA();function I0e({referencedIn:e,importPath:t}){return YE(M3(e),t)}function g6({reference:e,referencedIn:t,imports:r}){let[n,i,...o]=e.split(".");if(n==null||o.length>0)return;if(i==null)return{typeName:n,relativeFilepath:t};let a=r[n];if(a!=null)return{relativeFilepath:I0e({referencedIn:t,importPath:a}),typeName:i}}function JS({typeName:e,file:t}){let r=g6({reference:e,referencedIn:t.relativeFilepath,imports:t.imports});if(r==null)throw new j({message:"Failed to locate type: "+e,code:j.Code.ResolutionError});let n={name:t.casingsGenerator.generateName(r.typeName),fernFilepath:bN({relativeFilepath:r.relativeFilepath,casingsGenerator:t.casingsGenerator}),displayName:void 0};return{...n,typeId:Kl.generateTypeId(n)}}Rt();function Tkt(e){if(e!=null)return e=e.replace(/\*\//g,"* /"),e.endsWith(`
|
|
1588
1588
|
`)||e.endsWith("\r")?e.substring(0,e.length-1):e}var b_f={docs:void 0,availability:void 0};function KO(e){return typeof e=="string"?b_f:{docs:Tkt(e.docs),availability:EN(e.availability)}}function EN(e){if(e!=null)return{status:E_f(typeof e=="string"?e:e.status),message:typeof e!="string"?e.message:void 0}}function ZGa(e){return typeof e=="string"?[]:e.audiences??[]}function E_f(e){switch(e){case"in-development":return vC.InDevelopment;case"pre-release":return vC.PreRelease;case"deprecated":return vC.Deprecated;case"generally-available":return vC.GeneralAvailability;default:Ce(e)}}Rt();function e7a({object:e,file:t}){return vc.object({extends:p7(e.extends).map(r=>JS({typeName:r,file:t})),properties:Okt(e,t),extraProperties:e["extra-properties"]??!1,extendedProperties:void 0})}function Okt(e,t){return e.properties==null?[]:Object.entries(e.properties).map(([r,n])=>({...KO(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:r,name:YS({propertyKey:r,property:n}).name}),valueType:t.parseTypeReference(n),propertyAccess:EYe({property:n}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}))}function p7(e){return e==null?[]:typeof e=="string"?[e]:e}function YS({propertyKey:e,property:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function EYe({property:e}){if(typeof e=="string")return;let t=e.access;if(t!=null)switch(t){case"read-only":return JPe.ReadOnly;case"write-only":return JPe.WriteOnly;default:Ce(t)}}function r7a({request:e,file:t}){let r=e!=null?I_t(e):void 0;if(r!=null)return fd.bytes({isOptional:r.isOptional,contentType:typeof e=="string"?void 0:e?.["content-type"],docs:typeof e=="string"?void 0:e?.docs,v2Examples:void 0});if(typeof e=="string")return fd.reference(rPr({requestBody:e,file:t}));if(e?.body==null)return;let n=nDe(e);if(n!=null)return fd.fileUpload({contentType:e["content-type"],name:t.casingsGenerator.generateName(n.name),properties:n.properties.map(i=>i.isFile?i.isArray?xC.file(_2.fileArray({key:t.casingsGenerator.generateNameAndWireValue({wireValue:i.key,name:i.key}),isOptional:i.isOptional,contentType:i.contentType,docs:i.docs})):xC.file(_2.file({key:t.casingsGenerator.generateNameAndWireValue({wireValue:i.key,name:i.key}),isOptional:i.isOptional,contentType:i.contentType,docs:i.docs})):xC.bodyProperty({...t7a({propertyKey:i.key,propertyDefinition:i.propertyType,docs:i.docs,availability:EN(i.availability),file:t}),style:i.style??v_f(i.contentType),contentType:i.contentType})),docs:e.docs,v2Examples:void 0});if(hg(e.body)){if(e.name==null)throw new j({message:"Name is missing for inlined request",code:j.Code.InternalError});return fd.inlinedRequestBody({name:t.casingsGenerator.generateName(e.name),extends:p7(e.body.extends).map(i=>JS({typeName:i,file:t})),contentType:e["content-type"],docs:e.docs,properties:e.body.properties!=null?Object.entries(e.body.properties).map(([i,o])=>t7a({propertyKey:i,propertyDefinition:o,docs:typeof o!="string"?o.docs:void 0,availability:typeof o!="string"?EN(o.availability):void 0,file:t})):[],extraProperties:e.body["extra-properties"]??!1,extendedProperties:void 0,v2Examples:void 0})}return fd.reference(rPr({requestBody:e.body,file:t,contentType:e["content-type"]}))}var I_f={"application/json":"json"};function v_f(e){return e?I_f[e]:void 0}function rPr({requestBody:e,file:t,contentType:r}){return{docs:typeof e!="string"?e.docs:void 0,requestBodyType:t.parseTypeReference(e),contentType:r,v2Examples:void 0}}function t7a({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:YS({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},propertyAccess:void 0}}Rt();function rNe({typeResolver:e,file:t,resolvedType:r,property:n}){switch(r._type){case"container":if(r.container._type==="optional")return rNe({typeResolver:e,file:t,resolvedType:r.container.itemType,property:n});break;case"named":if(rf(r.declaration))return oKi({typeResolver:e,file:r.file,objectSchema:r.declaration,property:n});break;case"primitive":case"unknown":break;default:Ce(r)}throw new j({message:"Internal error; response must be an object in order to return a property as a response",code:j.Code.InternalError})}function oKi({typeResolver:e,file:t,objectSchema:r,property:n}){let o=n7a(r,t,e)[n];if(o==null)throw new j({message:`Object does not have a property named ${n}.`,code:j.Code.ReferenceError});return o}function n7a(e,t,r){let n=[];typeof e.extends=="string"?n=[e.extends]:Array.isArray(e.extends)&&(n=e.extends);let i={};for(let s of n){let a=C_f(s,t,r);Object.entries(a).map(([c,u])=>{i[c]=u})}return Okt(e,t).forEach(s=>{let a=Vr(s.name);i[a]=s}),i}function C_f(e,t,r){let n=r.resolveNamedTypeOrThrow({referenceToNamedType:e,file:t});if(n._type==="named"&&rf(n.declaration))return n7a(n.declaration,t,r);throw new j({message:`Extended type ${e} must be another named type`,code:j.Code.InternalError})}function nPr({typeResolver:e,file:t,resolvedType:r,propertyComponents:n}){if(n.length===0)return;if(n.length===1)return rNe({typeResolver:e,file:t,resolvedType:r,property:n[0]??""});let i=o7a(r);if(i!=null)return iPr({typeResolver:e,file:t,objectSchema:i,propertyComponents:n})}function iPr({typeResolver:e,file:t,objectSchema:r,propertyComponents:n}){if(n.length===0)return;if(n.length===1)return oKi({typeResolver:e,file:t,objectSchema:r,property:n[0]??""});let i=x_f({typeResolver:e,file:t,objectSchema:r,property:n[0]??""}),o=e.resolveTypeOrThrow({type:i,file:t});return nPr({typeResolver:e,file:IYe(o)??t,resolvedType:o,propertyComponents:n.slice(1)})}function x_f({typeResolver:e,file:t,objectSchema:r,property:n}){let o=i7a({typeResolver:e,file:t,objectSchema:r})[n];if(o==null)throw new j({message:`Response does not have a property named ${n}.`,code:j.Code.ReferenceError});return o}function i7a({typeResolver:e,file:t,objectSchema:r}){let n=[];typeof r.extends=="string"?n=[r.extends]:Array.isArray(r.extends)&&(n=r.extends);let i={};for(let o of n){let s=w_f({typeResolver:e,file:t,extendedType:o});Object.entries(s).map(([a,c])=>{i[a]=c})}return r.properties!=null&&Object.entries(r.properties).map(([o,s])=>{i[o]=typeof s=="string"?s:s.type}),i}function w_f({typeResolver:e,file:t,extendedType:r}){let n=e.resolveNamedTypeOrThrow({referenceToNamedType:r,file:t});if(n._type==="named"&&rf(n.declaration))return i7a({typeResolver:e,file:IYe(n)??t,objectSchema:n.declaration});throw new j({message:`Extended type ${r} must be another named type.`,code:j.Code.InternalError})}function IYe(e){if(e!=null){if(e._type==="named")return e.file;if(e._type==="container"&&e.container._type==="optional")return IYe(e.container.itemType)}}function o7a(e){if(e!=null){if(e._type==="named"&&rf(e.declaration))return e.declaration;if(e._type==="container"&&e.container._type==="optional")return o7a(e.container.itemType)}}function f7(e){return e.substring(9)?.split(".")??[]}function kB(e){return e.substring(10)?.split(".")??[]}var oPr="request",Pkt="body";function a7a({request:e,endpointKey:t,endpoint:r,service:n,file:i,typeResolver:o,propertyResolver:s}){let a=S_f({request:e,service:n,file:i,typeResolver:o});if(a!=null)return{shape:a,requestParameterName:i.casingsGenerator.generateName(oPr),streamParameter:r["stream-condition"]!=null?s.resolveRequestPropertyOrThrow({file:i,endpoint:t,propertyComponents:f7(r["stream-condition"])}):void 0}}function S_f({service:e,request:t,file:r,typeResolver:n}){let i=()=>{if(typeof t=="string"||t?.name==null)throw new j({message:"Name is missing for request wrapper",code:j.Code.InternalError});return X3.wrapper({wrapperName:r.casingsGenerator.generateName(t.name),bodyKey:r.casingsGenerator.generateName(Pkt),includePathParameters:B_f(t),onlyPathParameters:__f({request:t,file:r,typeResolver:n})})};if(!sKi({headers:e.headers??{},file:r,typeResolver:n}))return i();if(t==null)return;if(typeof t=="string")return X3.justRequestBody(s7a({requestBody:t,file:r}));let{body:o}=t;if(sPr({request:t,file:r,typeResolver:n})||o!=null&&hg(o))return i();if(o!=null)return X3.justRequestBody(s7a({requestBody:o,file:r}))}function s7a({requestBody:e,file:t,contentType:r}){let n=typeof e=="string"?s4(e):s4(e.type);return n!=null?Z5.bytes({isOptional:n.isOptional,contentType:r,docs:void 0,v2Examples:void 0}):Z5.typeReference(rPr({requestBody:e,file:t,contentType:r}))}function sPr({request:e,file:t,typeResolver:r}){let{headers:n={},"path-parameters":i={},"query-parameters":o={}}=e;return!sKi({headers:n,file:t,typeResolver:r})||ih(i)>0||ih(o)>0}function __f({request:e,file:t,typeResolver:r}){let{headers:n={},"path-parameters":i={},"query-parameters":o={}}=e;return ih(i)>0&&sKi({headers:n,file:t,typeResolver:r})&&ih(o)===0&&e.body==null}function B_f(e){return typeof e!="string"&&e?.["path-parameters"]!=null}function sKi({headers:e,file:t,typeResolver:r}){return Object.values(e).filter(n=>{let i=typeof n=="string"?n:n.type,o=r.resolveTypeOrThrow({type:i,file:t});return!(o._type==="container"&&o.container._type==="literal")}).length===0}Rt();var mPr=Ie(vm(),1);function d7(e){return typeof e.request!="string"&&e.request?.["path-parameters"]?e.request?.["path-parameters"]:e["path-parameters"]!=null?e["path-parameters"]:{}}function aPr(e,t){let r=T_f(e);if(r.length===0)return t;let n=new Map;for(let s of t)n.set(Vr(s.name),s);let i=[],o=new Set;for(let s of r){let a=n.get(s);a!=null&&(i.push(a),o.add(s))}for(let s of t)o.has(Vr(s.name))||i.push(s);return i}function T_f(e){let t=[],r=/{([^}]+)}/g,n;for(;(n=r.exec(e))!==null;)n[1]!=null&&t.push(n[1]);return t}function c7a({codeSample:e,file:t}){return BIi(e,{language:r=>UM.language({name:r.name!=null?t.casingsGenerator.generateName(r.name):void 0,docs:r.docs,language:r.language,code:r.code,install:r.install}),sdk:r=>UM.sdk({name:r.name!=null?t.casingsGenerator.generateName(r.name):void 0,docs:r.docs,sdk:O_f(r.sdk),code:r.code})})}function O_f(e){switch(e){case"js":return"javascript";case"node":return"javascript";case"ts":return"typescript";case"nodets":return"typescript";case"golang":return"go";case"dotnet":return"csharp";case"c#":return"csharp";case"jvm":return"java";default:return e}}function Dkt(e){if(e!=null){if(typeof e=="string")return ZI.string(e);if(typeof e=="boolean")return ZI.boolean(e)}}Rt();var R7a=Ie(vm(),1);function v0e({errorName:e,file:t}){let r=g6({reference:e,referencedIn:t.relativeFilepath,imports:t.imports});if(r==null)throw new j({message:"Failed to locate error "+e,code:j.Code.ResolutionError});let n={name:t.casingsGenerator.generateName(r.typeName),fernFilepath:bN({relativeFilepath:r.relativeFilepath,casingsGenerator:t.casingsGenerator})};return{...n,errorId:Kl.generateErrorId(n)}}function u7a(e){if(typeof e=="string"||e.availability==null)return;let t=typeof e.availability=="string"?{status:e.availability}:e.availability;return EN(e.availability)}function l7a(e){if(typeof e!="string")return e["display-name"]}function aKi(e){if(typeof e!="string")return e.docs}var p7a="value";function f7a({union:e,file:t,typeResolver:r}){let n=qce(e),i=e["default-variant"],o=Object.entries(e.union).map(([a,c])=>{let u=typeof c=="string"?c:typeof c.type=="string"?c.type:void 0,l=t.casingsGenerator.generateNameAndWireValue({wireValue:a,name:CYe({unionKey:a,rawSingleUnionType:c}).name}),p=aKi(c);if(u==null)return{discriminantValue:l,docs:p,shape:uS.noProperties(),displayName:void 0,availability:void 0};let d=t.parseTypeReference(u);return{discriminantValue:l,shape:cKi({rawSingleUnionType:c,rawValueType:u,parsedValueType:d,file:t,typeResolver:r}),docs:aKi(c),displayName:l7a(c),availability:u7a(c)}}),s=i!=null?o.find(a=>(typeof a.discriminantValue=="string"?a.discriminantValue:a.discriminantValue.wireValue)===i):void 0;return vc.union({discriminant:t.casingsGenerator.generateNameAndWireValue({wireValue:n,name:vYe(e).name}),extends:p7(e.extends).map(a=>JS({typeName:a,file:t})),baseProperties:e["base-properties"]!=null?Object.entries(e["base-properties"]).map(([a,c])=>({...KO(c),name:t.casingsGenerator.generateNameAndWireValue({wireValue:a,name:YS({propertyKey:a,property:c}).name}),valueType:t.parseTypeReference(c),propertyAccess:EYe({property:c}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}})):[],types:o,default:s,discriminatorContext:F_f({union:e})})}function qce(e){return e.discriminant==null?"type":typeof e.discriminant=="string"?e.discriminant:e.discriminant.value}function vYe(e){return e.discriminant!=null&&typeof e.discriminant!="string"&&e.discriminant.name!=null?{name:e.discriminant.name,wasExplicitlySet:!0}:{name:qce(e),wasExplicitlySet:!1}}function CYe({unionKey:e,rawSingleUnionType:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function cKi({rawSingleUnionType:e,rawValueType:t,parsedValueType:r,file:n,typeResolver:i}){let o=typeof e!="string"?e.key:void 0,s=i.resolveTypeOrThrow({type:t,file:n}),a=R_f(s),c=d7a(s);return!a&&c._type==="named"&&rf(c.declaration)&&o==null?uS.samePropertiesAsObject(c.name):uS.singleProperty({name:n.casingsGenerator.generateNameAndWireValue({wireValue:D_f(o),name:P_f(o)}),type:r})}function P_f(e){return e!=null?typeof e=="string"?e:e.name??e.value:p7a}function D_f(e){return e!=null?typeof e=="string"?e:e.value:p7a}function R_f(e){return e._type==="container"&&(e.container._type==="nullable"||e.container._type==="optional")}function d7a(e){return e._type==="container"&&(e.container._type==="nullable"||e.container._type==="optional")?d7a(e.container.itemType):e}function F_f({union:e}){return(typeof e.discriminant=="object"&&e.discriminant?.context)==="protocol"?dse.Protocol:dse.Data}Rt();Rt();function dU(e,t){return[{message:`Expected example to be ${t}. Example is: ${typeof e!="number"?JSON.stringify(e):e}`}]}function m7a({rawAlias:e,example:t,file:r,typeResolver:n,exampleResolver:i,workspace:o,breadcrumbs:s,depth:a}){return XS({rawTypeReference:typeof e=="string"?e:e.type,example:t,file:r,typeResolver:n,exampleResolver:i,workspace:o,breadcrumbs:s,depth:a+1})}function h7a({rawEnum:e,example:t,breadcrumbs:r}){let n=e.enum.map(s=>typeof s=="string"?s:s.value),i=n.map(s=>` - ${s}`).join(`
|
|
1589
1589
|
`);if(typeof t!="string")return dU(t,"a string");if(n.includes(t))return[];let o=t;return typeof t=="string"&&t.startsWith("\\$")&&(o=t.slice(1)),n.includes(o)?[]:[{message:`"${t}" is not a valid example for this enum. Enum values are:
|
|
1590
1590
|
`+i}]}Rt();Wi();YA();Wi();function Rkt({type:e,file:t,_default:r,validation:n}){return ev({type:e,_default:r,validation:n,visitor:{primitive:kr.primitive,unknown:kr.unknown,map:({keyType:i,valueType:o})=>kr.container(Qs.map({keyType:i,valueType:o})),list:i=>kr.container(Qs.list(i)),set:i=>kr.container(Qs.set(i)),optional:i=>kr.container(Qs.optional(i)),nullable:i=>kr.container(Qs.nullable(i)),literal:i=>kr.container(Qs.literal(i)),named:i=>kr.named({...JS({typeName:i,file:t}),default:void 0,inline:void 0})}})}function Gce({casingsGenerator:e,rootApiFile:t}){return lu({relativeFilepath:Ws.of("."),definitionFile:{imports:t.imports},casingsGenerator:e,rootApiFile:t})}function lu({defaultUrl:e,relativeFilepath:t,definitionFile:r,casingsGenerator:n,rootApiFile:i}){let o={defaultUrl:e,relativeFilepath:t,fernFilepath:bN({relativeFilepath:t,casingsGenerator:n}),imports:ep(r.imports??{},Ws.of),definitionFile:r,parseTypeReference:s=>typeof s=="string"?Rkt({type:s,_default:void 0,validation:void 0,file:o}):Rkt({type:s.type,_default:s.default,validation:s.validation,file:o}),casingsGenerator:n,rootApiFile:i};return o}var Fkt=sw({generationLanguage:void 0,keywords:void 0,smartCasing:!1});function mU({typeName:e,objectDeclaration:t,filepathOfDeclaration:r,definitionFile:n,workspace:i,typeResolver:o,smartCasing:s,path:a=[],seen:c={}}){let u=[];if(e!=null){let d=c[r]??=new Set;if(d.has(e))return u;d.add(e)}let l=Fkt;s&&(l=sw({generationLanguage:void 0,keywords:void 0,smartCasing:s}));let p=lu({relativeFilepath:r,definitionFile:n,casingsGenerator:l,rootApiFile:i.definition.rootApiFile.contents});if(t.properties!=null)for(let[d,f]of Object.entries(t.properties)){let m=typeof f=="string"?f:f.type,h=o.resolveType({type:m,file:p});h!=null&&u.push({wireKey:d,name:YS({propertyKey:d,property:f}).name,filepathOfDeclaration:r,path:a,propertyType:m,resolvedPropertyType:h,isOptional:h._type==="container"&&h.container._type==="optional",isNullable:h._type==="container"&&h.container._type==="nullable"})}if(t.extends!=null){let d=typeof t.extends=="string"?[t.extends]:t.extends;for(let f of d){let m=o.resolveNamedType({referenceToNamedType:f,file:p});if(m?._type==="named"&&rf(m.declaration)){let h=Q4(i,m.filepath);h!=null&&u.push(...mU({typeName:m.rawName,objectDeclaration:m.declaration,filepathOfDeclaration:m.filepath,definitionFile:h,workspace:i,typeResolver:o,smartCasing:s,path:[...a,{reference:f,followedVia:"extension"},...m.objectPath.map(A=>({reference:A.reference,followedVia:"alias"}))],seen:c}))}}}return u}function kkt({property:e,prefixBreadcrumbs:t=[]}){return[...t,...k_f(e.path),e.wireKey].join(" -> ")}function k_f(e){return e.map(N_f)}function N_f(e){return[Q_f(e),e.reference].join(" ")}function Q_f(e){switch(e.followedVia){case"alias":return"(alias of)";case"extension":return"(extends)"}}function nNe({typeName:e,typeNameForBreadcrumb:t,rawObject:r,file:n,typeResolver:i,exampleResolver:o,workspace:s,example:a,breadcrumbs:c,depth:u}){if(!fa(a))return dU(a,"an object");let l=[],p=mU({typeName:e,objectDeclaration:r,typeResolver:i,definitionFile:n.definitionFile,workspace:s,filepathOfDeclaration:n.relativeFilepath,smartCasing:!1}),d=BAi(p,m=>m.wireKey),f=p.filter(m=>!m.isNullable&&!m.isOptional&&m.resolvedPropertyType._type!=="unknown");for(let m of f)if(!(m.resolvedPropertyType._type==="container"&&m.resolvedPropertyType.container._type==="literal")&&typeof a[m.wireKey]>"u"){let A=`Example is missing required property "${c.length>0?`${c.join(".")}.${m.wireKey}`:m.wireKey}"`;l.push({message:A})}for(let[m,h]of Object.entries(a)){let A=d[m];if(!r["extra-properties"])if(A==null)l.push({message:`Unexpected property "${m}"`});else{let b=Q4(s,A.filepathOfDeclaration);if(b==null)throw new j({message:"Service file does not exist for property: "+A.wireKey,code:j.Code.InternalError});l.push(...XS({rawTypeReference:A.propertyType,example:h,file:lu({relativeFilepath:A.filepathOfDeclaration,definitionFile:b,casingsGenerator:n.casingsGenerator,rootApiFile:s.definition.rootApiFile.contents}),workspace:s,typeResolver:i,exampleResolver:o,breadcrumbs:[...c,`${m}`],depth:u+1}))}}return l}function g7a({rawUnion:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:o,breadcrumbs:s,depth:a}){let c=[];for(let u of e.union){let l=XS({rawTypeReference:typeof u=="string"?u:u.type,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:o,breadcrumbs:s,depth:a+1});if(l.length===0)return[];c.length===0&&c.push(...l)}return c}Rt();function y7a({typeName:e,rawUnion:t,example:r,typeResolver:n,exampleResolver:i,file:o,workspace:s,breadcrumbs:a,depth:c}){if(!fa(r))return dU(r,"an object");let u=qce(t),{[u]:l,...p}=r;if(l==null)return[{message:`Missing discriminant property ("${u}")`}];if(typeof l!="string")return dU(l,"a string");let d=t.union[l];if(l.startsWith("\\$")&&(d=t.union[l.slice(1)]),d==null)return[{message:`Invalid discriminant property: "${l}". Allowed discriminant values:
|
|
@@ -1626,7 +1626,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
|
|
|
1626
1626
|
`,s+1),c=a===-1?"":o.slice(a+1);String(n.stack).endsWith(c)||(n.stack+=`
|
|
1627
1627
|
`+o)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=C7(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&q2t.assertOptions(n,{silentJSONParsing:xU.transitional(xU.boolean),forcedJSONParsing:xU.transitional(xU.boolean),clarifyTimeoutError:xU.transitional(xU.boolean),legacyInterceptorReqResOrdering:xU.transitional(xU.boolean)},!1),i!=null&&(tr.isFunction(i)?r.paramsSerializer={serialize:i}:q2t.assertOptions(i,{encode:xU.function,serialize:xU.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),q2t.assertOptions(r,{baseUrl:xU.spelling("baseURL"),withXsrfToken:xU.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&tr.merge(o.common,o[r.method]);o&&tr.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),r.headers=aE.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;c=c&&h.synchronous;let A=r.transitional||N0e;A&&A.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});let u=[];this.interceptors.response.forEach(function(h){u.push(h.fulfilled,h.rejected)});let l,p=0,d;if(!c){let m=[IRr.bind(this),void 0];for(m.unshift(...a),m.push(...u),d=m.length,l=Promise.resolve(r);p<d;)l=l.then(m[p++],m[p++]);return l}d=a.length;let f=r;for(;p<d;){let m=a[p++],h=a[p++];try{f=m(f)}catch(A){h.call(this,A);break}}try{l=IRr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=u.length;p<d;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=C7(this.defaults,t);let r=TNe(t.baseURL,t.url,t.allowAbsoluteUrls);return BNe(r,t.params,t.paramsSerializer)}};tr.forEach(["delete","get","head","options"],function(t){cXe.prototype[t]=function(r,n){return this.request(C7(n||{},{method:t,url:r,data:(n||{}).data}))}});tr.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(C7(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}cXe.prototype[t]=r(),cXe.prototype[t+"Form"]=r(!0)});var G2t=cXe;var KZi=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{n.subscribe(a),o=a}).then(i);return s.cancel=function(){n.unsubscribe(o)},s},t(function(o,s,a){n.reason||(n.reason=new b6(o,s,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},KYa=KZi;function JZi(e){return function(r){return e.apply(null,r)}}function YZi(e){return tr.isObject(e)&&e.isAxiosError===!0}var XZi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(XZi).forEach(([e,t])=>{XZi[t]=e});var JYa=XZi;function YYa(e){let t=new G2t(e),r=P2t(G2t.prototype.request,t);return tr.extend(r,G2t.prototype,t,{allOwnKeys:!0}),tr.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return YYa(C7(e,i))},r}var WC=YYa(iXe);WC.Axios=G2t;WC.CanceledError=b6;WC.CancelToken=KYa;WC.isCancel=Q2t;WC.VERSION=DNe;WC.toFormData=k0e;WC.AxiosError=Eo;WC.Cancel=WC.CanceledError;WC.all=function(t){return Promise.all(t)};WC.spread=JZi;WC.isAxiosError=YZi;WC.mergeConfig=C7;WC.AxiosHeaders=aE;WC.formToJSON=e=>hRr(tr.isHTMLForm(e)?new FormData(e):e);WC.getAdapter=ERr.getAdapter;WC.HttpStatusCode=JYa;WC.default=WC;var ly=WC;var{Axios:Z50,AxiosError:XYa,CanceledError:eG0,isCancel:tG0,CancelToken:rG0,VERSION:nG0,all:iG0,Cancel:oG0,isAxiosError:sG0,spread:aG0,toFormData:cG0,AxiosHeaders:uG0,HttpStatusCode:lG0,formToJSON:pG0,getAdapter:fG0,mergeConfig:dG0}=ly;var hZa=require("fs"),EXe=require("fs/promises");var gZa=require("os"),AZa=Ie(require("path"),1),yZa=require("stream/promises");var PXa=Ie(require("events"),1),cF=Ie(require("fs"),1),XRr=require("events"),Heo=Ie(require("stream"),1),DXa=require("string_decoder"),Jeo=Ie(require("path"),1),qNe=Ie(require("fs"),1),eFr=require("path"),kXa=require("events"),HRr=Ie(require("assert"),1),G0e=require("buffer"),nXa=Ie(require("zlib"),1),NXa=Ie(require("zlib"),1),VNe=require("path"),zXa=require("path"),mNt=Ie(require("fs"),1),_7=Ie(require("fs"),1),Oeo=Ie(require("path"),1),$Xa=require("path"),jeo=Ie(require("path"),1),ito=Ie(require("fs"),1),eZa=Ie(require("assert"),1),oto=require("crypto"),td=Ie(require("fs"),1),HC=Ie(require("path"),1),sto=Ie(require("fs"),1),ANt=Ie(require("fs"),1),yXe=Ie(require("path"),1),TN=Ie(require("fs"),1),uZa=Ie(require("fs/promises"),1),hNt=Ie(require("path"),1),ato=require("path"),BN=Ie(require("fs"),1),uto=Ie(require("path"),1),aQf=Object.defineProperty,cQf=(e,t)=>{for(var r in t)aQf(e,r,{get:t[r],enumerable:!0})},ZYa=typeof process=="object"&&process?process:{stdout:null,stderr:null},uQf=e=>!!e&&typeof e=="object"&&(e instanceof HNe||e instanceof Heo.default||lQf(e)||pQf(e)),lQf=e=>!!e&&typeof e=="object"&&e instanceof XRr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==Heo.default.Writable.prototype.pipe,pQf=e=>!!e&&typeof e=="object"&&e instanceof XRr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",aue=Symbol("EOF"),cue=Symbol("maybeEmitEnd"),Q0e=Symbol("emittedEnd"),CRr=Symbol("emittingEnd"),W2t=Symbol("emittedError"),xRr=Symbol("closed"),eXa=Symbol("read"),wRr=Symbol("flush"),tXa=Symbol("flushChunk"),x7=Symbol("encoding"),uXe=Symbol("decoder"),s_=Symbol("flowing"),$2t=Symbol("paused"),dXe=Symbol("resume"),a_=Symbol("buffer"),aF=Symbol("pipes"),c_=Symbol("bufferLength"),ZZi=Symbol("bufferPush"),SRr=Symbol("bufferShift"),XO=Symbol("objectMode"),Ev=Symbol("destroyed"),eeo=Symbol("error"),teo=Symbol("emitData"),rXa=Symbol("emitEnd"),reo=Symbol("emitEnd2"),CY=Symbol("async"),neo=Symbol("abort"),_Rr=Symbol("aborted"),H2t=Symbol("signal"),FNe=Symbol("dataListeners"),E6=Symbol("discarded"),K2t=e=>Promise.resolve().then(e),fQf=e=>e(),dQf=e=>e==="end"||e==="finish"||e==="prefinish",mQf=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,hQf=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),RXa=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[dXe](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},gQf=class extends RXa{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=n=>this.dest.emit("error",n),e.on("error",this.proxyErrors)}},AQf=e=>!!e.objectMode,yQf=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",HNe=class extends XRr.EventEmitter{[s_]=!1;[$2t]=!1;[aF]=[];[a_]=[];[XO];[x7];[CY];[uXe];[aue]=!1;[Q0e]=!1;[CRr]=!1;[xRr]=!1;[W2t]=null;[c_]=0;[Ev]=!1;[H2t];[_Rr]=!1;[FNe]=0;[E6]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");AQf(t)?(this[XO]=!0,this[x7]=null):yQf(t)?(this[x7]=t.encoding,this[XO]=!1):(this[XO]=!1,this[x7]=null),this[CY]=!!t.async,this[uXe]=this[x7]?new DXa.StringDecoder(this[x7]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[a_]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[aF]});let{signal:r}=t;r&&(this[H2t]=r,r.aborted?this[neo]():r.addEventListener("abort",()=>this[neo]()))}get bufferLength(){return this[c_]}get encoding(){return this[x7]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[XO]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[CY]}set async(e){this[CY]=this[CY]||!!e}[neo](){this[_Rr]=!0,this.emit("abort",this[H2t]?.reason),this.destroy(this[H2t]?.reason)}get aborted(){return this[_Rr]}set aborted(e){}write(e,t,r){if(this[_Rr])return!1;if(this[aue])throw new Error("write after end");if(this[Ev])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let n=this[CY]?K2t:fQf;if(!this[XO]&&!Buffer.isBuffer(e)){if(hQf(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(mQf(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[XO]?(this[s_]&&this[c_]!==0&&this[wRr](!0),this[s_]?this.emit("data",e):this[ZZi](e),this[c_]!==0&&this.emit("readable"),r&&n(r),this[s_]):e.length?(typeof e=="string"&&!(t===this[x7]&&!this[uXe]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[x7]&&(e=this[uXe].write(e)),this[s_]&&this[c_]!==0&&this[wRr](!0),this[s_]?this.emit("data",e):this[ZZi](e),this[c_]!==0&&this.emit("readable"),r&&n(r),this[s_]):(this[c_]!==0&&this.emit("readable"),r&&n(r),this[s_])}read(e){if(this[Ev])return null;if(this[E6]=!1,this[c_]===0||e===0||e&&e>this[c_])return this[cue](),null;this[XO]&&(e=null),this[a_].length>1&&!this[XO]&&(this[a_]=[this[x7]?this[a_].join(""):Buffer.concat(this[a_],this[c_])]);let t=this[eXa](e||null,this[a_][0]);return this[cue](),t}[eXa](e,t){if(this[XO])this[SRr]();else{let r=t;e===r.length||e===null?this[SRr]():typeof r=="string"?(this[a_][0]=r.slice(e),t=r.slice(0,e),this[c_]-=e):(this[a_][0]=r.subarray(e),t=r.subarray(0,e),this[c_]-=e)}return this.emit("data",t),!this[a_].length&&!this[aue]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[aue]=!0,this.writable=!1,(this[s_]||!this[$2t])&&this[cue](),this}[dXe](){this[Ev]||(!this[FNe]&&!this[aF].length&&(this[E6]=!0),this[$2t]=!1,this[s_]=!0,this.emit("resume"),this[a_].length?this[wRr]():this[aue]?this[cue]():this.emit("drain"))}resume(){return this[dXe]()}pause(){this[s_]=!1,this[$2t]=!0,this[E6]=!1}get destroyed(){return this[Ev]}get flowing(){return this[s_]}get paused(){return this[$2t]}[ZZi](e){this[XO]?this[c_]+=1:this[c_]+=e.length,this[a_].push(e)}[SRr](){return this[XO]?this[c_]-=1:this[c_]-=this[a_][0].length,this[a_].shift()}[wRr](e=!1){do;while(this[tXa](this[SRr]())&&this[a_].length);!e&&!this[a_].length&&!this[aue]&&this.emit("drain")}[tXa](e){return this.emit("data",e),this[s_]}pipe(e,t){if(this[Ev])return e;this[E6]=!1;let r=this[Q0e];return t=t||{},e===ZYa.stdout||e===ZYa.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[aF].push(t.proxyErrors?new gQf(this,e,t):new RXa(this,e,t)),this[CY]?K2t(()=>this[dXe]()):this[dXe]()),e}unpipe(e){let t=this[aF].find(r=>r.dest===e);t&&(this[aF].length===1?(this[s_]&&this[FNe]===0&&(this[s_]=!1),this[aF]=[]):this[aF].splice(this[aF].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[E6]=!1,this[FNe]++,!this[aF].length&&!this[s_]&&this[dXe]();else if(e==="readable"&&this[c_]!==0)super.emit("readable");else if(dQf(e)&&this[Q0e])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[W2t]){let n=t;this[CY]?K2t(()=>n.call(this,this[W2t])):n.call(this,this[W2t])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[FNe]=this.listeners("data").length,this[FNe]===0&&!this[E6]&&!this[aF].length&&(this[s_]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[FNe]=0,!this[E6]&&!this[aF].length&&(this[s_]=!1)),t}get emittedEnd(){return this[Q0e]}[cue](){!this[CRr]&&!this[Q0e]&&!this[Ev]&&this[a_].length===0&&this[aue]&&(this[CRr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[xRr]&&this.emit("close"),this[CRr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==Ev&&this[Ev])return!1;if(e==="data")return!this[XO]&&!r?!1:this[CY]?(K2t(()=>this[teo](r)),!0):this[teo](r);if(e==="end")return this[rXa]();if(e==="close"){if(this[xRr]=!0,!this[Q0e]&&!this[Ev])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[W2t]=r,super.emit(eeo,r);let i=!this[H2t]||this.listeners("error").length?super.emit("error",r):!1;return this[cue](),i}else if(e==="resume"){let i=super.emit("resume");return this[cue](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let n=super.emit(e,...t);return this[cue](),n}[teo](e){for(let r of this[aF])r.dest.write(e)===!1&&this.pause();let t=this[E6]?!1:super.emit("data",e);return this[cue](),t}[rXa](){return this[Q0e]?!1:(this[Q0e]=!0,this.readable=!1,this[CY]?(K2t(()=>this[reo]()),!0):this[reo]())}[reo](){if(this[uXe]){let t=this[uXe].end();if(t){for(let r of this[aF])r.dest.write(t);this[E6]||super.emit("data",t)}}for(let t of this[aF])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[XO]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[XO]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[XO])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[x7]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Ev,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[E6]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[aue])return t();let n,i,o=u=>{this.off("data",s),this.off("end",a),this.off(Ev,c),t(),i(u)},s=u=>{this.off("error",o),this.off("end",a),this.off(Ev,c),this.pause(),n({value:u,done:!!this[aue]})},a=()=>{this.off("error",o),this.off("data",s),this.off(Ev,c),t(),n({done:!0,value:void 0})},c=()=>o(new Error("stream destroyed"));return new Promise((u,l)=>{i=l,n=u,this.once(Ev,c),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[E6]=!1;let e=!1,t=()=>(this.pause(),this.off(eeo,t),this.off(Ev,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}};return this.once("end",t),this.once(eeo,t),this.once(Ev,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[Ev])return e?this.emit("error",e):this.emit(Ev),this;this[Ev]=!0,this[E6]=!0,this[a_].length=0,this[c_]=0;let t=this;return typeof t.close=="function"&&!this[xRr]&&t.close(),e?this.emit("error",e):this.emit(Ev),this}static get isStream(){return uQf}},bQf=cF.default.writev,$0e=Symbol("_autoClose"),T7=Symbol("_close"),J2t=Symbol("_ended"),kh=Symbol("_fd"),ieo=Symbol("_finished"),fue=Symbol("_flags"),oeo=Symbol("_flush"),Seo=Symbol("_handleChunk"),_eo=Symbol("_makeBuf"),sNt=Symbol("_mode"),BRr=Symbol("_needDrain"),AXe=Symbol("_onerror"),bXe=Symbol("_onopen"),seo=Symbol("_onread"),mXe=Symbol("_onwrite"),H0e=Symbol("_open"),B7=Symbol("_path"),U0e=Symbol("_pos"),xY=Symbol("_queue"),hXe=Symbol("_read"),aeo=Symbol("_readSize"),pue=Symbol("_reading"),Y2t=Symbol("_remain"),ceo=Symbol("_size"),QRr=Symbol("_write"),kNe=Symbol("_writing"),jRr=Symbol("_defaultFlag"),GNe=Symbol("_errored"),Keo=class extends HNe{[GNe]=!1;[kh];[B7];[aeo];[pue]=!1;[ceo];[Y2t];[$0e];constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[GNe]=!1,this[kh]=typeof t.fd=="number"?t.fd:void 0,this[B7]=e,this[aeo]=t.readSize||16*1024*1024,this[pue]=!1,this[ceo]=typeof t.size=="number"?t.size:1/0,this[Y2t]=this[ceo],this[$0e]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[kh]=="number"?this[hXe]():this[H0e]()}get fd(){return this[kh]}get path(){return this[B7]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[H0e](){cF.default.open(this[B7],"r",(e,t)=>this[bXe](e,t))}[bXe](e,t){e?this[AXe](e):(this[kh]=t,this.emit("open",t),this[hXe]())}[_eo](){return Buffer.allocUnsafe(Math.min(this[aeo],this[Y2t]))}[hXe](){if(!this[pue]){this[pue]=!0;let e=this[_eo]();if(e.length===0)return process.nextTick(()=>this[seo](null,0,e));cF.default.read(this[kh],e,0,e.length,null,(t,r,n)=>this[seo](t,r,n))}}[seo](e,t,r){this[pue]=!1,e?this[AXe](e):this[Seo](t,r)&&this[hXe]()}[T7](){if(this[$0e]&&typeof this[kh]=="number"){let e=this[kh];this[kh]=void 0,cF.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[AXe](e){this[pue]=!0,this[T7](),this.emit("error",e)}[Seo](e,t){let r=!1;return this[Y2t]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[Y2t]<=0)&&(r=!1,this[T7](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[kh]=="number"&&this[hXe](),!1;case"error":return this[GNe]?!1:(this[GNe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},EQf=class extends Keo{[H0e](){let e=!0;try{this[bXe](null,cF.default.openSync(this[B7],"r")),e=!1}finally{e&&this[T7]()}}[hXe](){let e=!0;try{if(!this[pue]){this[pue]=!0;do{let t=this[_eo](),r=t.length===0?0:cF.default.readSync(this[kh],t,0,t.length,null);if(!this[Seo](r,t))break}while(!0);this[pue]=!1}e=!1}finally{e&&this[T7]()}}[T7](){if(this[$0e]&&typeof this[kh]=="number"){let e=this[kh];this[kh]=void 0,cF.default.closeSync(e),this.emit("close")}}},ZRr=class extends PXa.default{readable=!1;writable=!0;[GNe]=!1;[kNe]=!1;[J2t]=!1;[xY]=[];[BRr]=!1;[B7];[sNt];[$0e];[kh];[jRr];[fue];[ieo]=!1;[U0e];constructor(e,t){t=t||{},super(t),this[B7]=e,this[kh]=typeof t.fd=="number"?t.fd:void 0,this[sNt]=t.mode===void 0?438:t.mode,this[U0e]=typeof t.start=="number"?t.start:void 0,this[$0e]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[U0e]!==void 0?"r+":"w";this[jRr]=t.flags===void 0,this[fue]=t.flags===void 0?r:t.flags,this[kh]===void 0&&this[H0e]()}emit(e,...t){if(e==="error"){if(this[GNe])return!1;this[GNe]=!0}return super.emit(e,...t)}get fd(){return this[kh]}get path(){return this[B7]}[AXe](e){this[T7](),this[kNe]=!0,this.emit("error",e)}[H0e](){cF.default.open(this[B7],this[fue],this[sNt],(e,t)=>this[bXe](e,t))}[bXe](e,t){this[jRr]&&this[fue]==="r+"&&e&&e.code==="ENOENT"?(this[fue]="w",this[H0e]()):e?this[AXe](e):(this[kh]=t,this.emit("open",t),this[kNe]||this[oeo]())}end(e,t){return e&&this.write(e,t),this[J2t]=!0,!this[kNe]&&!this[xY].length&&typeof this[kh]=="number"&&this[mXe](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[J2t]?(this.emit("error",new Error("write() after end()")),!1):this[kh]===void 0||this[kNe]||this[xY].length?(this[xY].push(e),this[BRr]=!0,!1):(this[kNe]=!0,this[QRr](e),!0)}[QRr](e){cF.default.write(this[kh],e,0,e.length,this[U0e],(t,r)=>this[mXe](t,r))}[mXe](e,t){e?this[AXe](e):(this[U0e]!==void 0&&typeof t=="number"&&(this[U0e]+=t),this[xY].length?this[oeo]():(this[kNe]=!1,this[J2t]&&!this[ieo]?(this[ieo]=!0,this[T7](),this.emit("finish")):this[BRr]&&(this[BRr]=!1,this.emit("drain"))))}[oeo](){if(this[xY].length===0)this[J2t]&&this[mXe](null,0);else if(this[xY].length===1)this[QRr](this[xY].pop());else{let e=this[xY];this[xY]=[],bQf(this[kh],e,this[U0e],(t,r)=>this[mXe](t,r))}}[T7](){if(this[$0e]&&typeof this[kh]=="number"){let e=this[kh];this[kh]=void 0,cF.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},FXa=class extends ZRr{[H0e](){let e;if(this[jRr]&&this[fue]==="r+")try{e=cF.default.openSync(this[B7],this[fue],this[sNt])}catch(t){if(t?.code==="ENOENT")return this[fue]="w",this[H0e]();throw t}else e=cF.default.openSync(this[B7],this[fue],this[sNt]);this[bXe](null,e)}[T7](){if(this[$0e]&&typeof this[kh]=="number"){let e=this[kh];this[kh]=void 0,cF.default.closeSync(e),this.emit("close")}}[QRr](e){let t=!0;try{this[mXe](null,cF.default.writeSync(this[kh],e,0,e.length,this[U0e])),t=!1}finally{if(t)try{this[T7]()}catch{}}}},IQf=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),vQf=e=>!!e.sync&&!!e.file,CQf=e=>!e.sync&&!!e.file,xQf=e=>!!e.sync&&!e.file,wQf=e=>!e.sync&&!e.file,SQf=e=>!!e.file,_Qf=e=>IQf.get(e)||e,Yeo=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=_Qf(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},gNt=(e,t,r,n,i)=>Object.assign((o=[],s,a)=>{Array.isArray(o)&&(s=o,o={}),typeof s=="function"&&(a=s,s=void 0),s=s?Array.from(s):[];let c=Yeo(o);if(i?.(c,s),vQf(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(c,s)}else if(CQf(c)){let u=t(c,s);return a?u.then(()=>a(),a):u}else if(xQf(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,s)}else if(wQf(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(c,s)}throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:n,validate:i}),BQf=NXa.default.constants||{ZLIB_VERNUM:4736},_Y=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},BQf)),TQf=G0e.Buffer.concat,iXa=Object.getOwnPropertyDescriptor(G0e.Buffer,"concat"),OQf=e=>e,ueo=iXa?.writable===!0||iXa?.set!==void 0?e=>{G0e.Buffer.concat=e?OQf:TQf}:e=>{},WNe=Symbol("_superWrite"),TRr=class extends Error{code;errno;constructor(e,t){super("zlib: "+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,t??this.constructor)}get name(){return"ZlibError"}},leo=Symbol("flushFlag"),Xeo=class extends HNe{#e=!1;#t=!1;#r;#n;#i;#o;#s;get sawError(){return this.#e}get handle(){return this.#o}get flushFlag(){return this.#r}constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(e),this.#r=e.flush??0,this.#n=e.finishFlush??0,this.#i=e.fullFlushFlag??0,typeof nXa[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new nXa[t](e)}catch(r){throw new TRr(r,this.constructor)}this.#s=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#o?.on("error",r=>this.#s(new TRr(r))),this.once("end",()=>this.close)}close(){this.#o&&(this.#o.close(),this.#o=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,HRr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(G0e.Buffer.alloc(0),{[leo]:e})))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&(t?this.write(e,t):this.write(e)),this.flush(this.#n),this.#t=!0,super.end(r)}get ended(){return this.#t}[WNe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=G0e.Buffer.from(e,t)),this.#e)return;(0,HRr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},ueo(!0);let s;try{let c=typeof e[leo]=="number"?e[leo]:this.#r;s=this.#o._processChunk(e,c),ueo(!1)}catch(c){ueo(!1),this.#s(new TRr(c,this.write))}finally{this.#o&&(this.#o._handle=n,n.close=i,this.#o.close=o,this.#o.removeAllListeners("error"))}this.#o&&this.#o.on("error",c=>this.#s(new TRr(c,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let c=s[0];a=this[WNe](G0e.Buffer.from(c));for(let u=1;u<s.length;u++)a=this[WNe](s[u])}else a=this[WNe](G0e.Buffer.from(s));return r&&r(),a}},QXa=class extends Xeo{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||_Y.Z_NO_FLUSH,e.finishFlush=e.finishFlush||_Y.Z_FINISH,e.fullFlushFlag=_Y.Z_FULL_FLUSH,super(e,t),this.#e=e.level,this.#t=e.strategy}params(e,t){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==e||this.#t!==t){this.flush(_Y.Z_SYNC_FLUSH),(0,HRr.default)(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(e,t)}finally{this.handle.flush=r}this.handle&&(this.#e=e,this.#t=t)}}}},PQf=class extends QXa{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[WNe](e){return this.#e?(this.#e=!1,e[9]=255,super[WNe](e)):super[WNe](e)}},DQf=class extends QXa{constructor(e){super(e,"Unzip")}},jXa=class extends Xeo{constructor(e,t){e=e||{},e.flush=e.flush||_Y.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||_Y.BROTLI_OPERATION_FINISH,e.fullFlushFlag=_Y.BROTLI_OPERATION_FLUSH,super(e,t)}},RQf=class extends jXa{constructor(e){super(e,"BrotliCompress")}},FQf=class extends jXa{constructor(e){super(e,"BrotliDecompress")}},MXa=class extends Xeo{constructor(e,t){e=e||{},e.flush=e.flush||_Y.ZSTD_e_continue,e.finishFlush=e.finishFlush||_Y.ZSTD_e_end,e.fullFlushFlag=_Y.ZSTD_e_flush,super(e,t)}},kQf=class extends MXa{constructor(e){super(e,"ZstdCompress")}},NQf=class extends MXa{constructor(e){super(e,"ZstdDecompress")}},QQf=(e,t)=>{if(Number.isSafeInteger(e))e<0?MQf(e,t):jQf(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},jQf=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},MQf=(e,t)=>{t[0]=255;var r=!1;e=e*-1;for(var n=t.length;n>1;n--){var i=e&255;e=Math.floor(e/256),r?t[n-1]=LXa(i):i===0?t[n-1]=0:(r=!0,t[n-1]=UXa(i))}},LQf=e=>{let t=e[0],r=t===128?zQf(e.subarray(1,e.length)):t===255?UQf(e):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},UQf=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=LXa(o):o===0?s=o:(n=!0,s=UXa(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},zQf=e=>{for(var t=e.length,r=0,n=t-1;n>-1;n--){var i=Number(e[n]);i!==0&&(r+=i*Math.pow(256,t-n-1))}return r},LXa=e=>(255^e)&255,UXa=e=>(255^e)+1&255,VQf={};cQf(VQf,{code:()=>Zeo,isCode:()=>MRr,isName:()=>qQf,name:()=>tFr});var MRr=e=>tFr.has(e),qQf=e=>Zeo.has(e),tFr=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Zeo=new Map(Array.from(tFr).map(e=>[e[1],e[0]])),$Ne=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(e,t=0,r,n){Buffer.isBuffer(e)?this.decode(e,t||0,r,n):e&&this.#t(e)}decode(e,t,r,n){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");this.path=r?.path??NNe(e,t,100),this.mode=r?.mode??n?.mode??z0e(e,t+100,8),this.uid=r?.uid??n?.uid??z0e(e,t+108,8),this.gid=r?.gid??n?.gid??z0e(e,t+116,8),this.size=r?.size??n?.size??z0e(e,t+124,12),this.mtime=r?.mtime??n?.mtime??peo(e,t+136,12),this.cksum=z0e(e,t+148,12),n&&this.#t(n,!0),r&&this.#t(r);let i=NNe(e,t+156,1);if(MRr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=NNe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=r?.uname??n?.uname??NNe(e,t+265,32),this.gname=r?.gname??n?.gname??NNe(e,t+297,32),this.devmaj=r?.devmaj??n?.devmaj??z0e(e,t+329,8)??0,this.devmin=r?.devmin??n?.devmin??z0e(e,t+337,8)??0,e[t+475]!==0){let s=NNe(e,t+345,155);this.path=s+"/"+this.path}else{let s=NNe(e,t+345,130);s&&(this.path=s+"/"+this.path),this.atime=r?.atime??n?.atime??peo(e,t+476,12),this.ctime=r?.ctime??n?.ctime??peo(e,t+488,12)}let o=256;for(let s=t;s<t+148;s++)o+=e[s];for(let s=t+156;s<t+512;s++)o+=e[s];this.cksumValid=o===this.cksum,this.cksum===void 0&&o===256&&(this.nullBlock=!0)}#t(e,t=!1){Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t||r==="linkpath"&&t||r==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=GQf(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=QNe(e,t,100,i)||this.needPax,this.needPax=V0e(e,t+100,8,this.mode)||this.needPax,this.needPax=V0e(e,t+108,8,this.uid)||this.needPax,this.needPax=V0e(e,t+116,8,this.gid)||this.needPax,this.needPax=V0e(e,t+124,12,this.size)||this.needPax,this.needPax=feo(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=QNe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=QNe(e,t+265,32,this.uname)||this.needPax,this.needPax=QNe(e,t+297,32,this.gname)||this.needPax,this.needPax=V0e(e,t+329,8,this.devmaj)||this.needPax,this.needPax=V0e(e,t+337,8,this.devmin)||this.needPax,this.needPax=QNe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=QNe(e,t+345,155,o)||this.needPax:(this.needPax=QNe(e,t+345,130,o)||this.needPax,this.needPax=feo(e,t+476,12,this.atime)||this.needPax,this.needPax=feo(e,t+488,12,this.ctime)||this.needPax);let s=256;for(let a=t;a<t+148;a++)s+=e[a];for(let a=t+156;a<t+512;a++)s+=e[a];return this.cksum=s,V0e(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:tFr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(Zeo.get(e));if(MRr(t)||t==="Unsupported")this.#e=t;else if(MRr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},GQf=(e,t)=>{let r=e,n="",i,o=VNe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=VNe.posix.dirname(r),r=VNe.posix.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=t?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=t?i=[r.slice(0,99),n,!0]:(r=VNe.posix.join(VNe.posix.basename(n),r),n=VNe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},NNe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),peo=(e,t,r)=>WQf(z0e(e,t,r)),WQf=e=>e===void 0?void 0:new Date(e*1e3),z0e=(e,t,r)=>Number(e[t])&128?LQf(e.subarray(t,t+r)):HQf(e,t,r),$Qf=e=>isNaN(e)?void 0:e,HQf=(e,t,r)=>$Qf(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),KQf={12:8589934591,8:2097151},V0e=(e,t,r,n)=>n===void 0?!1:n>KQf[r]||n<0?(QQf(n,e.subarray(t,t+r)),!0):(JQf(e,t,r,n),!1),JQf=(e,t,r,n)=>e.write(YQf(n,r),t,r,"ascii"),YQf=(e,t)=>XQf(Math.floor(e).toString(8),t),XQf=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",feo=(e,t,r,n)=>n===void 0?!1:V0e(e,t,r,n.getTime()/1e3),ZQf=new Array(156).join("\0"),QNe=(e,t,r,n)=>n===void 0?!1:(e.write(n+ZQf,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),KRr=class VXa{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,r=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=r,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(t),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let o=0;o<512;o++)i[o]=0;new $Ne({path:("PaxHeader/"+(0,zXa.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(t,512,r,"utf8");for(let o=r+512;o<i.length;o++)i[o]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let r=this[t],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+n+`
|
|
1628
1628
|
`,o=Buffer.byteLength(i),s=Math.floor(Math.log(o)/Math.log(10))+1;return o+s>=Math.pow(10,s)&&(s+=1),s+o+i}static parse(t,r,n=!1){return new VXa(ejf(tjf(t),r),n)}},ejf=(e,t)=>t?Object.assign({},t,e):e,tjf=e=>e.replace(/\n$/,"").split(`
|
|
1629
|
-
`).reduce(rjf,Object.create(null)),rjf=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},njf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Jp=njf!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),qXa=class extends HNe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=Jp(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?Jp(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=Jp(e.path)),e.linkpath&&(e.linkpath=Jp(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},rFr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},ijf=1024*1024,Beo=Buffer.from([31,139]),Teo=Buffer.from([40,181,47,253]),ojf=Math.max(Beo.length,Teo.length),wU=Symbol("state"),jNe=Symbol("writeEntry"),uue=Symbol("readEntry"),deo=Symbol("nextEntry"),oXa=Symbol("processEntry"),wY=Symbol("extendedHeader"),X2t=Symbol("globalExtendedHeader"),j0e=Symbol("meta"),sXa=Symbol("emitMeta"),g0=Symbol("buffer"),lue=Symbol("queue"),M0e=Symbol("ended"),meo=Symbol("emittedEnd"),MNe=Symbol("emit"),$C=Symbol("unzip"),ORr=Symbol("consumeChunk"),PRr=Symbol("consumeChunkSub"),heo=Symbol("consumeBody"),aXa=Symbol("consumeMeta"),cXa=Symbol("consumeHeader"),Z2t=Symbol("consuming"),geo=Symbol("bufferConcat"),DRr=Symbol("maybeEnd"),lXe=Symbol("writing"),L0e=Symbol("aborted"),RRr=Symbol("onDone"),LNe=Symbol("sawValidEntry"),FRr=Symbol("sawNullBlock"),kRr=Symbol("sawEOF"),uXa=Symbol("closeStream"),sjf=()=>!0,dNt=class extends kXa.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[lue]=[];[g0];[uue];[jNe];[wU]="begin";[j0e]="";[wY];[X2t];[M0e]=!1;[$C];[L0e]=!1;[LNe];[FRr]=!1;[kRr]=!1;[lXe]=!1;[Z2t]=!1;[meo]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(RRr,()=>{(this[wU]==="begin"||this[LNe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(RRr,e.ondone):this.on(RRr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||ijf,this.filter=typeof e.filter=="function"?e.filter:sjf;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[uXa]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){rFr(this,e,t,r)}[cXa](e,t){this[LNe]===void 0&&(this[LNe]=!1);let r;try{r=new $Ne(e,t,this[wY],this[X2t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[FRr]?(this[kRr]=!0,this[wU]==="begin"&&(this[wU]="header"),this[MNe]("eof")):(this[FRr]=!0,this[MNe]("nullBlock"));else if(this[FRr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[jNe]=new qXa(r,this[wY],this[X2t]);if(!this[LNe])if(i.remain){let o=()=>{i.invalid||(this[LNe]=!0)};i.on("end",o)}else this[LNe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[MNe]("ignoredEntry",i),this[wU]="ignore",i.resume()):i.size>0&&(this[j0e]="",i.on("data",o=>this[j0e]+=o),this[wU]="meta"):(this[wY]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[MNe]("ignoredEntry",i),this[wU]=i.remain?"ignore":"header",i.resume()):(i.remain?this[wU]="body":(this[wU]="header",i.end()),this[uue]?this[lue].push(i):(this[lue].push(i),this[deo]())))}}}[uXa](){queueMicrotask(()=>this.emit("close"))}[oXa](e){let t=!0;if(!e)this[uue]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[uue]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[deo]()),t=!1);return t}[deo](){do;while(this[oXa](this[lue].shift()));if(this[lue].length===0){let e=this[uue];!e||e.flowing||e.size===e.remain?this[lXe]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[heo](e,t){let r=this[jNe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[wU]="header",this[jNe]=void 0,r.end()),i.length}[aXa](e,t){let r=this[jNe],n=this[heo](e,t);return!this[jNe]&&r&&this[sXa](r),n}[MNe](e,t,r){this[lue].length===0&&!this[uue]?this.emit(e,t,r):this[lue].push([e,t,r])}[sXa](e){switch(this[MNe]("meta",this[j0e]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[wY]=KRr.parse(this[j0e],this[wY],!1);break;case"GlobalExtendedHeader":this[X2t]=KRr.parse(this[j0e],this[X2t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[wY]??Object.create(null);this[wY]=t,t.path=this[j0e].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[wY]||Object.create(null);this[wY]=t,t.linkpath=this[j0e].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[L0e]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[L0e])return r?.(),!1;if((this[$C]===void 0||this.brotli===void 0&&this[$C]===!1)&&e){if(this[g0]&&(e=Buffer.concat([this[g0],e]),this[g0]=void 0),e.length<ojf)return this[g0]=e,r?.(),!0;for(let s=0;this[$C]===void 0&&s<Beo.length;s++)e[s]!==Beo[s]&&(this[$C]=!1);let i=!1;if(this[$C]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<Teo.length;s++)if(e[s]!==Teo[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[$C]===!1&&o)if(e.length<512)if(this[M0e])this.brotli=!0;else return this[g0]=e,r?.(),!0;else try{new $Ne(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[$C]===void 0||this[$C]===!1&&(this.brotli||i)){let s=this[M0e];this[M0e]=!1,this[$C]=this[$C]===void 0?new DQf({}):i?new NQf({}):new FQf({}),this[$C].on("data",c=>this[ORr](c)),this[$C].on("error",c=>this.abort(c)),this[$C].on("end",()=>{this[M0e]=!0,this[ORr]()}),this[lXe]=!0;let a=!!this[$C][s?"end":"write"](e);return this[lXe]=!1,r?.(),a}}this[lXe]=!0,this[$C]?this[$C].write(e):this[ORr](e),this[lXe]=!1;let n=this[lue].length>0?!1:this[uue]?this[uue].flowing:!0;return!n&&this[lue].length===0&&this[uue]?.once("drain",()=>this.emit("drain")),r?.(),n}[geo](e){e&&!this[L0e]&&(this[g0]=this[g0]?Buffer.concat([this[g0],e]):e)}[DRr](){if(this[M0e]&&!this[meo]&&!this[L0e]&&!this[Z2t]){this[meo]=!0;let e=this[jNe];if(e&&e.blockRemain){let t=this[g0]?this[g0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[g0]&&e.write(this[g0]),e.end()}this[MNe](RRr)}}[ORr](e){if(this[Z2t]&&e)this[geo](e);else if(!e&&!this[g0])this[DRr]();else if(e){if(this[Z2t]=!0,this[g0]){this[geo](e);let t=this[g0];this[g0]=void 0,this[PRr](t)}else this[PRr](e);for(;this[g0]&&this[g0]?.length>=512&&!this[L0e]&&!this[kRr];){let t=this[g0];this[g0]=void 0,this[PRr](t)}this[Z2t]=!1}(!this[g0]||this[M0e])&&this[DRr]()}[PRr](e){let t=0,r=e.length;for(;t+512<=r&&!this[L0e]&&!this[kRr];)switch(this[wU]){case"begin":case"header":this[cXa](e,t),t+=512;break;case"ignore":case"body":t+=this[heo](e,t);break;case"meta":t+=this[aXa](e,t);break;default:throw new Error("invalid state: "+this[wU])}t<r&&(this[g0]=this[g0]?Buffer.concat([e.subarray(t),this[g0]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[L0e]||(this[$C]?(e&&this[$C].write(e),this[$C].end()):(this[M0e]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[DRr]())),this}},aNt=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},ajf=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},GXa=(e,t)=>{let r=new Map(t.map(o=>[aNt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,eFr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,eFr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(aNt(o)):o=>i(aNt(o))},cjf=e=>{let t=new dNt(e),r=e.file,n;try{n=qNe.default.openSync(r,"r");let i=qNe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=qNe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=qNe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{qNe.default.closeSync(n)}catch{}}},ujf=(e,t)=>{let r=new dNt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),qNe.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new Keo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},nFr=gNt(cjf,ujf,e=>new dNt(e),e=>new dNt(e),(e,t)=>{t?.length&&GXa(e,t),e.noResume||ajf(e)}),WXa=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:ljf,parse:lXa}=$Xa.win32,eto=e=>{let t="",r=lXa(e);for(;ljf(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=lXa(e)}return[t,e]},iFr=["|","<",">","?",":"],tto=iFr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),pjf=new Map(iFr.map((e,t)=>[e,tto[t]])),fjf=new Map(tto.map((e,t)=>[e,iFr[t]])),pXa=e=>iFr.reduce((t,r)=>t.split(r).join(pjf.get(r)),e),djf=e=>tto.reduce((t,r)=>t.split(r).join(fjf.get(r)),e),HXa=(e,t)=>t?(e=Jp(e).replace(/^\.(\/|$)/,""),aNt(t)+"/"+e):Jp(e),mjf=16*1024*1024,fXa=Symbol("process"),dXa=Symbol("file"),mXa=Symbol("directory"),Peo=Symbol("symlink"),hXa=Symbol("hardlink"),eNt=Symbol("header"),LRr=Symbol("read"),Deo=Symbol("lstat"),URr=Symbol("onlstat"),Reo=Symbol("onread"),Feo=Symbol("onreadlink"),keo=Symbol("openfile"),Neo=Symbol("onopenfile"),q0e=Symbol("close"),JRr=Symbol("mode"),Qeo=Symbol("awaitDrain"),Aeo=Symbol("ondrain"),SY=Symbol("prefix"),KXa=class extends HNe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=Yeo(t);super(),this.path=Jp(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||mjf,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Jp(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Jp(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=eto(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=djf(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Jp(r.absolute||Oeo.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[URr](i):this[Deo]()}warn(e,t,r={}){return rFr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[Deo](){_7.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[URr](t)})}[URr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=Ajf(e),this.emit("stat",e),this[fXa]()}[fXa](){switch(this.type){case"File":return this[dXa]();case"Directory":return this[mXa]();case"SymbolicLink":return this[Peo]();default:return this.end()}}[JRr](e){return WXa(e,this.type==="Directory",this.portable)}[SY](e){return HXa(e,this.prefix)}[eNt](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new $Ne({path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,mode:this[JRr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new KRr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[mXa](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[eNt](),this.end()}[Peo](){_7.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Feo](t)})}[Feo](e){this.linkpath=Jp(e),this[eNt](),this.end()}[hXa](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Jp(Oeo.default.relative(this.cwd,e)),this.stat.size=0,this[eNt](),this.end()}[dXa](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[hXa](t);this.linkCache.set(e,this.absolute)}if(this[eNt](),this.stat.size===0)return this.end();this[keo]()}[keo](){_7.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Neo](t)})}[Neo](e){if(this.fd=e,this.#e)return this[q0e]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[LRr]()}[LRr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");_7.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[q0e](()=>this.emit("error",o));this[Reo](s)})}[q0e](e=()=>{}){this.fd!==void 0&&_7.default.close(this.fd,e)}[Reo](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[q0e](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[q0e](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[Aeo]():this[Qeo](()=>this[Aeo]())}[Qeo](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[Aeo](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[q0e](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[LRr]()}},hjf=class extends KXa{sync=!0;[Deo](){this[URr](_7.default.lstatSync(this.absolute))}[Peo](){this[Feo](_7.default.readlinkSync(this.absolute))}[keo](){this[Neo](_7.default.openSync(this.absolute,"r"))}[LRr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=_7.default.readSync(t,r,n,i,o);this[Reo](s),e=!1}finally{if(e)try{this[q0e](()=>{})}catch{}}}[Qeo](e){e()}[q0e](e=()=>{}){this.fd!==void 0&&_7.default.closeSync(this.fd),e()}},gjf=class extends HNe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return rFr(this,e,t,r)}constructor(e,t={}){let r=Yeo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Jp(e.path),this.mode=e.mode!==void 0?this[JRr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?Jp(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=eto(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new $Ne({path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new KRr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[SY](e){return HXa(e,this.prefix)}[JRr](e){return WXa(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},Ajf=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",yjf=class gXe{tail;head;length=0;static create(t=[]){return new gXe(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)Ejf(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)Ijf(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new gXe;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new gXe;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new gXe;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new gXe;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=bjf(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};function bjf(e,t,r){let n=t,i=t?t.next:e.head,o=new rto(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function Ejf(e,t){e.tail=new rto(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function Ijf(e,t){e.head=new rto(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var rto=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},gXa=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},AXa=Buffer.alloc(1024),zRr=Symbol("onStat"),tNt=Symbol("ended"),w7=Symbol("queue"),UNe=Symbol("current"),zNe=Symbol("process"),rNt=Symbol("processing"),yeo=Symbol("processJob"),S7=Symbol("jobs"),beo=Symbol("jobDone"),VRr=Symbol("addFSEntry"),yXa=Symbol("addTarEntry"),Meo=Symbol("stat"),Leo=Symbol("readdir"),qRr=Symbol("onreaddir"),GRr=Symbol("pipe"),bXa=Symbol("entry"),Eeo=Symbol("entryOpt"),WRr=Symbol("writeEntryClass"),JXa=Symbol("write"),Ieo=Symbol("ondrain"),oFr=class extends HNe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[WRr];onWriteEntry;[w7];[S7]=0;[rNt]=!1;[tNt]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Jp(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[WRr]=KXa,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new PQf(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new RQf(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new kQf(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[Ieo]()),this.on("resume",()=>t.resume())}else this.on("drain",this[Ieo]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[w7]=new yjf,this[S7]=0,this.jobs=Number(e.jobs)||4,this[rNt]=!1,this[tNt]=!1}[JXa](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[tNt]=!0,this[zNe](),r&&r(),this}write(e){if(this[tNt])throw new Error("write after end");return e instanceof qXa?this[yXa](e):this[VRr](e),this.flowing}[yXa](e){let t=Jp(jeo.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new gXa(e.path,t);r.entry=new gjf(e,this[Eeo](r)),r.entry.on("end",()=>this[beo](r)),this[S7]+=1,this[w7].push(r)}this[zNe]()}[VRr](e){let t=Jp(jeo.default.resolve(this.cwd,e));this[w7].push(new gXa(e,t)),this[zNe]()}[Meo](e){e.pending=!0,this[S7]+=1;let t=this.follow?"stat":"lstat";mNt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[S7]-=1,r?this.emit("error",r):this[zRr](e,n)})}[zRr](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)?t.isFile()&&t.nlink>1&&e===this[UNe]&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync&&this[yeo](e):e.ignore=!0,this[zNe]()}[Leo](e){e.pending=!0,this[S7]+=1,mNt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[S7]-=1,t)return this.emit("error",t);this[qRr](e,r)})}[qRr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[zNe]()}[zNe](){if(!this[rNt]){this[rNt]=!0;for(let e=this[w7].head;e&&this[S7]<this.jobs;e=e.next)if(this[yeo](e.value),e.value.ignore){let t=e.next;this[w7].removeNode(e),e.next=t}this[rNt]=!1,this[tNt]&&this[w7].length===0&&this[S7]===0&&(this.zip?this.zip.end(AXa):(super.write(AXa),super.end()))}}get[UNe](){return this[w7]&&this[w7].head&&this[w7].head.value}[beo](e){this[w7].shift(),this[S7]-=1,this[zNe]()}[yeo](e){if(!e.pending){if(e.entry){e===this[UNe]&&!e.piped&&this[GRr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[zRr](e,t):this[Meo](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[qRr](e,t):this[Leo](e),!e.readdir)return}if(e.entry=this[bXa](e),!e.entry){e.ignore=!0;return}e===this[UNe]&&!e.piped&&this[GRr](e)}}}[Eeo](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[bXa](e){this[S7]+=1;try{return new this[WRr](e.path,this[Eeo](e)).on("end",()=>this[beo](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[Ieo](){this[UNe]&&this[UNe].entry&&this[UNe].entry.resume()}[GRr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[VRr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){rFr(this,e,t,r)}},nto=class extends oFr{sync=!0;constructor(e){super(e),this[WRr]=hjf}pause(){}resume(){}[Meo](e){let t=this.follow?"statSync":"lstatSync";this[zRr](e,mNt.default[t](e.absolute))}[Leo](e){this[qRr](e,mNt.default.readdirSync(e.absolute))}[GRr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[VRr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[JXa](n)})}},vjf=(e,t)=>{let r=new nto(e),n=new FXa(e.file,{mode:e.mode||438});r.pipe(n),YXa(r,t)},Cjf=(e,t)=>{let r=new oFr(e),n=new ZRr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return XXa(r,t).catch(o=>r.emit("error",o)),i},YXa=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?nFr({file:Jeo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},XXa=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await nFr({file:Jeo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},xjf=(e,t)=>{let r=new nto(e);return YXa(r,t),r},wjf=(e,t)=>{let r=new oFr(e);return XXa(r,t).catch(n=>r.emit("error",n)),r},ZXa=gNt(vjf,Cjf,xjf,wjf,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),Sjf=process.env.__FAKE_PLATFORM__||process.platform,tZa=Sjf==="win32",{O_CREAT:rZa,O_NOFOLLOW:EXa,O_TRUNC:nZa,O_WRONLY:iZa}=sto.default.constants,oZa=Number(process.env.__FAKE_FS_O_FILENAME__)||sto.default.constants.UV_FS_O_FILEMAP||0,_jf=tZa&&!!oZa,Bjf=512*1024,Tjf=oZa|nZa|rZa|iZa,IXa=!tZa&&typeof EXa=="number"?EXa|nZa|rZa|iZa:null,sZa=IXa!==null?()=>IXa:_jf?e=>e<Bjf?Tjf:"w":()=>"w",Ueo=(e,t,r)=>{try{return ANt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},YRr=(e,t,r,n)=>{ANt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},Ojf=(e,t,r,n,i)=>{if(t.isDirectory())aZa(yXe.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=yXe.default.resolve(e,t.name);YRr(s,r,n,i)});else{let o=yXe.default.resolve(e,t.name);YRr(o,r,n,i)}},aZa=(e,t,r,n)=>{ANt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return YRr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return YRr(e,t,r,n)}};for(let u of o)Ojf(e,u,t,r,c)})},Pjf=(e,t,r,n)=>{t.isDirectory()&&cZa(yXe.default.resolve(e,t.name),r,n),Ueo(yXe.default.resolve(e,t.name),r,n)},cZa=(e,t,r)=>{let n;try{n=ANt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return Ueo(e,t,r);throw o}for(let i of n)Pjf(e,i,t,r);return Ueo(e,t,r)},lZa=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},sFr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},Djf=(e,t)=>{TN.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new lZa(e,r?.code||"ENOTDIR")),t(r)})},Rjf=(e,t,r)=>{e=Jp(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),u=t.preserve,l=t.unlink,p=Jp(t.cwd),d=(m,h)=>{m?r(m):h&&c?aZa(h,s,a,A=>d(A)):o?TN.default.chmod(e,i,r):r()};if(e===p)return Djf(e,d);if(u)return uZa.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Jp(hNt.default.relative(p,e)).split("/");zeo(p,f,i,l,p,void 0,d)},zeo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Jp(hNt.default.resolve(e+"/"+a));TN.default.mkdir(c,r,pZa(c,t,r,n,i,o,s))},pZa=(e,t,r,n,i,o,s)=>a=>{a?TN.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Jp(c.path),s(c);else if(u.isDirectory())zeo(e,t,r,n,i,o,s);else if(n)TN.default.unlink(e,l=>{if(l)return s(l);TN.default.mkdir(e,r,pZa(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new sFr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,zeo(e,t,r,n,i,o,s))},Fjf=e=>{let t=!1,r;try{t=TN.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new lZa(e,r??"ENOTDIR")}},kjf=(e,t)=>{e=Jp(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,u=t.unlink,l=Jp(t.cwd),p=m=>{m&&a&&cZa(m,o,s),i&&TN.default.chmodSync(e,n)};if(e===l)return Fjf(l),p();if(c)return p(TN.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Jp(hNt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),h=l;m&&(h+="/"+m);m=d.shift()){h=Jp(hNt.default.resolve(h));try{TN.default.mkdirSync(h,n),f=f||h}catch{let A=TN.default.lstatSync(h);if(A.isDirectory())continue;if(u){TN.default.unlinkSync(h),TN.default.mkdirSync(h,n),f=f||h;continue}else if(A.isSymbolicLink())return new sFr(h,h+"/"+d.join("/"))}}return p(f)},veo=Object.create(null),vXa=1e4,pXe=new Set,Njf=e=>{pXe.has(e)?pXe.delete(e):veo[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),pXe.add(e);let t=veo[e],r=pXe.size-vXa;if(r>vXa/10){for(let n of pXe)if(pXe.delete(n),delete veo[n],--r<=0)break}return t},Qjf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,jjf=Qjf==="win32",Mjf=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,ato.join)(n,r)),t.push(r||"/"),t},[]),Ljf=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=jjf?["win32 parallelization disabled"]:e.map(n=>aNt((0,ato.join)(Njf(n))));let r=new Set(e.map(n=>Mjf(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},Ujf=()=>process.umask(),CXa=Symbol("onEntry"),Veo=Symbol("checkFs"),xXa=Symbol("checkFs2"),qeo=Symbol("isReusable"),SU=Symbol("makeFs"),Geo=Symbol("file"),Weo=Symbol("directory"),$Rr=Symbol("link"),wXa=Symbol("symlink"),SXa=Symbol("hardlink"),oNt=Symbol("ensureNoSymlink"),_Xa=Symbol("unsupported"),BXa=Symbol("checkPath"),Ceo=Symbol("stripAbsolutePath"),W0e=Symbol("mkdir"),u_=Symbol("onError"),NRr=Symbol("pending"),TXa=Symbol("pend"),fXe=Symbol("unpend"),xeo=Symbol("ended"),weo=Symbol("maybeClose"),$eo=Symbol("skip"),cNt=Symbol("doChown"),uNt=Symbol("uid"),lNt=Symbol("gid"),pNt=Symbol("checkedCwd"),zjf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,fNt=zjf==="win32",Vjf=1024,qjf=(e,t)=>{if(!fNt)return td.default.unlink(e,t);let r=e+".DELETE."+(0,oto.randomBytes)(16).toString("hex");td.default.rename(e,r,n=>{if(n)return t(n);td.default.unlink(r,t)})},Gjf=e=>{if(!fNt)return td.default.unlinkSync(e);let t=e+".DELETE."+(0,oto.randomBytes)(16).toString("hex");td.default.renameSync(e,t),td.default.unlinkSync(t)},OXa=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,cto=class extends dNt{[xeo]=!1;[pNt]=!1;[NRr]=0;reservations=new Ljf;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[xeo]=!0,this[weo]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:Vjf,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||fNt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Jp(HC.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:Ujf():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[CXa](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[weo](){this[xeo]&&this[NRr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ceo](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=eto(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||fNt&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=HC.default.posix.dirname(e.path),c=HC.default.posix.normalize(HC.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[BXa](e){let t=Jp(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Jp(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[Ceo](e,"path")||!this[Ceo](e,"linkpath"))return!1;if(e.absolute=HC.default.isAbsolute(e.path)?Jp(HC.default.resolve(e.path)):Jp(HC.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:Jp(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=HC.default.win32.parse(String(e.absolute));e.absolute=n+pXa(String(e.absolute).slice(n.length));let{root:i}=HC.default.win32.parse(e.path);e.path=i+pXa(e.path.slice(i.length))}return!0}[CXa](e){if(!this[BXa](e))return e.resume();switch(eZa.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Veo](e);default:return this[_Xa](e)}}[u_](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[fXe](),t.resume())}[W0e](e,t,r){Rjf(Jp(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[cNt](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[uNt](e){return OXa(this.uid,e.uid,this.processUid)}[lNt](e){return OXa(this.gid,e.gid,this.processGid)}[Geo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new ZRr(String(e.absolute),{flags:sZa(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&td.default.close(n.fd,()=>{}),n.write=()=>!0,this[u_](a,e),t()});let i=1,o=a=>{if(a){n.fd&&td.default.close(n.fd,()=>{}),this[u_](a,e),t();return}--i===0&&n.fd!==void 0&&td.default.close(n.fd,c=>{c?this[u_](c,e):this[fXe](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;td.default.futimes(c,u,l,p=>p?td.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[cNt](e)){i++;let u=this[uNt](e),l=this[lNt](e);typeof u=="number"&&typeof l=="number"&&td.default.fchown(c,u,l,p=>p?td.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[u_](a,e),t()}),e.pipe(s)),s.pipe(n)}[Weo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[W0e](String(e.absolute),r,n=>{if(n){this[u_](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[fXe](),e.resume())};e.mtime&&!this.noMtime&&(i++,td.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[cNt](e)&&(i++,td.default.chown(String(e.absolute),Number(this[uNt](e)),Number(this[lNt](e)),o)),o()})}[_Xa](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[wXa](e,t){let r=Jp(HC.default.relative(this.cwd,HC.default.resolve(HC.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[oNt](e,this.cwd,r,()=>this[$Rr](e,String(e.linkpath),"symlink",t),n=>{this[u_](n,e),t()})}[SXa](e,t){let r=Jp(HC.default.resolve(this.cwd,String(e.linkpath))),n=Jp(String(e.linkpath)).split("/");this[oNt](e,this.cwd,n,()=>this[$Rr](e,r,"link",t),i=>{this[u_](i,e),t()})}[oNt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=HC.default.resolve(t,o);td.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new sFr(s,HC.default.resolve(s,r.join("/"))));this[oNt](e,s,r,n,i)})}[TXa](){this[NRr]++}[fXe](){this[NRr]--,this[weo]()}[$eo](e){this[fXe](),e.resume()}[qeo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!fNt}[Veo](e){this[TXa]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[xXa](e,r))}[xXa](e,t){let r=s=>{t(s)},n=()=>{this[W0e](this.cwd,this.dmode,s=>{if(s){this[u_](s,e),r();return}this[pNt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Jp(HC.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[W0e](s,this.dmode,a=>{if(a){this[u_](a,e),r();return}o()})}o()},o=()=>{td.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[$eo](e),r();return}if(s||this[qeo](e,a))return this[SU](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[SU](l??null,e,r);return c?td.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return td.default.rmdir(String(e.absolute),c=>this[SU](c??null,e,r))}if(e.absolute===this.cwd)return this[SU](null,e,r);qjf(String(e.absolute),c=>this[SU](c??null,e,r))})};this[pNt]?i():n()}[SU](e,t,r){if(e){this[u_](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[Geo](t,r);case"Link":return this[SXa](t,r);case"SymbolicLink":return this[wXa](t,r);case"Directory":case"GNUDumpDir":return this[Weo](t,r)}}[$Rr](e,t,r,n){td.default[r](t,String(e.absolute),i=>{i?this[u_](i,e):(this[fXe](),e.resume()),n()})}},nNt=e=>{try{return[null,e()]}catch(t){return[t,null]}},fZa=class extends cto{sync=!0;[SU](e,t){return super[SU](e,t,()=>{})}[Veo](e){if(!this[pNt]){let i=this[W0e](this.cwd,this.dmode);if(i)return this[u_](i,e);this[pNt]=!0}if(e.absolute!==this.cwd){let i=Jp(HC.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[W0e](i,this.dmode);if(o)return this[u_](o,e)}}let[t,r]=nNt(()=>td.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[$eo](e);if(t||this[qeo](e,r))return this[SU](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?nNt(()=>{td.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[SU](s,e)}let[i]=nNt(()=>td.default.rmdirSync(String(e.absolute)));this[SU](i,e)}let[n]=e.absolute===this.cwd?[]:nNt(()=>Gjf(String(e.absolute)));this[SU](n,e)}[Geo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{td.default.closeSync(i)}catch(c){a=c}(s||a)&&this[u_](s||a,e),t()},i;try{i=td.default.openSync(String(e.absolute),sZa(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[u_](s,e)),e.pipe(o)),o.on("data",s=>{try{td.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{td.default.futimesSync(i,a,c)}catch(u){try{td.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[cNt](e)){let a=this[uNt](e),c=this[lNt](e);try{td.default.fchownSync(i,Number(a),Number(c))}catch(u){try{td.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[Weo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[W0e](String(e.absolute),r);if(n){this[u_](n,e),t();return}if(e.mtime&&!this.noMtime)try{td.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[cNt](e))try{td.default.chownSync(String(e.absolute),Number(this[uNt](e)),Number(this[lNt](e)))}catch{}t(),e.resume()}[W0e](e,t){try{return kjf(Jp(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[oNt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=HC.default.resolve(o,s);let[a,c]=nNt(()=>td.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new sFr(o,HC.default.resolve(t,r.join("/"))))}n()}[$Rr](e,t,r,n){let i=`${r}Sync`;try{td.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[u_](o,e)}}},Wjf=e=>{let t=new fZa(e),r=e.file,n=ito.default.statSync(r),i=e.maxReadSize||16*1024*1024;new EQf(r,{readSize:i,size:n.size}).pipe(t)},$jf=(e,t)=>{let r=new cto(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),ito.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new Keo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},dZa=gNt(Wjf,$jf,e=>new fZa(e),e=>new cto(e),(e,t)=>{t?.length&&GXa(e,t)}),Hjf=(e,t)=>{let r=new nto(e),n=!0,i,o;try{try{i=BN.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=BN.default.openSync(e.file,"w+");else throw c}let s=BN.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=BN.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new $Ne(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,Kjf(e,r,o,i,t)}finally{if(n)try{BN.default.closeSync(i)}catch{}}},Kjf=(e,t,r,n,i)=>{let o=new FXa(e.file,{fd:n,start:r});t.pipe(o),Yjf(t,i)},Jjf=(e,t)=>{t=Array.from(t);let r=new oFr(e),n=(i,o,s)=>{let a=(d,f)=>{d?BN.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return BN.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new $Ne(l);if(!m.cksumValid)return a(null,c);let h=512*Math.ceil((m.size??0)/512);if(c+h+512>o||(c+=h+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),u=0,BN.default.read(i,l,0,512,c,p)};BN.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",BN.default.open(e.file,s,a);if(c||!u)return o(c);BN.default.fstat(u,(l,p)=>{if(l)return BN.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new ZRr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),Xjf(r,t)})})};BN.default.open(e.file,s,a)})},Yjf=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?nFr({file:uto.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},Xjf=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await nFr({file:uto.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},iNt=gNt(Hjf,Jjf,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!SQf(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),hG0=gNt(iNt.syncFile,iNt.asyncFile,iNt.syncNoFile,iNt.asyncNoFile,(e,t=[])=>{iNt.validate?.(e,t),Zjf(e)}),Zjf=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))};var bZa=Ie(nS(),1);var eMf=tue();async function EZa({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:n,cliVersion:i,settings:o,loadAPIWorkspace:s}){let a,c={type:Ol.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},u=t.dependencies[e];return u==null?c={type:Ol.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${aMf(u)}`},async l=>{switch(u.type){case"version":a=await oMf({context:l,dependency:u,cliVersion:i,settings:o,loadAPIWorkspace:s});return;case"local":a=await iMf({context:l,dependency:u,cliVersion:i,settings:o,loadAPIWorkspace:s});return;default:Ce(u)}}),a!=null?{didSucceed:!0,definition:a}:{didSucceed:!1,failure:c}}var IZa="dependencies";var tMf="metadata.json",rMf=".fern";function nMf(e){return $e($t.of((0,gZa.homedir)()),Te.of(rMf),Te.of(IZa),Te.of(e.organization),Te.of(e.apiName),Te.of(e.version))}async function iMf({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){if(i==null){t.failWithoutThrowing("Failed to load api definition",void 0,{code:j.Code.ResolutionError});return}t.logger.info("Parsing...");let o=await i({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!o.didSucceed){t.failWithoutThrowing("Failed to load api definition",o.failures,{code:j.Code.ResolutionError});return}t.logger.info("Modifying source filepath ...");let s=await o.workspace.getDefinition({context:t,relativePathToDependency:Te.of(e.path)},n);return t.logger.info("Loaded..."),s}async function oMf({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){let o=nMf(e),s=$e(o,Te.of(IZa)),a=$e(o,Te.of(tMf)),c;if(!await cr(s)||!await cr(a)){t.logger.info("Downloading manifest...");let p=await eMf.definitionRegistry.get(zr.OrganizationId(e.organization),zr.ApiId(e.apiName),e.version);if(!p.ok){p.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist",void 0,{code:j.Code.ResolutionError})},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist",void 0,{code:j.Code.ResolutionError})},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist",void 0,{code:j.Code.ResolutionError})},_other:h=>{t.failWithoutThrowing("Failed to download API manifest",h,{code:j.Code.NetworkError})}});return}let d=p.body.yamlSchemaVersion!=null?parseInt(p.body.yamlSchemaVersion):void 0,f=SNe(r),m=SNe(p.body.cliVersion);if(d!=null){if(d>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${p.body.cliVersion}`,void 0,{code:j.Code.VersionError});return}else if(d<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`,void 0,{code:j.Code.VersionError});return}}else if(f.major!==m.major||f.minor!==m.minor){t.failWithoutThrowing(`CLI version is ${p.body.cliVersion}. Expected ${f.major}.${f.minor}.x (to match current workspace).`,void 0,{code:j.Code.VersionError});return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+p.body.definitionS3DownloadUrl),await(0,EXe.mkdir)(s,{recursive:!0});try{await sMf({s3PreSignedReadUrl:p.body.definitionS3DownloadUrl,absolutePathToLocalOutput:s})}catch(h){t.failWithoutThrowing("Failed to download API",h,{code:j.Code.NetworkError});return}c=p.body,await(0,EXe.writeFile)(a,JSON.stringify(c))}else c=JSON.parse((await(0,EXe.readFile)(a)).toString());if(t.logger.info("Parsing..."),i==null){t.failWithoutThrowing("Failed to load API",void 0,{code:j.Code.ResolutionError});return}let u=await i({absolutePathToWorkspace:s,context:t,cliVersion:c.cliVersion,workspaceName:void 0});if(!u.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",u.failures,{code:j.Code.ParseError});return}if(u.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.",void 0,{code:j.Code.ConfigError});return}return await u.workspace.getDefinition({context:t},n)}async function sMf({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await ly.get(e,{responseType:"stream"}),n=await bZa.default.dir(),i=AZa.default.join(n.path,"api.tgz");await(0,yZa.pipeline)(r.data,(0,hZa.createWriteStream)(i)),await dZa({file:i,cwd:t})}function aMf(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Ce(e)}}async function vZa({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:n,settings:i,loadAPIWorkspace:o}){let s={},a={},c={};return await Promise.all(L0(t.packageMarkers).map(async([u,l])=>{if(l.contents.export==null)s[u]=l;else{let{export:p,...d}=l.contents;if(ih(d)>0)c[u]={type:Ol.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:u};else{let f=xn(u);if(jT(t.namedDefinitionFiles).some(h=>h!==u&&h.startsWith(f)))c[u]={type:Ol.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:f};else{let h=await EZa({dependencyName:typeof l.contents.export=="string"?l.contents.export:l.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:n,settings:i,loadAPIWorkspace:o});h.didSucceed?a[xn(u)]={definition:h.definition,url:typeof l.contents.export=="object"?l.contents.export.url:void 0}:c[u]=h.failure}}}})),ih(c)>0?{didSucceed:!1,failures:c}:{didSucceed:!0,packageMarkers:s,importedDefinitions:a}}Rt();Jt();var CZa=Ie(require("path"),1);var lto={};ee(lto,{additionalProperties:()=>pMf,default:()=>dMf,definitions:()=>fMf,properties:()=>uMf,required:()=>lMf,type:()=>cMf});var cMf="object",uMf={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},lMf=["name"],pMf=!1,fMf={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}},"url-templates":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"default-urls":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}}},{type:"null"}]}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},dMf={type:cMf,properties:uMf,required:lMf,additionalProperties:pMf,definitions:fMf};var pto={};ee(pto,{additionalProperties:()=>gMf,default:()=>yMf,definitions:()=>AMf,properties:()=>hMf,type:()=>mMf});var mMf="object",hMf={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},gMf=!1,AMf={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadBodySortSchema":{type:"string",enum:["alphabetical"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]},"body-sort":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadBodySortSchema"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},yMf={type:mMf,properties:hMf,additionalProperties:gMf,definitions:AMf};var fto={};ee(fto,{additionalProperties:()=>IMf,default:()=>CMf,definitions:()=>vMf,properties:()=>EMf,type:()=>bMf});var bMf="object",EMf={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},IMf=!1,vMf={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadBodySortSchema":{type:"string",enum:["alphabetical"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]},"body-sort":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadBodySortSchema"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},CMf={type:bMf,properties:EMf,additionalProperties:IMf,definitions:vMf};var dto=new Map,mto=new Map,hto=new Map;function xZa({files:e,absolutePathToDefinition:t,skipValidation:r}){let n,i={},o={},s={};for(let[a,c]of L0(e)){let u=c.contents,l=p=>{s[a]={type:Ol.JSONSCHEMA_VALIDATION,error:p}};if(a===eI){let p=dto.get(c.rawContents);if(p!=null&&(p.validated||r))n={defaultUrl:p.value["default-url"],contents:p.value,rawContents:c.rawContents};else if(r){let d=oh.serialization.RootApiFileSchema.parseOrThrow(u);dto.set(c.rawContents,{value:d,validated:!1}),n={defaultUrl:d["default-url"],contents:d,rawContents:c.rawContents}}else{let d=Q3(u,lto);if(d.success){let f=oh.serialization.RootApiFileSchema.parseOrThrow(u);dto.set(c.rawContents,{value:f,validated:!0}),n={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else l(d)}}else if(CZa.default.basename(a)===kf){let p=hto.get(c.rawContents);if(p!=null&&(p.validated||r))o[a]={defaultUrl:typeof p.value.export=="object"?p.value.export.url:void 0,contents:p.value,rawContents:c.rawContents};else if(r){let d=oh.serialization.PackageMarkerFileSchema.parseOrThrow(u);hto.set(c.rawContents,{value:d,validated:!1}),o[a]={defaultUrl:typeof d.export=="object"?d.export.url:void 0,contents:d,rawContents:c.rawContents}}else{let d=Q3(u,fto);if(d.success){let f=oh.serialization.PackageMarkerFileSchema.parseOrThrow(u);hto.set(c.rawContents,{value:f,validated:!0}),o[a]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else l(d)}}else{let p=mto.get(c.rawContents);if(p!=null&&(p.validated||r))i[a]={defaultUrl:void 0,contents:p.value,rawContents:c.rawContents,absoluteFilePath:$e(t,a)};else if(r){let d=oh.serialization.DefinitionFileSchema.parseOrThrow(u);mto.set(c.rawContents,{value:d,validated:!1}),i[a]={defaultUrl:void 0,contents:d,rawContents:c.rawContents,absoluteFilePath:$e(t,a)}}else{let d=Q3(u,pto);if(d.success){let f=oh.serialization.DefinitionFileSchema.parseOrThrow(u);mto.set(c.rawContents,{value:f,validated:!0}),i[a]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:$e(t,a)}}else l(d)}}}return n==null?{didSucceed:!1,failures:{[Te.of(eI)]:{type:Ol.FILE_MISSING},...s}}:Object.keys(s).length>0?{didSucceed:!1,failures:s}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:n,packageMarkers:o}}var ZO=class extends uG{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...n}){super(n),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){let n=t||this.context;return(await this.toFernWorkspace({context:n},r)).definition}async toFernWorkspace({context:t,skipValidation:r},n,i,o){let s=(0,wZa.default)(n??{}),a=this.fernWorkspaces[s];if(a==null){let c=t||this.context,u=$e(this.absoluteFilePath,Te.of(wA)),l=await E2i({absolutePathToWorkspace:this.absoluteFilePath,context:c}),p=await HHa(u,"{yml,yaml}"),d=await KHa(p);if(!d.didSucceed)return RDr(d.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let f=xZa({files:d.files,absolutePathToDefinition:u,skipValidation:r});if(!f.didSucceed)return RDr(f.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let m=await vZa({dependenciesConfiguration:l,structuralValidationResult:f,context:c,cliVersion:this.cliVersion,settings:n,loadAPIWorkspace:this.loadAPIWorkspace});if(!m.didSucceed)return RDr(m.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let h={absoluteFilePath:u,rootApiFile:f.rootApiFile,namedDefinitionFiles:f.namedDefinitionFiles,packageMarkers:m.packageMarkers,importedDefinitions:m.importedDefinitions};n?.auth!=null&&(h={...h,rootApiFile:{...h.rootApiFile,contents:{...h.rootApiFile.contents,auth:n?.auth}}}),a=new F2({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:h,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[s]=a}return a}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};Jt();var tic=require("fs/promises");var Qnc=Ie(Nnc(),1);async function uF(e){return(await(0,Qnc.convertObj)(e,{})).openapi}var Hnc=require("fs/promises");var Knc=require("path");Rt();var jnc=require("fs/promises");async function MXe({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,jnc.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Tr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:j.Code.ParseError})}return P$({data:t,overrides:i,allowNullKeys:n})}var qnc=require("fs/promises");var fQt=require("path");function Gnc(e){return e.startsWith("http://")||e.startsWith("https://")}async function Mnc(e,t){let r=t.get(e);if(r!==void 0)return r;let n=await(0,qnc.readFile)(e,"utf-8"),i=Tr.load(n);return t.set(e,i),i}function Wnc(e,t){let r=new Map;if(e==null||typeof e!="object"||Array.isArray(e))return r;let n=e;function i(s,a){if(!(s==null||typeof s!="object"||Array.isArray(s)))for(let[c,u]of Object.entries(s)){if(!Mzf(u))continue;let l=u.$ref,{jsonPointer:p,absolutePath:d}=$nc(l,t);r.set(`${d}#${p}`,`${a}/${c}`)}}i(n.channels,"#/channels"),i(n.operations,"#/operations");let o=n.components;if(o!=null&&typeof o=="object"&&!Array.isArray(o)){let s=o;i(s.schemas,"#/components/schemas"),i(s.messages,"#/components/messages"),i(s.parameters,"#/components/parameters")}return r}function $nc(e,t){let r=e.indexOf("#"),n=r>=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"",o=(0,fQt.resolve)(t,n);return{filePath:n,jsonPointer:i,absolutePath:o}}function Mzf(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e.$ref;return typeof t=="string"&&t.length>0&&!t.startsWith("#")&&!Gnc(t)}function Lnc(e){let t={},r=!1;for(let[n,i]of Object.entries(e))n!=="$ref"&&(t[n]=i,r=!0);return{siblingProperties:t,hasSiblings:r}}function Unc(e,t,r){if(t==="")return e;let n=t.split("/").filter(o=>o!==""),i=e;for(let o of n){let s=o.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof i!="object"||i==null)throw new Error(`Cannot navigate JSON Pointer "${t}" in "${r}": expected an object but found ${typeof i} at key "${s}"`);let a=i[s];if(a===void 0)throw new Error(`Cannot navigate JSON Pointer "${t}" in "${r}": key "${s}" not found`);i=a}return i}function znc(e,t,r){return r&&e!=null&&typeof e=="object"&&!Array.isArray(e)?{...e,...t}:e}function Vnc(e,t,r,n){if(e===r)return"#"+t;let i=`${e}#${t}`,o=n.get(i);if(o!==void 0)return o;for(let[s,a]of n){let c=s.indexOf("#"),u=s.slice(0,c),l=s.slice(c+1);if(u===e&&t.startsWith(l+"/")){let p=t.slice(l.length);return a+p}}return null}async function LXe(e,t,r,n,i=!1,o=new Set,s=new Map,a){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return Promise.all(e.map(p=>LXe(p,t,r,n,i,o,s,a)));let c=e,u=c.$ref;if(typeof u=="string"&&u.startsWith("#")&&a!=null){let p=u.substring(1),{siblingProperties:d,hasSiblings:f}=Lnc(c),m=Vnc(a,p,r,n);if(m!==null)return f?{$ref:m,...d}:{$ref:m};let h=`${a}#${p}`;if(o.has(h))throw new Error(`Circular $ref detected: "${u}" (resolved to "${h}")`);let A=new Set(o);A.add(h);let b=await Mnc(a,s),v=Unc(b,p,a),x=(0,fQt.dirname)(a),C=await LXe(v,x,r,n,!0,A,s,a);return znc(C,d,f)}if(typeof u=="string"&&!u.startsWith("#")&&!Gnc(u)){let{jsonPointer:p,absolutePath:d}=$nc(u,t),{siblingProperties:f,hasSiblings:m}=Lnc(c);if(i){let w=Vnc(d,p,r,n);if(w!==null)return{$ref:w,...f}}let h=`${d}#${p}`;if(o.has(h))throw new j({message:`Circular $ref detected: "${u}" (resolved to "${h}")`,code:j.Code.ReferenceError});let A=new Set(o);A.add(h);let b=await Mnc(d,s),v=Unc(b,p,d),x=(0,fQt.dirname)(d),C=await LXe(v,x,r,n,!0,A,s,d);return znc(C,f,m)}let l={};for(let[p,d]of Object.entries(c))l[p]=await LXe(d,t,r,n,i,o,s,a);return l}async function yno({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,Hnc.readFile)(t)).toString(),i=await Tr.load(n),o=(0,Knc.dirname)(t),s=Wnc(i,o),a=await LXe(i,o,t,s),c=[];r!=null&&(Array.isArray(r)?c=r:c=[r]);let u=a;for(let l of c)u=await MXe({absoluteFilePathToOverrides:l,context:e,data:u});return u}Jt();var Ino=require("fs/promises");Rt();var Ekr=require("fs/promises");var bkr=Ie(require("path"),1),Jnc=Ie(nS(),1),bno;async function Lzf(){return bno===void 0&&(bno=(await Jnc.default.dir({prefix:"fern-overlay-"})).path),bno}async function Ync({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:n}){let i=await Uzf(e,n);if(!zzf(i,n))return r;n.logger.debug(`Applying overlay "${i.info.title}" v${i.info.version}`);let o=cqe({data:r,overlay:i}),s=await Lzf(),a=bkr.default.basename(t),c=`${bkr.default.parse(a).name}.overlaid.json`,u=bkr.default.join(s,c);return await(0,Ekr.writeFile)(u,JSON.stringify(o,null,2),"utf8"),n.logger.debug(`Wrote overlaid OpenAPI spec to: ${u}`),o}async function Uzf(e,t){let r;try{r=await(0,Ekr.readFile)(e,"utf8")}catch(n){return t.failAndThrow(`Failed to read overlay file at ${e}: ${n}`,void 0,{code:j.Code.ConfigError})}try{try{return JSON.parse(r)}catch{return Tr.load(r,{json:!0})}}catch(n){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${n}`,void 0,{code:j.Code.ParseError})}}function zzf(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let n=e.actions[r];if(!n?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(n.update===void 0&&!n.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var hQt=Ie(Yvr(),1);Jt();var Xnc=Ie(Yvr(),1),dQt=Ie(require("path"),1),mQt=class extends Xnc.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let n=super.resolveExternalRef(t,r);if(n.startsWith("http://")||n.startsWith("https://")||Q$($t.of(n)))return n;if(this.absolutePathToOpenAPIOverlays!=null){let i=dQt.default.resolve(dQt.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(Q$($t.of(i)))return i}return this.absolutePathToOpenAPIOverrides!=null?dQt.default.resolve(dQt.default.dirname(this.absolutePathToOpenAPIOverrides),r):n}};async function Ikr({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:n}){return(n!=null?await(0,hQt.bundle)({...Xvr,doc:{source:new hQt.Source(e,"<openapi>"),parsed:n},externalRefResolver:new mQt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,hQt.bundle)({...Xvr,ref:e,externalRefResolver:new mQt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}Rt();var Znc=require("fs/promises"),eic=require("path");async function Eno(e,t,r){await vkr(e,t,r,"",void 0)}var Vzf=new Set(["properties","patternProperties"]);async function vkr(e,t,r,n,i){if(Array.isArray(e)){await Promise.all(e.map((o,s)=>vkr(o,t,r,`${n}[${s}]`,i)));return}if(fa(e))for(let[o,s]of Object.entries(e)){let a=n===""?o:`${n}.${o}`;if(o==="description"&&!(i!=null&&Vzf.has(i))){if(typeof s=="string"||s==null)continue;if(qzf(s)){e[o]=await $zf(s.$ref,t,r,a);continue}if(Gzf(s)){r.logger.warn(`OpenAPI description at "${a}" is a \`$ref\` object we can't resolve (${Wzf(s)}). Descriptions must be plain strings, and we only inline relative \`.md\` file refs. Coercing to empty string so generation can continue.`),e[o]="";continue}await vkr(s,t,r,a,o)}else await vkr(s,t,r,a,o)}}function qzf(e){if(!fa(e))return!1;let t=Object.keys(e);if(t.length!==1||t[0]!=="$ref")return!1;let r=e.$ref;return typeof r!="string"||r.length===0||r.startsWith("#")||r.startsWith("http://")||r.startsWith("https://")?!1:r.toLowerCase().endsWith(".md")}function Gzf(e){return fa(e)&&typeof e.$ref=="string"&&e.$ref.length>0}function Wzf(e){let t=e.$ref,r=Object.keys(e).filter(i=>i!=="$ref"),n=r.length>0?`, sibling keys: ${r.map(i=>`"${i}"`).join(", ")}`:"";return`target="${t}"${n}`}async function $zf(e,t,r,n){let i=(0,eic.resolve)(t,e);try{return(await(0,Znc.readFile)(i,"utf-8")).trimEnd()}catch(o){return r.logger.warn(`Failed to resolve markdown description $ref at "${n}" \u2192 "${e}" (${i}): ${o instanceof Error?o.message:String(o)}. Coercing to empty string so generation can continue.`),""}}function Hzf(e,t){if(t.includes(e))return e;for(let r of t){let n=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${n}$`).test(e))return r}}var Kzf=["examples","example",Bn.EXAMPLES,cB.REDOCLY_CODE_SAMPLES_CAMEL,cB.REDOCLY_CODE_SAMPLES_KEBAB];async function gQt({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:n,loadAiExamples:i=!1}){let o=await(0,Ino.readFile)(t,"utf-8"),s=Tr.load(o);await Eno(s,xn(t),e);let a=await Ikr({absolutePathToOpenAPI:t,parsed:s}),c=[];r!=null?Array.isArray(r)?c=r:c=[r]:typeof a=="object"&&a[Bn.OPENAPI_OVERIDES_FILEPATH]!=null&&(c=[$e(xn(t),Te.of(a[Bn.OPENAPI_OVERIDES_FILEPATH]))]);let u=a;for(let p of c)u=await MXe({absoluteFilePathToOverrides:p,context:e,data:u,allowNullKeys:Kzf}),await Eno(u,xn(p),e),u=await Ikr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:p,parsed:u});if(n!=null&&(u=await Ync({absoluteFilePathToOverlay:n,absoluteFilePathToOpenAPI:t,context:e,data:u})),i){let p=$e(xn(t),Te.of("ai_examples_override.yml"));try{let d=await(0,Ino.readFile)(p,"utf-8"),f=Tr.load(d);if(f?.paths&&u.paths){for(let[m,h]of Object.entries(f.paths))if(h&&typeof h=="object")for(let[A,b]of Object.entries(h)){let v=A.toLowerCase(),x=u.paths[m];if(!x&&u.paths){let C=Hzf(m,Object.keys(u.paths));C&&(x=u.paths[C],e.logger.debug(`Matched override path "${m}" to OpenAPI path "${C}" using pattern matching`))}if(x&&typeof x=="object"){let w=x[v];if(w&&typeof w=="object"){let B=w;!B["x-fern-examples"]&&b["x-fern-examples"]&&(B["x-fern-examples"]=b["x-fern-examples"],e.logger.debug(`Added AI examples for ${A.toUpperCase()} ${m} from override file`))}}}}e.logger.debug(`Processed AI examples from ${p}`)}catch{}}return u!==a&&c.length===0||n!=null?await Ikr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverlays:n,parsed:u}):u}var R7=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:n=!1}){return(await Promise.all(r.map(o=>this.loadDocument({context:t,spec:o,loadAiExamples:n})))).filter(o=>o!=null)}async loadDocument({context:t,spec:r,loadAiExamples:n}){try{let i=(await(0,tic.readFile)(r.absoluteFilepath)).toString(),o=$s(this.absoluteFilePath,r.source.file);r.source.relativePathToDependency!=null&&(o=$e(r.source.relativePathToDependency,o));let s=r.source.type==="protobuf"?lO.protobuf({file:o}):lO.openapi({file:o});if(i.includes("openapi")||i.includes("swagger"))try{let a=await gQt({absolutePathToOpenAPI:r.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:r.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:r.absoluteFilepathToOverlays,loadAiExamples:n});if(b2i(a))return{type:"openapi",value:a,source:s,namespace:r.namespace,settings:C4({options:r.settings})};if(UR(a))return(!a.schemes||a.schemes.length===0)&&(a.schemes=["https"]),{type:"openapi",value:await uF(a),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.debug(`Failed to parse OpenAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("asyncapi"))try{return{type:"asyncapi",value:await yno({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.error(`Failed to parse AsyncAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("openrpc"))try{return{type:"asyncapi",value:await yno({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.error(`Failed to parse OpenRPC document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}t.logger.warn(`${r.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`);return}catch(i){t.logger.error(`Failed to read or process file ${r.absoluteFilepath}: ${i}. Skipping...`);return}}};var oo=class e{breadcrumbs=[];context;static STRING=Yt.TypeReference.primitive({v1:"STRING",v2:Yt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Yt.TypeReference.container(Yt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};Wi();Jt();var nic=require("fs/promises");var vno=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},ric=vno;var ub;(function(e){e.WARNING="warning",e.ERROR="error"})(ub||(ub={}));var TU=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new Cno({logger:t,relativePathToFile:Te.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||ub.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===ub.ERROR?t++:(n.level===ub.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??ub.WARNING;if(!(n===ub.WARNING&&!t))switch(n){case ub.ERROR:if(this.logger.log(Xn.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Xn.Debug,` - at location (${o})`)}break;case ub.WARNING:if(this.logger.log(Xn.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Xn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Xn.Warn,` - resolution: ${r.resolution}`);break}}}},Cno=class{logger;relativePathToFile;map=new ric;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,nic.readFile)(this.relativePathToFile,"utf-8");Tr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Xn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var A0=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=sw({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((i,o)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||o===0&&i==="components"||o===1&&i==="schemas"||t[0]==="paths"&&(o===0||o===1&&["get","post","put","delete","patch"].includes(i)||o===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=Wn(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:ub.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:ub.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};s=l;let p=await fetch(l);if(!p.ok)return{resolved:!1};try{let d=await p.text();try{o=JSON.parse(d),r=o}catch{o=Tr.load(d),r=o}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,u=s.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return Yt.ObjectPropertyAccess.ReadOnly;if(i)return Yt.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new uw.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}let i=new uw.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:vC.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var qa=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}};Wi();var uw={};ee(uw,{AudienceExtension:()=>UXe,FernAvailabilityExtension:()=>Ckr,FernDiscriminatorContextExtension:()=>zXe,FernEnumExtension:()=>VXe,FernIgnoreExtension:()=>aQe,FernOptionalExtension:()=>xkr,FernTypeExtension:()=>Bkr,FernTypeNameExtension:()=>Tkr,SdkGroupNameExtension:()=>wkr,SdkMethodNameExtension:()=>Skr,ServerFromOperationNameExtension:()=>_kr});var UXe=class extends qa{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var Ckr=class extends qa{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return vC.InDevelopment;case"PRE_RELEASE":case"BETA":return vC.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return vC.GeneralAvailability;case"DEPRECATED":return vC.Deprecated;default:return}}};var zXe=class extends qa{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}};ts();var Jzf=It.object({snake:It.string().optional(),camel:It.string().optional(),screamingSnake:It.string().optional(),pascal:It.string().optional()}),Yzf=It.object({description:It.string().optional(),name:It.string().optional(),casing:Jzf.optional()}),iic=It.record(Yzf);var VXe=class extends qa{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=iic.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var aQe=class extends qa{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var xkr=class extends qa{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var wkr=class extends qa{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var Skr=class extends qa{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var _kr=class extends qa{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var Bkr=class extends qa{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var Tkr=class extends qa{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var F7=class extends oo{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new eNe(n),this.ir={auth:{docs:void 0,requirement:Yt.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Yt.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new aQe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new aQe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n};let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i));let o=this.context.exampleGenerationArgs,s=ZHi({ir:i,exampleGeneration:o});if(this.context.generateV1Examples){let a=_kt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let o of Object.values(t.services)){let s=[];for(let a of o.endpoints)r.has(a.id)&&s.push(a);o.endpoints=s}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([o])=>n.has(o))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([o,s])=>{let a=s.filter(c=>c.id!=null&&i.has(c.id));return[o,a]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:o}){let s=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),a=this.getOrCreatePackage({group:n}),c=[...s].map(p=>this.context.casingsGenerator.generateName(p)),u=c[c.length-1];a.service==null&&(a.service=o??`service_${s.map(p=>Wn(p)).join("/")}`),this.ir.services[a.service]==null&&(this.ir.services[a.service]=this.createNewService({allParts:c,finalpart:u,endpointGroupDisplayName:i})),this.ir.services[a.service]?.endpoints.push(t);let l=this.ir.services[a.service];l!=null&&(this.irGraph.addEndpoint(l,t),this.irGraph.markEndpointForAudience(l.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let o=i?.join(".")??r,s=this.getOrCreatePackage({group:i});this.ir.webhookGroups[o]==null&&(this.ir.webhookGroups[o]=[]),this.ir.webhookGroups[o].push(t),s.webhooks=o;let a=this.context.createFernFilepath();this.irGraph.addWebhook(a,t),n!=null&&this.irGraph.markWebhookForAudiences(a,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=Wn(i?.join(".")),s=Wn(r),a=this.context.namespace?`${Wn(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:ob(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>Wn(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}};var Yd={};ee(Yd,{AbstractConverters:()=>Sno,ExampleConverter:()=>vv,SchemaConverters:()=>wno,ServersConverter:()=>v6});var Sno={};ee(Sno,{AbstractMediaTypeObjectConverter:()=>Dkr,AbstractParameterConverter:()=>Rkr});Wi();Rt();var Xzf=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function oic(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function Zzf(e){if(!oic(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>oic(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function e8f(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function sic(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var vv=class e extends oo{MAX_DEPTH=12;EXAMPLE_STRING=ki.STRING;EXAMPLE_NUMBER=ki.DOUBLE;EXAMPLE_BOOLEAN=ki.BOOLEAN;EXAMPLE_INTEGER=ki.INT;EXAMPLE_DATE=ki.DATE;EXAMPLE_DATE_TIME=ki.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=Object.entries(t.properties??{}).map(([p,d])=>{if(typeof d!="object")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:p,resolvedSchema:t}))return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let f=Zzf(d),m=!(p in r)||!f&&r[p]==null||f&&r[p]===void 0,h=!t.required?.includes(p);if(m&&h){if(this.example===void 0&&this.generateOptionalProperties){let A=this.maybeResolveSchemaExample(d),b=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:A,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:p,result:b.convert()}}return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let A=r[p],b=A!==void 0?A:this.maybeResolveSchemaExample(d),x=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:p,result:x}}}),i=(t.allOf??[]).map((p,d)=>{let f=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],skipErrorCollector:!0});return f&&this.isConstraintOnlySchema(f)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...p,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),o=this.example!==void 0&&(n.some(({result:p})=>p.usedProvidedExample)||i.some(p=>p.usedProvidedExample)),s=Object.fromEntries(n.map(({key:p,result:d})=>[p,d.validExample]).filter(([p,d])=>d!==void 0));for(let p of i)if(typeof p.validExample=="object"&&p.validExample!==null){let d=p.validExample;s={...s,...Object.fromEntries(Object.entries(d).filter(([f,m])=>m!==void 0))}}let a=[],c=this.collectAllPropertyKeys(t),u=Object.keys(r).filter(p=>!c.has(p));if(u.length>0)if(t.additionalProperties===!1)u.forEach(p=>{let d=[...this.breadcrumbs,p].join("."),f={message:`Found unexpected property '${p}' in example. This property does not exist in the schema${d?` at path: ${d}`:""}`,path:[...this.breadcrumbs,p]};a.push({key:p,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[f]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)u.forEach(p=>{a.push({key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[p],errors:[]}})});else{let p=t.additionalProperties;u.forEach(d=>{let m=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:p,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();a.push({key:d,result:m})})}for(let{key:p,result:d}of a)d.validExample!==void 0&&s[p]===void 0&&(s[p]=d.validExample);let l=n.every(p=>p.result.isValid)&&i.every(p=>p.isValid)&&a.every(({result:p})=>p.isValid);if(Object.keys(s).length===0){let p=i.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));p&&(s=p.validExample)}return{isValid:l,coerced:!1,usedProvidedExample:o,validExample:s,errors:[...n.flatMap(({result:p})=>p.errors),...i.flatMap(p=>p.errors),...a.flatMap(({result:p})=>p.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let h=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});h&&d.push(h)}if(d.length>0&&d.every(m=>e8f(m))){let m=d.findIndex(h=>sic(h)!==void 0);if(m!==-1){let h=n[m],A=d[m];if(h&&A){let b=sic(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...h,oneOf:void 0}:h,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,h=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(b.isValid&&!b.coerced&&b.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:b.validExample,errors:[]};if(b.isValid&&!b.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:b.usedProvidedExample,validExample:b.validExample,errors:[]};o.push(b),b.isValid&&b.usedProvidedExample&&a===null&&(a=b),b.isValid&&s===null&&(s=b)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(Xzf);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}};var wno={};ee(wno,{ArraySchemaConverter:()=>$Xe,EnumSchemaConverter:()=>fbe,ObjectSchemaConverter:()=>GXe,OneOfSchemaConverter:()=>cQe,PrimitiveSchemaConverter:()=>WXe,SchemaConverter:()=>mbe,SchemaOrReferenceConverter:()=>nP});function aic(e){return ev({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return kr.primitive({v1:"BASE_64",v2:$n.base64({})});case"BOOLEAN":return kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})});case"DATE":return kr.primitive({v1:"DATE",v2:$n.date({})});case"DATE_TIME":return kr.primitive({v1:"DATE_TIME",v2:$n.dateTime({})});case"DATE_TIME_RFC_2822":return kr.primitive({v1:"DATE_TIME_RFC_2822",v2:$n.dateTimeRfc2822({})});case"FLOAT":return kr.primitive({v1:"FLOAT",v2:$n.float({default:void 0,validation:void 0})});case"DOUBLE":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:void 0,validation:void 0})});case"UINT":return kr.primitive({v1:"UINT",v2:$n.uint({default:void 0,validation:void 0})});case"UINT_64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:void 0,validation:void 0})});case"INTEGER":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:void 0,validation:void 0})});case"LONG":return kr.primitive({v1:"LONG",v2:$n.long({default:void 0,validation:void 0})});case"STRING":return kr.primitive({v1:"STRING",v2:$n.string({default:void 0,validation:void 0})});case"UUID":return kr.primitive({v1:"UUID",v2:$n.uuid({})});case"BIG_INTEGER":return kr.primitive({v1:"BIG_INTEGER",v2:$n.bigInteger({default:void 0})});default:return}},unknown:()=>kr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return kr.container(Qs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return kr.container(Qs.list(t))},optional:t=>{if(t!=null)return kr.container(Qs.optional(t))},nullable:t=>{if(t!=null)return kr.container(Qs.nullable(t))},set:t=>{if(t!=null)return kr.container(Qs.set(t))},literal:t=>kr.container(Qs.literal(t._visit({string:r=>ZI.string(r),boolean:r=>ZI.boolean(r),_other:()=>{throw new j({message:"Unexpected literal type",code:j.Code.InternalError})}}))),named:()=>{}}})}var fbe=class extends oo{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:vc.enum({default:n!=null?r.find(i=>Xt(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}};var Okr=class extends oo{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=kr.container(Qs.map({keyType:oo.STRING,valueType:kr.unknown()}));return{type:vc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new nP({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=kr.container(Qs.map({keyType:oo.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return{type:vc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};var t8f=["description","title","format","type","discriminator","xml","externalDocs","extensions"],cic=["example","default"],uic=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],r8f=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],n8f=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],i8f=["allOf","oneOf","anyOf"];function lic(e,t){let r=pic(t),n={};for(let i of r)n=xno(n,i);return s8f(n,e),n}function pic(e){let t=[];for(let r of e)if(Array.isArray(r.allOf)&&r.allOf.length>0){let{allOf:n,...i}=r,o=n.filter(s=>!("$ref"in s));t.push(...pic(o)),Object.keys(i).length>0&&t.push(i)}else t.push(r);return t}function xno(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||i8f.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=o8f(o??{},i);continue}if(n==="items"){dbe(o)&&dbe(i)?r[n]=xno(o,i):r[n]=i;continue}if(cic.includes(n)){dbe(o)&&dbe(i)?r[n]=fic(o,i):r[n]=i;continue}if(uic.includes(n)){r[n]=!!o||!!i;continue}if(r8f.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(n8f.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function o8f(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];dbe(o)&&dbe(i)?r[n]=xno(o,i):r[n]=i}return r}function fic(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];dbe(o)&&dbe(i)?r[n]=fic(o,i):r[n]=i}return r}function s8f(e,t){for(let r of t8f){let n=t[r];n!=null&&(e[r]=n)}for(let r of cic){let n=t[r];n!=null&&(e[r]=n)}for(let r of uic)t[r]===!0&&(e[r]=!0)}function dbe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Rt();function qXe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let o=[],s={},a={},c=new Set;for(let[u,l]of Object.entries(e??{})){let p=[...r,"properties",u];if(typeof l!="object"){i.collect({message:`Schema property ${u} should be an object`,path:p});continue}let d=c8f(r,l,n)??n.convertBreadcrumbsToName(p),f="nullable"in l?l.nullable:!1,h=new nP({context:n,breadcrumbs:p,schemaOrReference:l,schemaIdOverride:d,wrapAsOptional:!t.includes(u),wrapAsNullable:f}).convert();if(h!=null){o.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:h.type,docs:l.description,availability:h.availability,propertyAccess:n.getPropertyAccess(l),v2Examples:h.schema?.typeDeclaration?.v2Examples??a8f({propertySchema:l,breadcrumbs:p,context:n,propertyId:d})}),s={...s,...h.inlinedTypes},h.schema?.typeDeclaration.referencedTypes!=null&&h.schema.typeDeclaration.referencedTypes.forEach(A=>{c.add(A)});for(let A of h.schema?.audiences??[])a[A]==null&&(a[A]=new Set),a[A].add(u)}}for(let u of Object.keys(s))c.add(u);return{convertedProperties:o,propertiesByAudience:a,inlinedTypesFromProperties:s,referencedTypes:c}}function a8f({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new vv({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:h}=m.convert();u[f]=h}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new vv({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function c8f(e,t,r){return r.isReferenceObject(t)?void 0:new uw.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var GXe=class extends oo{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:vc.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=qXe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,u=n,l=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,h]of Object.entries(f.properties))!this.context.isReferenceObject(h)&&p[m]==null&&(p[m]=h)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],h,A=!1;if(this.context.isReferenceObject(f)){let O=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(O==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(h=O,typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0),!c||Object.keys(h.properties??{}).every(F=>!this.schema.required?.includes(F))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else h=f,A=!0;typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0);let b=h.oneOf??h.anyOf;if(b!=null&&h.type==null&&h.properties==null){let O=new Set(r.map(F=>Xt(F.name)));for(let[F,T]of b.entries()){let V=[...m,h.oneOf!=null?"oneOf":"anyOf",F.toString()],K=this.context.isReferenceObject(T)?this.context.resolveMaybeReference({schemaOrReference:T,breadcrumbs:V}):T;if(K==null)continue;let Z={};for(let[Re,ne]of Object.entries(K.properties??{}))!this.context.isReferenceObject(ne)&&"not"in ne||(Z[Re]=ne);let Y=Object.keys(Z).filter(Re=>!O.has(Re));if(Y.length===0)continue;let le={};for(let Re of Y){let ne=Z[Re];ne!=null&&(le[Re]=ne,O.add(Re))}let{convertedProperties:Ae,inlinedTypesFromProperties:ae,referencedTypes:me,propertiesByAudience:Pe}=qXe({properties:le,required:[],breadcrumbs:V,context:this.context,errorCollector:this.context.errorCollector});r.push(...Ae),u={...u,...ae},l={...l,...Pe},me.forEach(Re=>{a.add(Re)})}continue}let v=h.properties??{};if(A){v={};for(let[O,F]of Object.entries(h.properties??{})){let T=p[O];T!=null&&!this.context.isReferenceObject(F)?v[O]={...T,...F}:v[O]=F}}let{convertedProperties:x,inlinedTypesFromProperties:C,referencedTypes:w,propertiesByAudience:B}=qXe({properties:v,required:[...this.schema.required??[],...h.required??[]],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector});r.push(...x),u={...u,...C},l={...l,...B},w.forEach(O=>{a.add(O)})}for(let d of Object.keys(u))a.add(d);return{type:vc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(Ra),extendedProperties:[],extraProperties:t}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}};var Pkr=class extends qa{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var cQe=class extends oo{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new Pkr({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null)return this.convertAsDiscriminatedUnion();if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new VXe({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new fbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let[l,p]of Object.entries(this.schema.discriminator.mapping??{})){let d=this.context.getTypeIdFromSchemaReference({$ref:p}),f=[...this.breadcrumbs,"discriminator","mapping",l],m=this.context.resolveReference({reference:{$ref:p},breadcrumbs:f}),h={$ref:p};m.resolved&&m.value.properties!=null&&t in m.value.properties&&(h=this.filterDiscriminantFromSchema(m.value,t));let A=new nP({context:this.context,schemaOrReference:h,schemaIdOverride:d??void 0,breadcrumbs:f});d!=null&&n.add(d);let b=A.convert();if(b?.type!=null&&d!=null){for(let O of Object.keys(b?.inlinedTypes??{}))n.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])n.add(O);let v=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),x=p.split("/").pop()??d,C=m.resolved?m.value.title:void 0,w=m.resolved?m.value.description:void 0,B=C??l??x;b.schema?.typeDeclaration!=null&&C!=null&&(b.schema.typeDeclaration.name.displayName=C),r.push({docs:w,discriminantValue:v,availability:b.availability,displayName:B,shape:uS.samePropertiesAsObject({typeId:d,name:this.context.casingsGenerator.generateName(x),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:B})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=qXe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let h=this.context.typeReferenceToDeclaredTypeName(f.reference);h!=null&&c.push(h)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let l of Object.keys({...i,...a}))n.add(l);let u=new zXe({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:vc.union({baseProperties:o,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:u.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[i,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else{let f=this.getDiscriminatorKeyForRef(o);f!=null?p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:f,displayNameOverrideSource:"discriminator_key"}):p=this.context.convertReferenceToTypeReference({reference:o,breadcrumbs:this.breadcrumbs})}if(p.ok){let f=this.context.resolveReference({reference:o,breadcrumbs:this.breadcrumbs}),m=f.resolved?f.value.description:void 0;t.push({type:p.reference,docs:m})}let d=this.context.getTypeIdFromSchemaReference(o);d!=null&&r.add(d);continue}let s=this.extendSubSchema(o),a=this.context.convertBreadcrumbsToName([`${this.id}_${i}`]),c=o.title,l=new mbe({context:this.context,id:a,nameOverride:c,breadcrumbs:[...this.breadcrumbs,`oneOf[${i}]`],schema:s??o}).convert();if(l!=null){let p=l.convertedSchema.typeDeclaration.shape;if(p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf))t.push({type:p.aliasOf,docs:o.description});else if(p.type==="object"&&p.properties.length===0&&p.extends.length===0)t.push({type:kr.container(Qs.map({keyType:oo.STRING,valueType:kr.unknown()})),docs:o.description});else{t.push({type:this.context.createNamedTypeReference(a,c),docs:o.description});let d=this.context.getNamespacedSchemaId(a);n={...n,...l.inlinedTypes,[d]:l.convertedSchema}}l.convertedSchema.typeDeclaration.referencedTypes.forEach(d=>{r.add(d)})}}return{type:vc.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new nP({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:vc.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return kr.container(Qs.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}};var WXe=class extends oo{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return kr.container(Qs.literal(ZI.string(t)));if(this.schema.format==="date-time-rfc-2822")return kr.primitive({v1:fs.DateTimeRfc2822,v2:$n.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return kr.primitive({v1:fs.Date,v2:$n.date({})});if(this.schema.format==="date-time")return kr.primitive({v1:fs.DateTime,v2:$n.dateTime({})})}return kr.primitive({v1:"STRING",v2:$n.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return kr.primitive({v1:"FLOAT",v2:$n.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return kr.primitive({v1:"LONG",v2:$n.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return kr.primitive({v1:"UINT",v2:$n.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return kr.primitive({v1:"FLOAT",v2:$n.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return kr.primitive({v1:"LONG",v2:$n.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return kr.primitive({v1:"UINT",v2:$n.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?kr.container(Qs.literal(ZI.boolean(t))):kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}};var u8f=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],mbe=class e extends oo{schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let o=this.tryConvertArraySchema();if(o!=null)return o;let s=this.tryConvertTypeArraySchema();if(s!=null)return s;let a=this.tryConvertOneOfAnyOfSchema();if(a!=null)return a;let c=this.tryConvertMapSchema();if(c!=null)return c;let u=this.tryConvertDiscriminatorMappingSchema();if(u!=null)return u;let l=this.tryConvertObjectAllOfSchema();if(l!=null)return l;let p=this.tryConvertUntypedSchema();if(p!=null)return p;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new uw.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new fbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let u;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,h]of Object.entries(f.properties??{}))!this.context.isReferenceObject(h)&&"not"in h||m in p||(p[m]=h)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(u)}if(i)return;let o=lic(this.schema,n),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryConvertPrimitiveSchema(){let r=new WXe({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new $Xe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new cQe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new Okr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new cQe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new GXe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:kr.unknown(),resolvedType:kr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new uw.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=aic(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...u8f,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}};var nP=class extends oo{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{}}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>!i.properties&&!i.enum&&!i.oneOf&&!i.anyOf&&!i.allOf&&!i.format&&!("items"in i))&&!r.some(i=>i.type==="null"||Array.isArray(i.type)&&i.type.includes("null"))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{}}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new mbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return kr.container(Qs.optional(t))}wrapInNullable(t){return kr.container(Qs.nullable(t))}};var $Xe=class e extends oo{static LIST_UNKNOWN=kr.container(Qs.list(kr.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),{typeReference:kr.container(Qs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Dkr=class extends oo{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=Wn(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}};var Rkr=class extends oo{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??oo.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??oo.OPTIONAL_STRING,env:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??oo.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},n=this.parameter.example,i=this.parameter.examples;for(let[o,s]of Object.entries(i??{})){let a=this.context.resolveExampleWithValue(s);a!=null&&(r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:a,exampleName:o}))}if(n!=null){let o=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:n,exampleName:o})}if(Object.keys(r.userSpecifiedExamples).length===0){let o=`${this.parameter.name}_example`;r.autogeneratedExamples[o]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:o})}return r}generateOrValidateExample({schema:t,example:r}){let n=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};Rt();var Fkr=class extends qa{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var dic="Base",l8f="x-fern-default-url",v6=class e extends oo{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=this.endpointLevelServers?.map(h=>[e.getServerName({server:h,context:this.context}),this.getServerUrl(h)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,environments:q0.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(Ra);return{value:{defaultEnvironment:r[0]?.id,environments:q0.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new Fkr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new UXe({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?dic:e.getServerExtensionName({server:this.servers[0],context:this.context})??dic}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[l8f];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}};var uQe=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new vv({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?ub.WARNING:ub.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:ub.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?ub.WARNING:ub.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:ub.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf)return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:h,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let v of b){n++;let x={endpointPath:c,method:p,exampleName:v.name,exampleSource:v.source,requestExample:v.request,responseExample:v.response,requestSchema:m,responseSchema:h,responseStatusCode:v.statusCode,responseSchemas:A},C=this.validateEndpointExample({exampleToValidate:x});f.push(C),C.isValid?i++:(o++,v.source==="human"?s.push(C):v.source==="ai"&&a.push(C))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(v=>!v.isValid),invalidExampleCount:f.filter(v=>!v.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}};var HXe=new RegExp("[^\\x00-\\x7F]"),p8f=/(?:^|\n)\s*---\s*(?:\n|$)/;function mic({tags:e,errorCollector:t}){for(let r of e)if(HXe.test(r.name)){let n=[...r.name].filter(i=>HXe.test(i));t.collect({level:ub.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(HXe,"").trim()}".`})}}function hic({description:e,path:t,errorCollector:r}){p8f.test(e)&&r.collect({level:ub.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function _no({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");mic({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let u=c;if(typeof u.description=="string"&&hic({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&HXe.test(l)){n.add(l);let p=[...l].filter(d=>HXe.test(d));t.collect({level:ub.ERROR,message:`Tag name "${l}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${l}" to "${l.replace(HXe,"").trim()}".`})}}}}}}var kkr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},f8f=new Set(Object.values(kkr));function Bno(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}Wi();ts();var d8f=It.object({type:It.string(),channelId:It.string().optional(),messageId:It.string(),value:It.any()}),m8f=It.object({summary:It.string().optional(),description:It.string().optional(),"query-parameters":It.record(It.string()).optional(),headers:It.record(It.string()).optional(),messages:It.array(d8f)}),gic=It.array(m8f);var Nkr=class extends qa{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=gic.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}};var KXe=class extends oo{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new Nkr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var h8f="x-fern-server-name",k7=class e extends oo{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,environments:q0.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[h8f];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var hbe=class extends Yd.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new uw.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}};var Qkr=class extends qa{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var gbe=class extends qa{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}};var jkr=class extends qa{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}};var Mkr=class extends KXe{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new gbe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let l=new Qkr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=ob(p),m=Wn(this.channelPath),h=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})}},audiences:h,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=OPe(Wn(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=kr.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=Z1.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new gbe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new hbe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0}}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new hbe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0}}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return k7.getServerName(t,n)}return t}getOperationMethodName(t){return new jkr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new hbe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1}}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}};var Lkr=class extends k7{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Tno="$message.",Aic="#/channels/",Ono="#/servers/",Ukr=class extends KXe{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new gbe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((f,[m,h])=>{try{this.getChannelPathFromOperation(h)===this.channelPath&&(f[m]=h)}catch{}return f},{}),a=[];for(let[f,m]of Object.entries(s)){let A=new gbe({breadcrumbs:[...this.breadcrumbs,f],node:m,context:this.context}).convert()??f;for(let b of m.messages){let v=this.context.convertReferenceToTypeReference({reference:b});if(v.ok){let x=Z1.reference({bodyType:v.reference,docs:m.description});a.push({type:f,displayName:A,origin:m.action==="send"?"client":"server",body:x,availability:this.context.getAvailability({node:m,breadcrumbs:this.breadcrumbs}),docs:m.description,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=ob(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:l,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:u,baseUrl:c,asyncApiVersion:"v3"})}},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(Ono,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:u}=a,p=new hbe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(Tno)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${Tno} prefix`,path:this.breadcrumbs});return}let i=r.substring(Tno.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(Ono)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(Ono.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return k7.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return k7.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(Aic))throw new j({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:j.Code.ReferenceError});return t.channel.$ref.substring(Aic.length)}};var zkr=class extends k7{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var AQt=class extends F7{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let u=`${r}_${i}`;this.convertSchema({id:u,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new zkr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Lkr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=Ckt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return Gp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:t.description});if(t.scheme?.toLowerCase()==="basic")return Gp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,docs:t.description});break}case"apiKey":{if(t.in==="header")return Gp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:oo.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:t.description});break}case"oauth2":return Gp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:t.description})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new uw.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new Ukr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new Mkr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}};var yQt=class extends A0{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let u=a[1],l=a[2];return o=`${u}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};Rt();Jt();var wic=Ie(Vkr(),1);var qkr=class extends qa{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Gkr=class extends qa{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function y8f(e){if(e!=null){if(typeof e=="string")return Yt.Literal.string(e);if(typeof e=="boolean")return Yt.Literal.boolean(e)}}function yic({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:oo.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:oo.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:y8f(i.default)})}return r}function b8f(e){if(e!=null){if(typeof e=="string")return Yt.Literal.string(e);if(typeof e=="boolean")return Yt.Literal.boolean(e)}}function bic({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?oo.OPTIONAL_STRING:oo.STRING,env:r.env,v2Examples:r.optional?void 0:E8f({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:b8f(r["x-fern-default"])}))}function E8f({header:e,context:t}){let r=new vv({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}Wi();var Wkr=class extends Yd.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let n=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),o=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:n}).convert();o!=null&&(t=o.type,r=o.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};Rt();var $kr=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:u,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u,this.queryParameters=l??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if($f.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=$f.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=$f.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:fd.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes})}:{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:kr.unknown(),v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:fd.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[Xt(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:fd.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?xC.file(_2.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):xC.file(_2.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):xC.bodyProperty({...t,contentType:n?.contentType??r,style:v8f({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i==null||this.context.isReferenceObject(i))return;let o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let u=c.schema?.typeDeclaration.shape;if(u?.type==="object")return{requestBody:fd.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>Xt(n.name).toLowerCase()));return t.some(n=>r.has(Xt(n.name).toLowerCase()))}},I8f={"application/json":"json"};function v8f({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return I8f[e.contentType]}}var C8f=/{([^}]+)}/g,x8f=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),JXe=class extends oo{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o}convertHttpMethod(){switch(this.method){case"get":return kd.Get;case"post":return kd.Post;case"put":return kd.Put;case"delete":return kd.Delete;case"patch":return kd.Patch;case"head":return kd.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let o of this.operation.parameters){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t});if(s==null)continue;let c=new Wkr({context:this.context,breadcrumbs:t,parameter:s}).convert();if(c!=null)switch(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type){case"path":r.push(c.parameter);break;case"query":n.push(c.parameter);break;case"header":{let u=Vr(c.parameter.name),l=Xt(c.parameter.name),p=!1,d=this.context.authOverrides?.["auth-schemes"];if(d!=null){for(let m of Object.values(d))if(B8f(m)&&m.header.toLowerCase()===l.toLowerCase()){p=!0;break}}let f=this.context.globalHeaderNames;if(f!=null){for(let m of f)if(m.toLowerCase()===l.toLowerCase()){p=!0;break}}!x8f.has(u.toLowerCase())&&!p&&i.push(c.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}checkMissingPathParameters(t){let n=[...this.path.matchAll(C8f)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:oo.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,u]of Object.entries(s.content)){let p=new $kr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new uw.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new uw.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?Wn(this.operation.summary):Wn(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let n=Eic(t),i=Eic(r);return JE(n,i)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:n,methodName:r,methodNameTokens:i})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:n};let s=i.slice(r.length);return{group:[t],method:Wn(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Yd.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}};function Eic(e){let t=w8f(e)?S8f(e):_8f(e);return t=t.map(r=>r.toLowerCase()),t=B3(t),t}function w8f(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function S8f(e){return e.split(/(?=[A-Z])/)}function _8f(e){return e.split(/[^a-zA-Z0-9]+/)}function B8f(e){return e?.header!=null}var YXe=class extends JXe{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let u,l;if(c.type==="inlinedRequestBody")u=lS.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=lS.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")l={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=lS.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let p=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:u,signatureVerification:void 0,fileUploadPayload:l,responses:p.length>0?p:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}};var Rno=Ie(Vkr(),1);var Iic=["get","post","put","delete","patch","head"];var Hkr=class extends qa{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};ts();var T8f=It.object({cursor:It.string(),next_cursor:It.string(),results:It.string()}),O8f=It.object({offset:It.string(),results:It.string(),step:It.string().optional(),"has-next-page":It.string().optional()}),P8f=It.object({next_uri:It.string(),results:It.string()}),D8f=It.object({next_path:It.string(),results:It.string()}),Pno=It.union([It.boolean(),T8f,O8f,P8f,D8f]);var Dno="$request.",ybe="$response.",Kkr=class extends qa{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Pno.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=Pno.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:A0.maybeTrimPrefix(r.cursor,Dno),nextCursor:A0.maybeTrimPrefix(r.next_cursor,ybe),results:A0.maybeTrimPrefix(r.results,ybe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:A0.maybeTrimPrefix(n.next_uri,ybe),results:A0.maybeTrimPrefix(n.results,ybe)};let i=t;if("next_path"in i)return{type:"path",nextPath:A0.maybeTrimPrefix(i.next_path,ybe),results:A0.maybeTrimPrefix(i.results,ybe)};let o=t;return{type:"offset",offset:A0.maybeTrimPrefix(o.offset,Dno),results:A0.maybeTrimPrefix(o.results,ybe),step:o.step!=null?A0.maybeTrimPrefix(o.step,Dno):void 0,hasNextPage:o["has-next-page"]!=null?A0.maybeTrimPrefix(o["has-next-page"],ybe):void 0}}};ts();var R8f="$request.",F8f=It.object({"stream-condition":It.string().optional(),format:It.enum(["sse","json"]).optional(),"stream-description":It.string().optional(),"stream-request-name":It.string().optional(),"response-stream":It.any(),response:It.any(),terminator:It.string().optional()}),k8f=It.union([It.boolean(),F8f]),Jkr=class extends qa{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=k8f.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:A0.maybeTrimPrefix(r.data["stream-condition"],R8f),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response}}};var Ykr=class extends qa{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};Wi();Rt();var Zkr=require("fs"),vic=require("path");function N8f(e){return fa(e)&&typeof e.$ref=="string"}function Q8f(e,t){if(e!=null){if(typeof e=="string")return e;if(N8f(e)){let r=(0,vic.resolve)(t??process.cwd(),e.$ref);if((0,Zkr.existsSync)(r))try{return(0,Zkr.readFileSync)(r,"utf-8")}catch{return}}}}var Xkr=class extends qa{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=fa(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!fa(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=Q8f(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}};Rt();var t2r=require("fs"),Cic=require("path");function j8f(e){return fa(e)&&typeof e.$ref=="string"}function M8f(e,t){if(e!=null){if(typeof e=="string")return e;if(j8f(e)){let r=(0,Cic.resolve)(t??process.cwd(),e.$ref);if((0,t2r.existsSync)(r))try{return(0,t2r.readFileSync)(r,"utf-8")}catch{return}}}}function L8f(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!fa(n))continue;let o=M8f(n.code,t);o!=null&&r.push({...n,code:o})}return r}var e2r=class extends qa{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!fa(o))return o;let a=o["code-samples"];if(a!=null){let c=L8f(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=oh.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}};var bQt=class extends qa{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};Rt();var EQt=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:yu.json(Wb.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:yu.streaming(XE.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:yu.streaming(XE.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:yu.streaming(XE.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:yu.json(Wb.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:yu.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:yu.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:yu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return $f.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=oo.OPTIONAL_STRING;if(s!=null){let u=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});u!=null&&(u.type==="number"||u.type==="integer"?a=kr.primitive({v1:u.type==="integer"?"INTEGER":"DOUBLE",v2:u.type==="integer"?$n.integer({default:void 0,validation:void 0}):$n.double({default:void 0,validation:void 0})}):u.type==="boolean"&&(a=kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})})))}let c=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:c,availability:void 0,clientDefault:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,c]of Object.entries(s??{})){let u=this.context.resolveExampleWithValue(c);u!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:u}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};var r2r=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:kr.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:xic(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return kkr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?xic(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=oo.OPTIONAL_STRING;if(s!=null){let u=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});u!=null&&(u.type==="number"||u.type==="integer"?a=kr.primitive({v1:u.type==="integer"?"INTEGER":"DOUBLE",v2:u.type==="integer"?$n.integer({default:void 0,validation:void 0}):$n.double({default:void 0,validation:void 0})}):u.type==="boolean"&&(a=kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})})))}let c=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:c,availability:void 0,clientDefault:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,c]of Object.entries(s??{})){let u=this.context.resolveExampleWithValue(c);u!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:u}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};function xic(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var n2r=class e extends JXe{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,idempotent:s,idToAuthScheme:a,topLevelServers:c,pathLevelServers:u,streamingExtension:l}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o}),this.idempotent=s,this.idToAuthScheme=a,this.topLevelServers=c,this.pathLevelServers=u,this.streamingExtension=l}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),{headers:o,pathParameters:s,queryParameters:a}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),c=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:a}),u=c?.[0]?.requestBody,l=c?.[0]?.streamRequestBody,p={requestBodies:c?.map(me=>me.requestBody)},d=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),f=d?.response,m=d?.streamResponse,h=d!=null?d.errors:[],A={},b=h.map(me=>me.error),v=ob(this.path),x=this.getEndpointBaseUrl(),C=this.getEndpointBaseUrls(),w=this.convertExamples({httpPath:v,httpMethod:t,baseUrl:x});if(Object.keys(w.examples).length===0&&Object.keys(w.streamExamples).length===0){let me=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:v,httpMethod:t,baseUrl:x});if(me!=null)for(let[Pe,Re]of Object.entries(me))w.examples[Pe]=Re}let B=new Set(this.operation.security?.flatMap(me=>Object.keys(me))??[]),O=this.authSchemeToHeaders(Array.from(B));O.length>0&&o.push(...O);for(let me of h){let Pe=me.error,Re=me.errorType,ne=Pe.error.errorId,ie=me.examples;A[ne]={name:Pe.error,displayName:me.displayName,discriminantValue:{name:Pe.error.name,wireValue:ne},type:Re,statusCode:me.statusCode,isWildcardStatusCode:me.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:ie??{},autogeneratedExamples:{}},headers:me.headers}}let F=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],V=new bQt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),Y=new bQt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??V,le={displayName:this.operation.summary,method:t,baseUrl:x,v2BaseUrls:C,path:v,pathParameters:s,queryParameters:a,headers:o.filter((me,Pe,Re)=>Pe===Re.findIndex(ne=>Xt(ne.name)===Xt(me.name))),responseHeaders:d?.responseHeaders,sdkRequest:void 0,errors:b,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:v,allPathParameters:s,pagination:void 0,transport:void 0,source:YT.openapi(),audiences:F,retries:void 0,apiPlayground:Y},Ae=this.context.namespace!=null?[this.context.namespace]:[],ae=r?.map(me=>Wn(me));return Ae.push(...ae??[]),{audiences:F,group:r,groupDisplayName:i,errors:A,endpoint:{...le,id:`endpoint_${Ae.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:u,v2RequestBodies:p,response:f,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w.examples},v2Responses:{responses:d?.v2Responses}},streamEndpoint:m!=null&&m.body!=null?{...le,id:`endpoint_${Ae.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:l,v2RequestBodies:void 0,response:m,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:m.body,docs:m.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let h=new EQt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(h==null){a=!0;continue}h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.streamResponseBody,docs:f.description},h.headers!=null&&(o.responseHeaders=h.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let h=new r2r({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!0:void 0}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},o.errors.push(h))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new EQt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:yu.json(Wb.response({...c.value,responseBodyType:kr.container(Qs.optional(u))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():Bno(this.operation.security??this.context.spec.security)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:oo.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new e2r({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new Xkr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={displayName:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:Yt.V2HttpEndpointResponseBody.json(c)}}}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Yt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Yt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new uw.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${Bn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return v6.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(n=>{let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return v6.getServerName({server:o,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let n=t?.[t.length-1];if(n!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===n?r:void 0}};var i2r=class extends oo{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s}convert(){let t=[],r=[],n={};for(let i of Iic){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let u=new Jkr({breadcrumbs:s,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new Ykr({breadcrumbs:n,operation:t,context:i}).convert()?new YXe({context:this.context,breadcrumbs:n,operation:t,method:Rno.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new Kkr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new Hkr({breadcrumbs:n,operation:t,context:this.context}).convert();return new n2r({context:this.context,breadcrumbs:n,operation:t,method:Rno.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:c,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}};var o2r=class extends oo{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",n=t?.env;return Gp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:n,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",n=t?.password?.name??"password",i=t?.username?.env,o=t?.password?.env;return Gp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(n),usernameEnvVar:i,passwordEnvVar:o,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",n=t?.env,i=t?.prefix;return Gp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:oo.OPTIONAL_STRING,prefix:i,headerEnvVar:n,docs:this.securityScheme.description})}break}case"oauth2":return Gp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var IQt=class extends F7{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),_no({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=yic({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new Gkr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=bic({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertBasePath(){let r=new qkr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=ob(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=Ckt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new o2r({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let i=xkt({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return i!=null&&this.addEnvironmentsToIr({environmentConfig:i.environmentsConfig,audiences:i.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let n=new v6({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new YXe({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:wic.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[n,i]of Object.entries(this.context.spec.paths??{})){if(i==null)continue;let s=new i2r({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:i,path:n}).convert();if(s!=null){for(let a of s.endpoints){if(a.streamEndpoint!=null&&this.addEndpointToIr({endpoint:a.streamEndpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),this.addEndpointToIr({endpoint:a.endpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),a.servers)for(let c of a.servers)this.shouldAddServerToCollectedServers({server:c,currentServers:t})&&t.push(c);if(a.errors)for(let[c,u]of Object.entries(a.errors))r[c]=u}for(let a of s.webhooks){let c=this.context.getGroup({groupParts:a.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:a.webhook,operationId:c.join("."),group:c,audiences:a.audiences})}this.addTypesToIr(s.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security&&delete i.security}}}};var s2r=class extends qa{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var bue=class extends A0{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let u;if(o.includes("/")){let p=new Yd.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>Xt(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new s2r({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=i}return this.tagToDisplayName[t]??t}};var U8f={GET:kd.Get,POST:kd.Post,PUT:kd.Put,PATCH:kd.Patch,DELETE:kd.Delete};function kno({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=aDe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>z8f({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function z8f({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"],i=Sic({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=Fno({ir:e,endpoint:o,wireValue:N7(c?.["client-id"],"client_id")}),p=Fno({ir:e,endpoint:o,wireValue:N7(c?.["client-secret"],"client_secret")}),d=XXe({ir:e,endpoint:o,wireValue:N7(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return Gp.oauth({key:t,docs:r.docs,configuration:G$.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:l,clientSecret:p,scopes:void 0,customProperties:G8f({ir:e,endpoint:o,excludeWireValues:[N7(c?.["client-id"],"client_id"),N7(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:XXe({ir:e,endpoint:o,wireValue:N7(u?.["expires-in"],"expires_in")}),refreshToken:XXe({ir:e,endpoint:o,wireValue:N7(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?V8f({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function V8f({ir:e,refreshTokenConfig:t}){let r=Sic({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=Fno({ir:e,endpoint:n,wireValue:N7(s?.["refresh-token"],"refresh_token")}),u=XXe({ir:e,endpoint:n,wireValue:N7(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:XXe({ir:e,endpoint:n,wireValue:N7(a?.["expires-in"],"expires_in")}),refreshToken:XXe({ir:e,endpoint:n,wireValue:N7(a?.["refresh-token"],"refresh_token")})}}}function Sic({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=U8f[r[0]?.toUpperCase()??""],i=r[1]?.replace(/\/+$/,"");if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(q8f(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function q8f(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t.replace(/\/+$/,"")}function N7(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function _ic(e,t){return e.find(r=>Xt(r.name)===t)}function Nno(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function Fno({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties:t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=Nno(e,t.requestBody.requestBodyType.typeId));let i=n!=null?_ic(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:J1.body({...i})}}function G8f({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties:t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=Nno(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(Xt(s.name))).map(s=>({propertyPath:void 0,property:J1.body({...s})}));return o.length>0?o:void 0}function XXe({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=Nno(e,n.typeId),o=i!=null?_ic(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}Rt();ts();var W8f=It.object({description:It.string().optional(),required:It.boolean().optional(),deprecated:It.boolean().optional(),allowEmptyValue:It.boolean().optional(),style:It.string().optional(),explode:It.boolean().optional(),allowReserved:It.boolean().optional(),schema:It.any().optional(),example:It.any().optional(),examples:It.record(It.string(),It.any()).optional(),content:It.record(It.string(),It.any()).optional()}),$8f=W8f.extend({name:It.string(),in:It.string()}),H8f=It.array($8f),a2r=class extends qa{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return H8f.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${oi(r)}`,path:this.breadcrumbs});return}}};var c2r=class extends oo{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=ob(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let h=this.context.resolveReference({reference:l});if(h.resolved)p=h.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Yd.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Yd.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?fd.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:yu.json(Wb.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:YT.openrpc(),audiences:a,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return v6.getServerName({server:s,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let n of this.method.examples??[]){let i;if(this.context.isReferenceObject(n)){let c=this.context.resolveReference({reference:n});if(c.resolved)i=c.value;else continue}else i=n;let o;if(i.result)if(this.context.isReferenceObject(i.result)){let c=this.context.resolveReference({reference:i.result});c.resolved&&(o=c.value)}else o=i.result;let s=i.name??`Example ${r+1}`,a=[];if(i.params&&Array.isArray(i.params)){a=[];for(let c of i.params)if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c});if(u.resolved)a.push(u.value);else continue}else a.push(c)}t[s]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:a.map(c=>c.value)??void 0},response:{docs:void 0,statusCode:void 0,body:o?.value?Yt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:i.examplePairedRequest?.id||"1",result:o.value}):void 0},codeSamples:[]}}++r}return t}};var u2r=class extends Yd.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var vQt=class extends F7{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new v6({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new a2r({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new u2r({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new c2r({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}};var CQt=class extends A0{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};var ooo=require("fs/promises");var Bic=require("fs/promises");async function Qno({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,Bic.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Tr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await MXe({absoluteFilePathToOverrides:a,context:e,data:s});return s}Jt();var rsc=Ie(tsc(),1);function Uqf(e,t){if(!t)return;if(e.catch(()=>{}),t.aborted){e.kill();return}let r=()=>{e.kill()};t.addEventListener("abort",r,{once:!0}),e.finally(()=>t.removeEventListener("abort",r)).catch(()=>{})}function C6(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let c=i.reduce((p,d)=>({...p,[d]:"<redacted>"}),o),u=[t,...r].join(" ");for(let[p,d]of Object.entries(c))u=u.replaceAll(p,d);e?.debug(`+ ${u}`);let l=(0,rsc.default)(t,r,a);return Uqf(l,s),l}async function Eu(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let c=C6(e,t,r,{doNotPipeOutput:n,secrets:i,substitutions:o,signal:s,...a});n||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let u=await c;return u.stdout==null&&(u.stdout=""),u.stderr==null&&(u.stderr=""),u}function Q7(e,{logger:t,...r}={}){return(n,i)=>Eu(t,e,n,{...r,...i})}var lF=require("fs/promises"),hsc=Ie(require("path"),1),oio=Ie(nS(),1);Rt();Jt();var lQe=require("fs/promises"),ssc=Ie(nS(),1);Jt();var y0=require("fs/promises"),A2r=Ie(require("os"),1),rio=Ie(require("path"),1),Eue="v1.50.0",zqf="https://github.com/bufbuild/buf/releases/download",BQt="buf",Vqf=".fern",qqf="bin",nsc=12e4,eio=200;function nio(){let e=A2r.default.platform(),t=A2r.default.arch(),r;switch(e){case"linux":r="Linux";break;case"darwin":r="Darwin";break;case"win32":r="Windows";break;default:throw new j({message:`Unsupported platform: ${e}`,code:j.Code.EnvironmentError})}let n;switch(t){case"x64":n="x86_64";break;case"arm64":n=e==="linux"?"aarch64":"arm64";break;default:throw new j({message:`Unsupported architecture: ${t}`,code:j.Code.EnvironmentError})}return{os:r,arch:n,extension:r==="Windows"?".exe":""}}function TQt(){let e=A2r.default.homedir();return $t.of(rio.default.join(e,Vqf,qqf))}function Gqf(){let{extension:e}=nio(),t=TQt();return $e(t,Te.of(`${BQt}-${Eue}${e}`))}function Wqf(){let{extension:e}=nio(),t=TQt();return $e(t,Te.of(`${BQt}${e}`))}function $qf(){let e=TQt();return $e(e,Te.of(`${BQt}.version`))}function Hqf(){let e=TQt();return rio.default.join(e,`${BQt}.lock`)}function Kqf(){let{os:e,arch:t,extension:r}=nio();return`${zqf}/${Eue}/${BQt}-${e}-${t}${r}`}async function isc(e){try{return await(0,y0.access)(e),!0}catch{return!1}}async function Jqf(e){let t=Hqf(),r=Date.now()+nsc;for(;Date.now()<r;)try{return await(0,y0.mkdir)(t,{recursive:!1}),tio(t,e)}catch{e.debug(`Waiting for buf lock on ${t}...`),await new Promise(n=>setTimeout(n,eio))}e.debug(`Buf lock timed out after ${nsc}ms, breaking stale lock`);try{await(0,y0.rm)(t,{recursive:!0})}catch(n){e.debug(`Failed to remove stale buf lock: ${n instanceof Error?n.message:String(n)}`)}try{await(0,y0.mkdir)(t,{recursive:!1})}catch{let n=Math.max(eio*5,r-Date.now()),i=Date.now()+n;for(;Date.now()<i;)try{return await(0,y0.mkdir)(t,{recursive:!1}),tio(t,e)}catch{e.debug(`Waiting for buf lock on ${t} (post-break retry)...`),await new Promise(o=>setTimeout(o,eio))}throw new j({message:"Failed to acquire buf lock after timeout and retry",code:j.Code.InternalError})}return tio(t,e)}function tio(e,t){return async()=>{try{await(0,y0.rm)(e,{recursive:!0})}catch(r){t.debug(`Failed to release buf lock: ${r instanceof Error?r.message:String(r)}`)}}}async function OQt(e){try{let t=TQt();await(0,y0.mkdir)(t,{recursive:!0});let r=await Jqf(e);try{return await Yqf(e)}finally{await r()}}catch(t){e.debug(`Failed to resolve buf: ${t instanceof Error?t.message:String(t)}`);return}}async function Yqf(e){let t=Gqf(),r=Wqf(),n=$qf();if(await isc(t))return await Xqf(n,e)===Eue&&await isc(r)?(e.info(`Using cached buf ${Eue}`),r):(await osc(t,r),await(0,y0.writeFile)(n,Eue),e.info(`Updated buf to ${Eue}`),r);let i=Kqf();e.info(`Downloading buf ${Eue}...`);let o=$t.of(`${t}.download`);try{let s=await fetch(i,{redirect:"follow"});if(!s.ok){e.debug(`Failed to download buf: ${s.status} ${s.statusText}`);return}let a=await s.arrayBuffer();return await(0,y0.writeFile)(o,new Uint8Array(a)),await(0,y0.chmod)(o,493),await(0,y0.rename)(o,t),await osc(t,r),await(0,y0.writeFile)(n,Eue),e.info(`Downloaded buf ${Eue}`),r}catch(s){e.debug(`Failed to download buf: ${s instanceof Error?s.message:String(s)}`);try{await(0,y0.rm)(o,{force:!0})}catch(a){e.debug(`Failed to clean up partial buf download: ${a instanceof Error?a.message:String(a)}`)}return}}async function Xqf(e,t){try{return(await(0,y0.readFile)(e,"utf-8")).trim()}catch(r){t.debug(`Failed to read buf version marker: ${r instanceof Error?r.message:String(r)}`);return}}async function osc(e,t){let r=$t.of(`${t}.tmp`);await(0,y0.copyFile)(e,r),await(0,y0.chmod)(r,493),await(0,y0.rename)(r,t)}function DQt(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var PQt,iio;async function RQt(e,t,r=5e3){return PQt!==void 0?PQt:(iio==null&&(iio=Zqf(e,t,r)),iio)}async function Zqf(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),PQt=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(n){let i=oi(n);return DQt(i)?(PQt=!0,t.debug(`Network check failed - entering air-gapped mode: ${i}`),!0):(PQt=!1,!1)}}async function FQt(e,t,r="buf"){let n=$e(e,Te.of("buf.lock")),i=!1;try{await(0,lQe.access)(n),i=!0,t.debug(`Found buf.lock at: ${n}`)}catch{t.debug(`No buf.lock found at: ${n}`)}if(!i)return!1;let o=$t.of((await ssc.default.dir()).path);try{let s=$e(e,Te.of("buf.yaml"));try{await(0,lQe.cp)(s,$e(o,Te.of("buf.yaml"))),await(0,lQe.cp)(n,$e(o,Te.of("buf.lock")))}catch{return!1}try{return await C6(t,r,["dep","update"],{cwd:o,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(a){let c=oi(a);return DQt(c)?(t.debug(`Network check failed - entering air-gapped mode: ${c.substring(0,100)}`),!0):!1}}finally{try{await(0,lQe.rm)(o,{recursive:!0,force:!0})}catch{}}}async function kQt(e){let t=Q7("which",{cwd:$t.of(process.cwd()),logger:void 0,doNotPipeOutput:!0});try{let n=(await t(["buf"])).stdout?.trim();return n?e.debug(`Found buf on PATH: ${n}`):e.debug("Found buf on PATH"),"buf"}catch{e.debug("buf not found on PATH, attempting auto-download");let r=await OQt(e);if(r!=null)return e.debug(`Using auto-downloaded buf: ${r}`),r;throw new j({message:"Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').",code:j.Code.EnvironmentError})}}var asc="buf.gen.yaml",e5f="output",csc=`${e5f}/ir.json`,usc="protoc-gen-fern",lsc=`version: v1
|
|
1629
|
+
`).reduce(rjf,Object.create(null)),rjf=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},njf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Jp=njf!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),qXa=class extends HNe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=Jp(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?Jp(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=Jp(e.path)),e.linkpath&&(e.linkpath=Jp(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},rFr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},ijf=1024*1024,Beo=Buffer.from([31,139]),Teo=Buffer.from([40,181,47,253]),ojf=Math.max(Beo.length,Teo.length),wU=Symbol("state"),jNe=Symbol("writeEntry"),uue=Symbol("readEntry"),deo=Symbol("nextEntry"),oXa=Symbol("processEntry"),wY=Symbol("extendedHeader"),X2t=Symbol("globalExtendedHeader"),j0e=Symbol("meta"),sXa=Symbol("emitMeta"),g0=Symbol("buffer"),lue=Symbol("queue"),M0e=Symbol("ended"),meo=Symbol("emittedEnd"),MNe=Symbol("emit"),$C=Symbol("unzip"),ORr=Symbol("consumeChunk"),PRr=Symbol("consumeChunkSub"),heo=Symbol("consumeBody"),aXa=Symbol("consumeMeta"),cXa=Symbol("consumeHeader"),Z2t=Symbol("consuming"),geo=Symbol("bufferConcat"),DRr=Symbol("maybeEnd"),lXe=Symbol("writing"),L0e=Symbol("aborted"),RRr=Symbol("onDone"),LNe=Symbol("sawValidEntry"),FRr=Symbol("sawNullBlock"),kRr=Symbol("sawEOF"),uXa=Symbol("closeStream"),sjf=()=>!0,dNt=class extends kXa.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[lue]=[];[g0];[uue];[jNe];[wU]="begin";[j0e]="";[wY];[X2t];[M0e]=!1;[$C];[L0e]=!1;[LNe];[FRr]=!1;[kRr]=!1;[lXe]=!1;[Z2t]=!1;[meo]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(RRr,()=>{(this[wU]==="begin"||this[LNe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(RRr,e.ondone):this.on(RRr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||ijf,this.filter=typeof e.filter=="function"?e.filter:sjf;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[uXa]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){rFr(this,e,t,r)}[cXa](e,t){this[LNe]===void 0&&(this[LNe]=!1);let r;try{r=new $Ne(e,t,this[wY],this[X2t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[FRr]?(this[kRr]=!0,this[wU]==="begin"&&(this[wU]="header"),this[MNe]("eof")):(this[FRr]=!0,this[MNe]("nullBlock"));else if(this[FRr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[jNe]=new qXa(r,this[wY],this[X2t]);if(!this[LNe])if(i.remain){let o=()=>{i.invalid||(this[LNe]=!0)};i.on("end",o)}else this[LNe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[MNe]("ignoredEntry",i),this[wU]="ignore",i.resume()):i.size>0&&(this[j0e]="",i.on("data",o=>this[j0e]+=o),this[wU]="meta"):(this[wY]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[MNe]("ignoredEntry",i),this[wU]=i.remain?"ignore":"header",i.resume()):(i.remain?this[wU]="body":(this[wU]="header",i.end()),this[uue]?this[lue].push(i):(this[lue].push(i),this[deo]())))}}}[uXa](){queueMicrotask(()=>this.emit("close"))}[oXa](e){let t=!0;if(!e)this[uue]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[uue]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[deo]()),t=!1);return t}[deo](){do;while(this[oXa](this[lue].shift()));if(this[lue].length===0){let e=this[uue];!e||e.flowing||e.size===e.remain?this[lXe]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[heo](e,t){let r=this[jNe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[wU]="header",this[jNe]=void 0,r.end()),i.length}[aXa](e,t){let r=this[jNe],n=this[heo](e,t);return!this[jNe]&&r&&this[sXa](r),n}[MNe](e,t,r){this[lue].length===0&&!this[uue]?this.emit(e,t,r):this[lue].push([e,t,r])}[sXa](e){switch(this[MNe]("meta",this[j0e]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[wY]=KRr.parse(this[j0e],this[wY],!1);break;case"GlobalExtendedHeader":this[X2t]=KRr.parse(this[j0e],this[X2t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[wY]??Object.create(null);this[wY]=t,t.path=this[j0e].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[wY]||Object.create(null);this[wY]=t,t.linkpath=this[j0e].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[L0e]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[L0e])return r?.(),!1;if((this[$C]===void 0||this.brotli===void 0&&this[$C]===!1)&&e){if(this[g0]&&(e=Buffer.concat([this[g0],e]),this[g0]=void 0),e.length<ojf)return this[g0]=e,r?.(),!0;for(let s=0;this[$C]===void 0&&s<Beo.length;s++)e[s]!==Beo[s]&&(this[$C]=!1);let i=!1;if(this[$C]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<Teo.length;s++)if(e[s]!==Teo[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[$C]===!1&&o)if(e.length<512)if(this[M0e])this.brotli=!0;else return this[g0]=e,r?.(),!0;else try{new $Ne(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[$C]===void 0||this[$C]===!1&&(this.brotli||i)){let s=this[M0e];this[M0e]=!1,this[$C]=this[$C]===void 0?new DQf({}):i?new NQf({}):new FQf({}),this[$C].on("data",c=>this[ORr](c)),this[$C].on("error",c=>this.abort(c)),this[$C].on("end",()=>{this[M0e]=!0,this[ORr]()}),this[lXe]=!0;let a=!!this[$C][s?"end":"write"](e);return this[lXe]=!1,r?.(),a}}this[lXe]=!0,this[$C]?this[$C].write(e):this[ORr](e),this[lXe]=!1;let n=this[lue].length>0?!1:this[uue]?this[uue].flowing:!0;return!n&&this[lue].length===0&&this[uue]?.once("drain",()=>this.emit("drain")),r?.(),n}[geo](e){e&&!this[L0e]&&(this[g0]=this[g0]?Buffer.concat([this[g0],e]):e)}[DRr](){if(this[M0e]&&!this[meo]&&!this[L0e]&&!this[Z2t]){this[meo]=!0;let e=this[jNe];if(e&&e.blockRemain){let t=this[g0]?this[g0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[g0]&&e.write(this[g0]),e.end()}this[MNe](RRr)}}[ORr](e){if(this[Z2t]&&e)this[geo](e);else if(!e&&!this[g0])this[DRr]();else if(e){if(this[Z2t]=!0,this[g0]){this[geo](e);let t=this[g0];this[g0]=void 0,this[PRr](t)}else this[PRr](e);for(;this[g0]&&this[g0]?.length>=512&&!this[L0e]&&!this[kRr];){let t=this[g0];this[g0]=void 0,this[PRr](t)}this[Z2t]=!1}(!this[g0]||this[M0e])&&this[DRr]()}[PRr](e){let t=0,r=e.length;for(;t+512<=r&&!this[L0e]&&!this[kRr];)switch(this[wU]){case"begin":case"header":this[cXa](e,t),t+=512;break;case"ignore":case"body":t+=this[heo](e,t);break;case"meta":t+=this[aXa](e,t);break;default:throw new Error("invalid state: "+this[wU])}t<r&&(this[g0]=this[g0]?Buffer.concat([e.subarray(t),this[g0]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[L0e]||(this[$C]?(e&&this[$C].write(e),this[$C].end()):(this[M0e]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[DRr]())),this}},aNt=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},ajf=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},GXa=(e,t)=>{let r=new Map(t.map(o=>[aNt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,eFr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,eFr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(aNt(o)):o=>i(aNt(o))},cjf=e=>{let t=new dNt(e),r=e.file,n;try{n=qNe.default.openSync(r,"r");let i=qNe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=qNe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=qNe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{qNe.default.closeSync(n)}catch{}}},ujf=(e,t)=>{let r=new dNt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),qNe.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new Keo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},nFr=gNt(cjf,ujf,e=>new dNt(e),e=>new dNt(e),(e,t)=>{t?.length&&GXa(e,t),e.noResume||ajf(e)}),WXa=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:ljf,parse:lXa}=$Xa.win32,eto=e=>{let t="",r=lXa(e);for(;ljf(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=lXa(e)}return[t,e]},iFr=["|","<",">","?",":"],tto=iFr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),pjf=new Map(iFr.map((e,t)=>[e,tto[t]])),fjf=new Map(tto.map((e,t)=>[e,iFr[t]])),pXa=e=>iFr.reduce((t,r)=>t.split(r).join(pjf.get(r)),e),djf=e=>tto.reduce((t,r)=>t.split(r).join(fjf.get(r)),e),HXa=(e,t)=>t?(e=Jp(e).replace(/^\.(\/|$)/,""),aNt(t)+"/"+e):Jp(e),mjf=16*1024*1024,fXa=Symbol("process"),dXa=Symbol("file"),mXa=Symbol("directory"),Peo=Symbol("symlink"),hXa=Symbol("hardlink"),eNt=Symbol("header"),LRr=Symbol("read"),Deo=Symbol("lstat"),URr=Symbol("onlstat"),Reo=Symbol("onread"),Feo=Symbol("onreadlink"),keo=Symbol("openfile"),Neo=Symbol("onopenfile"),q0e=Symbol("close"),JRr=Symbol("mode"),Qeo=Symbol("awaitDrain"),Aeo=Symbol("ondrain"),SY=Symbol("prefix"),KXa=class extends HNe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=Yeo(t);super(),this.path=Jp(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||mjf,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Jp(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Jp(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=eto(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=djf(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Jp(r.absolute||Oeo.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[URr](i):this[Deo]()}warn(e,t,r={}){return rFr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[Deo](){_7.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[URr](t)})}[URr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=Ajf(e),this.emit("stat",e),this[fXa]()}[fXa](){switch(this.type){case"File":return this[dXa]();case"Directory":return this[mXa]();case"SymbolicLink":return this[Peo]();default:return this.end()}}[JRr](e){return WXa(e,this.type==="Directory",this.portable)}[SY](e){return HXa(e,this.prefix)}[eNt](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new $Ne({path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,mode:this[JRr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new KRr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[mXa](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[eNt](),this.end()}[Peo](){_7.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Feo](t)})}[Feo](e){this.linkpath=Jp(e),this[eNt](),this.end()}[hXa](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Jp(Oeo.default.relative(this.cwd,e)),this.stat.size=0,this[eNt](),this.end()}[dXa](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[hXa](t);this.linkCache.set(e,this.absolute)}if(this[eNt](),this.stat.size===0)return this.end();this[keo]()}[keo](){_7.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Neo](t)})}[Neo](e){if(this.fd=e,this.#e)return this[q0e]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[LRr]()}[LRr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");_7.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[q0e](()=>this.emit("error",o));this[Reo](s)})}[q0e](e=()=>{}){this.fd!==void 0&&_7.default.close(this.fd,e)}[Reo](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[q0e](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[q0e](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[Aeo]():this[Qeo](()=>this[Aeo]())}[Qeo](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[Aeo](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[q0e](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[LRr]()}},hjf=class extends KXa{sync=!0;[Deo](){this[URr](_7.default.lstatSync(this.absolute))}[Peo](){this[Feo](_7.default.readlinkSync(this.absolute))}[keo](){this[Neo](_7.default.openSync(this.absolute,"r"))}[LRr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=_7.default.readSync(t,r,n,i,o);this[Reo](s),e=!1}finally{if(e)try{this[q0e](()=>{})}catch{}}}[Qeo](e){e()}[q0e](e=()=>{}){this.fd!==void 0&&_7.default.closeSync(this.fd),e()}},gjf=class extends HNe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return rFr(this,e,t,r)}constructor(e,t={}){let r=Yeo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Jp(e.path),this.mode=e.mode!==void 0?this[JRr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?Jp(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=eto(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new $Ne({path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new KRr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[SY](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[SY](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[SY](e){return HXa(e,this.prefix)}[JRr](e){return WXa(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},Ajf=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",yjf=class gXe{tail;head;length=0;static create(t=[]){return new gXe(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)Ejf(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)Ijf(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new gXe;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new gXe;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new gXe;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new gXe;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=bjf(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};function bjf(e,t,r){let n=t,i=t?t.next:e.head,o=new rto(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function Ejf(e,t){e.tail=new rto(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function Ijf(e,t){e.head=new rto(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var rto=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},gXa=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},AXa=Buffer.alloc(1024),zRr=Symbol("onStat"),tNt=Symbol("ended"),w7=Symbol("queue"),UNe=Symbol("current"),zNe=Symbol("process"),rNt=Symbol("processing"),yeo=Symbol("processJob"),S7=Symbol("jobs"),beo=Symbol("jobDone"),VRr=Symbol("addFSEntry"),yXa=Symbol("addTarEntry"),Meo=Symbol("stat"),Leo=Symbol("readdir"),qRr=Symbol("onreaddir"),GRr=Symbol("pipe"),bXa=Symbol("entry"),Eeo=Symbol("entryOpt"),WRr=Symbol("writeEntryClass"),JXa=Symbol("write"),Ieo=Symbol("ondrain"),oFr=class extends HNe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[WRr];onWriteEntry;[w7];[S7]=0;[rNt]=!1;[tNt]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Jp(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[WRr]=KXa,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new PQf(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new RQf(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new kQf(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[Ieo]()),this.on("resume",()=>t.resume())}else this.on("drain",this[Ieo]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[w7]=new yjf,this[S7]=0,this.jobs=Number(e.jobs)||4,this[rNt]=!1,this[tNt]=!1}[JXa](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[tNt]=!0,this[zNe](),r&&r(),this}write(e){if(this[tNt])throw new Error("write after end");return e instanceof qXa?this[yXa](e):this[VRr](e),this.flowing}[yXa](e){let t=Jp(jeo.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new gXa(e.path,t);r.entry=new gjf(e,this[Eeo](r)),r.entry.on("end",()=>this[beo](r)),this[S7]+=1,this[w7].push(r)}this[zNe]()}[VRr](e){let t=Jp(jeo.default.resolve(this.cwd,e));this[w7].push(new gXa(e,t)),this[zNe]()}[Meo](e){e.pending=!0,this[S7]+=1;let t=this.follow?"stat":"lstat";mNt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[S7]-=1,r?this.emit("error",r):this[zRr](e,n)})}[zRr](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)?t.isFile()&&t.nlink>1&&e===this[UNe]&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync&&this[yeo](e):e.ignore=!0,this[zNe]()}[Leo](e){e.pending=!0,this[S7]+=1,mNt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[S7]-=1,t)return this.emit("error",t);this[qRr](e,r)})}[qRr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[zNe]()}[zNe](){if(!this[rNt]){this[rNt]=!0;for(let e=this[w7].head;e&&this[S7]<this.jobs;e=e.next)if(this[yeo](e.value),e.value.ignore){let t=e.next;this[w7].removeNode(e),e.next=t}this[rNt]=!1,this[tNt]&&this[w7].length===0&&this[S7]===0&&(this.zip?this.zip.end(AXa):(super.write(AXa),super.end()))}}get[UNe](){return this[w7]&&this[w7].head&&this[w7].head.value}[beo](e){this[w7].shift(),this[S7]-=1,this[zNe]()}[yeo](e){if(!e.pending){if(e.entry){e===this[UNe]&&!e.piped&&this[GRr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[zRr](e,t):this[Meo](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[qRr](e,t):this[Leo](e),!e.readdir)return}if(e.entry=this[bXa](e),!e.entry){e.ignore=!0;return}e===this[UNe]&&!e.piped&&this[GRr](e)}}}[Eeo](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[bXa](e){this[S7]+=1;try{return new this[WRr](e.path,this[Eeo](e)).on("end",()=>this[beo](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[Ieo](){this[UNe]&&this[UNe].entry&&this[UNe].entry.resume()}[GRr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[VRr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){rFr(this,e,t,r)}},nto=class extends oFr{sync=!0;constructor(e){super(e),this[WRr]=hjf}pause(){}resume(){}[Meo](e){let t=this.follow?"statSync":"lstatSync";this[zRr](e,mNt.default[t](e.absolute))}[Leo](e){this[qRr](e,mNt.default.readdirSync(e.absolute))}[GRr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[VRr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[JXa](n)})}},vjf=(e,t)=>{let r=new nto(e),n=new FXa(e.file,{mode:e.mode||438});r.pipe(n),YXa(r,t)},Cjf=(e,t)=>{let r=new oFr(e),n=new ZRr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return XXa(r,t).catch(o=>r.emit("error",o)),i},YXa=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?nFr({file:Jeo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},XXa=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await nFr({file:Jeo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},xjf=(e,t)=>{let r=new nto(e);return YXa(r,t),r},wjf=(e,t)=>{let r=new oFr(e);return XXa(r,t).catch(n=>r.emit("error",n)),r},ZXa=gNt(vjf,Cjf,xjf,wjf,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),Sjf=process.env.__FAKE_PLATFORM__||process.platform,tZa=Sjf==="win32",{O_CREAT:rZa,O_NOFOLLOW:EXa,O_TRUNC:nZa,O_WRONLY:iZa}=sto.default.constants,oZa=Number(process.env.__FAKE_FS_O_FILENAME__)||sto.default.constants.UV_FS_O_FILEMAP||0,_jf=tZa&&!!oZa,Bjf=512*1024,Tjf=oZa|nZa|rZa|iZa,IXa=!tZa&&typeof EXa=="number"?EXa|nZa|rZa|iZa:null,sZa=IXa!==null?()=>IXa:_jf?e=>e<Bjf?Tjf:"w":()=>"w",Ueo=(e,t,r)=>{try{return ANt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},YRr=(e,t,r,n)=>{ANt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},Ojf=(e,t,r,n,i)=>{if(t.isDirectory())aZa(yXe.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=yXe.default.resolve(e,t.name);YRr(s,r,n,i)});else{let o=yXe.default.resolve(e,t.name);YRr(o,r,n,i)}},aZa=(e,t,r,n)=>{ANt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return YRr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return YRr(e,t,r,n)}};for(let u of o)Ojf(e,u,t,r,c)})},Pjf=(e,t,r,n)=>{t.isDirectory()&&cZa(yXe.default.resolve(e,t.name),r,n),Ueo(yXe.default.resolve(e,t.name),r,n)},cZa=(e,t,r)=>{let n;try{n=ANt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return Ueo(e,t,r);throw o}for(let i of n)Pjf(e,i,t,r);return Ueo(e,t,r)},lZa=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},sFr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},Djf=(e,t)=>{TN.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new lZa(e,r?.code||"ENOTDIR")),t(r)})},Rjf=(e,t,r)=>{e=Jp(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),u=t.preserve,l=t.unlink,p=Jp(t.cwd),d=(m,h)=>{m?r(m):h&&c?aZa(h,s,a,A=>d(A)):o?TN.default.chmod(e,i,r):r()};if(e===p)return Djf(e,d);if(u)return uZa.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Jp(hNt.default.relative(p,e)).split("/");zeo(p,f,i,l,p,void 0,d)},zeo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Jp(hNt.default.resolve(e+"/"+a));TN.default.mkdir(c,r,pZa(c,t,r,n,i,o,s))},pZa=(e,t,r,n,i,o,s)=>a=>{a?TN.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Jp(c.path),s(c);else if(u.isDirectory())zeo(e,t,r,n,i,o,s);else if(n)TN.default.unlink(e,l=>{if(l)return s(l);TN.default.mkdir(e,r,pZa(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new sFr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,zeo(e,t,r,n,i,o,s))},Fjf=e=>{let t=!1,r;try{t=TN.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new lZa(e,r??"ENOTDIR")}},kjf=(e,t)=>{e=Jp(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,u=t.unlink,l=Jp(t.cwd),p=m=>{m&&a&&cZa(m,o,s),i&&TN.default.chmodSync(e,n)};if(e===l)return Fjf(l),p();if(c)return p(TN.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Jp(hNt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),h=l;m&&(h+="/"+m);m=d.shift()){h=Jp(hNt.default.resolve(h));try{TN.default.mkdirSync(h,n),f=f||h}catch{let A=TN.default.lstatSync(h);if(A.isDirectory())continue;if(u){TN.default.unlinkSync(h),TN.default.mkdirSync(h,n),f=f||h;continue}else if(A.isSymbolicLink())return new sFr(h,h+"/"+d.join("/"))}}return p(f)},veo=Object.create(null),vXa=1e4,pXe=new Set,Njf=e=>{pXe.has(e)?pXe.delete(e):veo[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),pXe.add(e);let t=veo[e],r=pXe.size-vXa;if(r>vXa/10){for(let n of pXe)if(pXe.delete(n),delete veo[n],--r<=0)break}return t},Qjf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,jjf=Qjf==="win32",Mjf=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,ato.join)(n,r)),t.push(r||"/"),t},[]),Ljf=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=jjf?["win32 parallelization disabled"]:e.map(n=>aNt((0,ato.join)(Njf(n))));let r=new Set(e.map(n=>Mjf(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},Ujf=()=>process.umask(),CXa=Symbol("onEntry"),Veo=Symbol("checkFs"),xXa=Symbol("checkFs2"),qeo=Symbol("isReusable"),SU=Symbol("makeFs"),Geo=Symbol("file"),Weo=Symbol("directory"),$Rr=Symbol("link"),wXa=Symbol("symlink"),SXa=Symbol("hardlink"),oNt=Symbol("ensureNoSymlink"),_Xa=Symbol("unsupported"),BXa=Symbol("checkPath"),Ceo=Symbol("stripAbsolutePath"),W0e=Symbol("mkdir"),u_=Symbol("onError"),NRr=Symbol("pending"),TXa=Symbol("pend"),fXe=Symbol("unpend"),xeo=Symbol("ended"),weo=Symbol("maybeClose"),$eo=Symbol("skip"),cNt=Symbol("doChown"),uNt=Symbol("uid"),lNt=Symbol("gid"),pNt=Symbol("checkedCwd"),zjf=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,fNt=zjf==="win32",Vjf=1024,qjf=(e,t)=>{if(!fNt)return td.default.unlink(e,t);let r=e+".DELETE."+(0,oto.randomBytes)(16).toString("hex");td.default.rename(e,r,n=>{if(n)return t(n);td.default.unlink(r,t)})},Gjf=e=>{if(!fNt)return td.default.unlinkSync(e);let t=e+".DELETE."+(0,oto.randomBytes)(16).toString("hex");td.default.renameSync(e,t),td.default.unlinkSync(t)},OXa=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,cto=class extends dNt{[xeo]=!1;[pNt]=!1;[NRr]=0;reservations=new Ljf;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[xeo]=!0,this[weo]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:Vjf,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||fNt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Jp(HC.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:Ujf():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[CXa](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[weo](){this[xeo]&&this[NRr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ceo](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=eto(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||fNt&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=HC.default.posix.dirname(e.path),c=HC.default.posix.normalize(HC.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[BXa](e){let t=Jp(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Jp(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[Ceo](e,"path")||!this[Ceo](e,"linkpath"))return!1;if(e.absolute=HC.default.isAbsolute(e.path)?Jp(HC.default.resolve(e.path)):Jp(HC.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:Jp(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=HC.default.win32.parse(String(e.absolute));e.absolute=n+pXa(String(e.absolute).slice(n.length));let{root:i}=HC.default.win32.parse(e.path);e.path=i+pXa(e.path.slice(i.length))}return!0}[CXa](e){if(!this[BXa](e))return e.resume();switch(eZa.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Veo](e);default:return this[_Xa](e)}}[u_](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[fXe](),t.resume())}[W0e](e,t,r){Rjf(Jp(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[cNt](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[uNt](e){return OXa(this.uid,e.uid,this.processUid)}[lNt](e){return OXa(this.gid,e.gid,this.processGid)}[Geo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new ZRr(String(e.absolute),{flags:sZa(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&td.default.close(n.fd,()=>{}),n.write=()=>!0,this[u_](a,e),t()});let i=1,o=a=>{if(a){n.fd&&td.default.close(n.fd,()=>{}),this[u_](a,e),t();return}--i===0&&n.fd!==void 0&&td.default.close(n.fd,c=>{c?this[u_](c,e):this[fXe](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;td.default.futimes(c,u,l,p=>p?td.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[cNt](e)){i++;let u=this[uNt](e),l=this[lNt](e);typeof u=="number"&&typeof l=="number"&&td.default.fchown(c,u,l,p=>p?td.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[u_](a,e),t()}),e.pipe(s)),s.pipe(n)}[Weo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[W0e](String(e.absolute),r,n=>{if(n){this[u_](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[fXe](),e.resume())};e.mtime&&!this.noMtime&&(i++,td.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[cNt](e)&&(i++,td.default.chown(String(e.absolute),Number(this[uNt](e)),Number(this[lNt](e)),o)),o()})}[_Xa](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[wXa](e,t){let r=Jp(HC.default.relative(this.cwd,HC.default.resolve(HC.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[oNt](e,this.cwd,r,()=>this[$Rr](e,String(e.linkpath),"symlink",t),n=>{this[u_](n,e),t()})}[SXa](e,t){let r=Jp(HC.default.resolve(this.cwd,String(e.linkpath))),n=Jp(String(e.linkpath)).split("/");this[oNt](e,this.cwd,n,()=>this[$Rr](e,r,"link",t),i=>{this[u_](i,e),t()})}[oNt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=HC.default.resolve(t,o);td.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new sFr(s,HC.default.resolve(s,r.join("/"))));this[oNt](e,s,r,n,i)})}[TXa](){this[NRr]++}[fXe](){this[NRr]--,this[weo]()}[$eo](e){this[fXe](),e.resume()}[qeo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!fNt}[Veo](e){this[TXa]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[xXa](e,r))}[xXa](e,t){let r=s=>{t(s)},n=()=>{this[W0e](this.cwd,this.dmode,s=>{if(s){this[u_](s,e),r();return}this[pNt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Jp(HC.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[W0e](s,this.dmode,a=>{if(a){this[u_](a,e),r();return}o()})}o()},o=()=>{td.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[$eo](e),r();return}if(s||this[qeo](e,a))return this[SU](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[SU](l??null,e,r);return c?td.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return td.default.rmdir(String(e.absolute),c=>this[SU](c??null,e,r))}if(e.absolute===this.cwd)return this[SU](null,e,r);qjf(String(e.absolute),c=>this[SU](c??null,e,r))})};this[pNt]?i():n()}[SU](e,t,r){if(e){this[u_](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[Geo](t,r);case"Link":return this[SXa](t,r);case"SymbolicLink":return this[wXa](t,r);case"Directory":case"GNUDumpDir":return this[Weo](t,r)}}[$Rr](e,t,r,n){td.default[r](t,String(e.absolute),i=>{i?this[u_](i,e):(this[fXe](),e.resume()),n()})}},nNt=e=>{try{return[null,e()]}catch(t){return[t,null]}},fZa=class extends cto{sync=!0;[SU](e,t){return super[SU](e,t,()=>{})}[Veo](e){if(!this[pNt]){let i=this[W0e](this.cwd,this.dmode);if(i)return this[u_](i,e);this[pNt]=!0}if(e.absolute!==this.cwd){let i=Jp(HC.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[W0e](i,this.dmode);if(o)return this[u_](o,e)}}let[t,r]=nNt(()=>td.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[$eo](e);if(t||this[qeo](e,r))return this[SU](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?nNt(()=>{td.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[SU](s,e)}let[i]=nNt(()=>td.default.rmdirSync(String(e.absolute)));this[SU](i,e)}let[n]=e.absolute===this.cwd?[]:nNt(()=>Gjf(String(e.absolute)));this[SU](n,e)}[Geo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{td.default.closeSync(i)}catch(c){a=c}(s||a)&&this[u_](s||a,e),t()},i;try{i=td.default.openSync(String(e.absolute),sZa(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[u_](s,e)),e.pipe(o)),o.on("data",s=>{try{td.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{td.default.futimesSync(i,a,c)}catch(u){try{td.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[cNt](e)){let a=this[uNt](e),c=this[lNt](e);try{td.default.fchownSync(i,Number(a),Number(c))}catch(u){try{td.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[Weo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[W0e](String(e.absolute),r);if(n){this[u_](n,e),t();return}if(e.mtime&&!this.noMtime)try{td.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[cNt](e))try{td.default.chownSync(String(e.absolute),Number(this[uNt](e)),Number(this[lNt](e)))}catch{}t(),e.resume()}[W0e](e,t){try{return kjf(Jp(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[oNt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=HC.default.resolve(o,s);let[a,c]=nNt(()=>td.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new sFr(o,HC.default.resolve(t,r.join("/"))))}n()}[$Rr](e,t,r,n){let i=`${r}Sync`;try{td.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[u_](o,e)}}},Wjf=e=>{let t=new fZa(e),r=e.file,n=ito.default.statSync(r),i=e.maxReadSize||16*1024*1024;new EQf(r,{readSize:i,size:n.size}).pipe(t)},$jf=(e,t)=>{let r=new cto(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),ito.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new Keo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},dZa=gNt(Wjf,$jf,e=>new fZa(e),e=>new cto(e),(e,t)=>{t?.length&&GXa(e,t)}),Hjf=(e,t)=>{let r=new nto(e),n=!0,i,o;try{try{i=BN.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=BN.default.openSync(e.file,"w+");else throw c}let s=BN.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=BN.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new $Ne(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,Kjf(e,r,o,i,t)}finally{if(n)try{BN.default.closeSync(i)}catch{}}},Kjf=(e,t,r,n,i)=>{let o=new FXa(e.file,{fd:n,start:r});t.pipe(o),Yjf(t,i)},Jjf=(e,t)=>{t=Array.from(t);let r=new oFr(e),n=(i,o,s)=>{let a=(d,f)=>{d?BN.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return BN.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new $Ne(l);if(!m.cksumValid)return a(null,c);let h=512*Math.ceil((m.size??0)/512);if(c+h+512>o||(c+=h+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),u=0,BN.default.read(i,l,0,512,c,p)};BN.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",BN.default.open(e.file,s,a);if(c||!u)return o(c);BN.default.fstat(u,(l,p)=>{if(l)return BN.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new ZRr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),Xjf(r,t)})})};BN.default.open(e.file,s,a)})},Yjf=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?nFr({file:uto.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},Xjf=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await nFr({file:uto.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},iNt=gNt(Hjf,Jjf,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!SQf(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),hG0=gNt(iNt.syncFile,iNt.asyncFile,iNt.syncNoFile,iNt.asyncNoFile,(e,t=[])=>{iNt.validate?.(e,t),Zjf(e)}),Zjf=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))};var bZa=Ie(nS(),1);var eMf=tue();async function EZa({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:n,cliVersion:i,settings:o,loadAPIWorkspace:s}){let a,c={type:Ol.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},u=t.dependencies[e];return u==null?c={type:Ol.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${aMf(u)}`},async l=>{switch(u.type){case"version":a=await oMf({context:l,dependency:u,cliVersion:i,settings:o,loadAPIWorkspace:s});return;case"local":a=await iMf({context:l,dependency:u,cliVersion:i,settings:o,loadAPIWorkspace:s});return;default:Ce(u)}}),a!=null?{didSucceed:!0,definition:a}:{didSucceed:!1,failure:c}}var IZa="dependencies";var tMf="metadata.json",rMf=".fern";function nMf(e){return $e($t.of((0,gZa.homedir)()),Te.of(rMf),Te.of(IZa),Te.of(e.organization),Te.of(e.apiName),Te.of(e.version))}async function iMf({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){if(i==null){t.failWithoutThrowing("Failed to load api definition",void 0,{code:j.Code.ResolutionError});return}t.logger.info("Parsing...");let o=await i({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!o.didSucceed){t.failWithoutThrowing("Failed to load api definition",o.failures,{code:j.Code.ResolutionError});return}t.logger.info("Modifying source filepath ...");let s=await o.workspace.getDefinition({context:t,relativePathToDependency:Te.of(e.path)},n);return t.logger.info("Loaded..."),s}async function oMf({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){let o=nMf(e),s=$e(o,Te.of(IZa)),a=$e(o,Te.of(tMf)),c;if(!await cr(s)||!await cr(a)){t.logger.info("Downloading manifest...");let p=await eMf.definitionRegistry.get(zr.OrganizationId(e.organization),zr.ApiId(e.apiName),e.version);if(!p.ok){p.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist",void 0,{code:j.Code.ResolutionError})},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist",void 0,{code:j.Code.ResolutionError})},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist",void 0,{code:j.Code.ResolutionError})},_other:h=>{t.failWithoutThrowing("Failed to download API manifest",h,{code:j.Code.NetworkError})}});return}let d=p.body.yamlSchemaVersion!=null?parseInt(p.body.yamlSchemaVersion):void 0,f=SNe(r),m=SNe(p.body.cliVersion);if(d!=null){if(d>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${p.body.cliVersion}`,void 0,{code:j.Code.VersionError});return}else if(d<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`,void 0,{code:j.Code.VersionError});return}}else if(f.major!==m.major||f.minor!==m.minor){t.failWithoutThrowing(`CLI version is ${p.body.cliVersion}. Expected ${f.major}.${f.minor}.x (to match current workspace).`,void 0,{code:j.Code.VersionError});return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+p.body.definitionS3DownloadUrl),await(0,EXe.mkdir)(s,{recursive:!0});try{await sMf({s3PreSignedReadUrl:p.body.definitionS3DownloadUrl,absolutePathToLocalOutput:s})}catch(h){t.failWithoutThrowing("Failed to download API",h,{code:j.Code.NetworkError});return}c=p.body,await(0,EXe.writeFile)(a,JSON.stringify(c))}else c=JSON.parse((await(0,EXe.readFile)(a)).toString());if(t.logger.info("Parsing..."),i==null){t.failWithoutThrowing("Failed to load API",void 0,{code:j.Code.ResolutionError});return}let u=await i({absolutePathToWorkspace:s,context:t,cliVersion:c.cliVersion,workspaceName:void 0});if(!u.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",u.failures,{code:j.Code.ParseError});return}if(u.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.",void 0,{code:j.Code.ConfigError});return}return await u.workspace.getDefinition({context:t},n)}async function sMf({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await ly.get(e,{responseType:"stream"}),n=await bZa.default.dir(),i=AZa.default.join(n.path,"api.tgz");await(0,yZa.pipeline)(r.data,(0,hZa.createWriteStream)(i)),await dZa({file:i,cwd:t})}function aMf(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Ce(e)}}async function vZa({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:n,settings:i,loadAPIWorkspace:o}){let s={},a={},c={};return await Promise.all(L0(t.packageMarkers).map(async([u,l])=>{if(l.contents.export==null)s[u]=l;else{let{export:p,...d}=l.contents;if(ih(d)>0)c[u]={type:Ol.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:u};else{let f=xn(u);if(jT(t.namedDefinitionFiles).some(h=>h!==u&&h.startsWith(f)))c[u]={type:Ol.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:f};else{let h=await EZa({dependencyName:typeof l.contents.export=="string"?l.contents.export:l.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:n,settings:i,loadAPIWorkspace:o});h.didSucceed?a[xn(u)]={definition:h.definition,url:typeof l.contents.export=="object"?l.contents.export.url:void 0}:c[u]=h.failure}}}})),ih(c)>0?{didSucceed:!1,failures:c}:{didSucceed:!0,packageMarkers:s,importedDefinitions:a}}Rt();Jt();var CZa=Ie(require("path"),1);var lto={};ee(lto,{additionalProperties:()=>pMf,default:()=>dMf,definitions:()=>fMf,properties:()=>uMf,required:()=>lMf,type:()=>cMf});var cMf="object",uMf={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},lMf=["name"],pMf=!1,fMf={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}},"url-templates":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"default-urls":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}}},{type:"null"}]}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},dMf={type:cMf,properties:uMf,required:lMf,additionalProperties:pMf,definitions:fMf};var pto={};ee(pto,{additionalProperties:()=>gMf,default:()=>yMf,definitions:()=>AMf,properties:()=>hMf,type:()=>mMf});var mMf="object",hMf={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},gMf=!1,AMf={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadBodySortSchema":{type:"string",enum:["alphabetical"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]},"body-sort":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadBodySortSchema"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},yMf={type:mMf,properties:hMf,additionalProperties:gMf,definitions:AMf};var fto={};ee(fto,{additionalProperties:()=>IMf,default:()=>CMf,definitions:()=>vMf,properties:()=>EMf,type:()=>bMf});var bMf="object",EMf={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},IMf=!1,vMf={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadBodySortSchema":{type:"string",enum:["alphabetical"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]},"body-sort":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadBodySortSchema"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},CMf={type:bMf,properties:EMf,additionalProperties:IMf,definitions:vMf};var dto=new Map,mto=new Map,hto=new Map;function xZa({files:e,absolutePathToDefinition:t,skipValidation:r}){let n,i={},o={},s={};for(let[a,c]of L0(e)){let u=c.contents,l=p=>{s[a]={type:Ol.JSONSCHEMA_VALIDATION,error:p}};if(a===eI){let p=dto.get(c.rawContents);if(p!=null&&(p.validated||r))n={defaultUrl:p.value["default-url"],contents:p.value,rawContents:c.rawContents};else if(r){let d=oh.serialization.RootApiFileSchema.parseOrThrow(u);dto.set(c.rawContents,{value:d,validated:!1}),n={defaultUrl:d["default-url"],contents:d,rawContents:c.rawContents}}else{let d=Q3(u,lto);if(d.success){let f=oh.serialization.RootApiFileSchema.parseOrThrow(u);dto.set(c.rawContents,{value:f,validated:!0}),n={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else l(d)}}else if(CZa.default.basename(a)===kf){let p=hto.get(c.rawContents);if(p!=null&&(p.validated||r))o[a]={defaultUrl:typeof p.value.export=="object"?p.value.export.url:void 0,contents:p.value,rawContents:c.rawContents};else if(r){let d=oh.serialization.PackageMarkerFileSchema.parseOrThrow(u);hto.set(c.rawContents,{value:d,validated:!1}),o[a]={defaultUrl:typeof d.export=="object"?d.export.url:void 0,contents:d,rawContents:c.rawContents}}else{let d=Q3(u,fto);if(d.success){let f=oh.serialization.PackageMarkerFileSchema.parseOrThrow(u);hto.set(c.rawContents,{value:f,validated:!0}),o[a]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else l(d)}}else{let p=mto.get(c.rawContents);if(p!=null&&(p.validated||r))i[a]={defaultUrl:void 0,contents:p.value,rawContents:c.rawContents,absoluteFilePath:$e(t,a)};else if(r){let d=oh.serialization.DefinitionFileSchema.parseOrThrow(u);mto.set(c.rawContents,{value:d,validated:!1}),i[a]={defaultUrl:void 0,contents:d,rawContents:c.rawContents,absoluteFilePath:$e(t,a)}}else{let d=Q3(u,pto);if(d.success){let f=oh.serialization.DefinitionFileSchema.parseOrThrow(u);mto.set(c.rawContents,{value:f,validated:!0}),i[a]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:$e(t,a)}}else l(d)}}}return n==null?{didSucceed:!1,failures:{[Te.of(eI)]:{type:Ol.FILE_MISSING},...s}}:Object.keys(s).length>0?{didSucceed:!1,failures:s}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:n,packageMarkers:o}}var ZO=class extends uG{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...n}){super(n),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){let n=t||this.context;return(await this.toFernWorkspace({context:n},r)).definition}async toFernWorkspace({context:t,skipValidation:r},n,i,o){let s=(0,wZa.default)(n??{}),a=this.fernWorkspaces[s];if(a==null){let c=t||this.context,u=$e(this.absoluteFilePath,Te.of(wA)),l=await E2i({absolutePathToWorkspace:this.absoluteFilePath,context:c}),p=await HHa(u,"{yml,yaml}"),d=await KHa(p);if(!d.didSucceed)return RDr(d.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let f=xZa({files:d.files,absolutePathToDefinition:u,skipValidation:r});if(!f.didSucceed)return RDr(f.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let m=await vZa({dependenciesConfiguration:l,structuralValidationResult:f,context:c,cliVersion:this.cliVersion,settings:n,loadAPIWorkspace:this.loadAPIWorkspace});if(!m.didSucceed)return RDr(m.failures,c.logger),c.failAndThrow(void 0,void 0,{code:j.Code.ValidationError});let h={absoluteFilePath:u,rootApiFile:f.rootApiFile,namedDefinitionFiles:f.namedDefinitionFiles,packageMarkers:m.packageMarkers,importedDefinitions:m.importedDefinitions};n?.auth!=null&&(h={...h,rootApiFile:{...h.rootApiFile,contents:{...h.rootApiFile.contents,auth:n?.auth}}}),a=new F2({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:h,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[s]=a}return a}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};Jt();var tic=require("fs/promises");var Qnc=Ie(Nnc(),1);async function uF(e){return(await(0,Qnc.convertObj)(e,{})).openapi}var Hnc=require("fs/promises");var Knc=require("path");Rt();var jnc=require("fs/promises");async function MXe({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,jnc.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Tr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:j.Code.ParseError})}return P$({data:t,overrides:i,allowNullKeys:n})}var qnc=require("fs/promises");var fQt=require("path");function Gnc(e){return e.startsWith("http://")||e.startsWith("https://")}async function Mnc(e,t){let r=t.get(e);if(r!==void 0)return r;let n=await(0,qnc.readFile)(e,"utf-8"),i=Tr.load(n);return t.set(e,i),i}function Wnc(e,t){let r=new Map;if(e==null||typeof e!="object"||Array.isArray(e))return r;let n=e;function i(s,a){if(!(s==null||typeof s!="object"||Array.isArray(s)))for(let[c,u]of Object.entries(s)){if(!Mzf(u))continue;let l=u.$ref,{jsonPointer:p,absolutePath:d}=$nc(l,t);r.set(`${d}#${p}`,`${a}/${c}`)}}i(n.channels,"#/channels"),i(n.operations,"#/operations");let o=n.components;if(o!=null&&typeof o=="object"&&!Array.isArray(o)){let s=o;i(s.schemas,"#/components/schemas"),i(s.messages,"#/components/messages"),i(s.parameters,"#/components/parameters")}return r}function $nc(e,t){let r=e.indexOf("#"),n=r>=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"",o=(0,fQt.resolve)(t,n);return{filePath:n,jsonPointer:i,absolutePath:o}}function Mzf(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e.$ref;return typeof t=="string"&&t.length>0&&!t.startsWith("#")&&!Gnc(t)}function Lnc(e){let t={},r=!1;for(let[n,i]of Object.entries(e))n!=="$ref"&&(t[n]=i,r=!0);return{siblingProperties:t,hasSiblings:r}}function Unc(e,t,r){if(t==="")return e;let n=t.split("/").filter(o=>o!==""),i=e;for(let o of n){let s=o.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof i!="object"||i==null)throw new Error(`Cannot navigate JSON Pointer "${t}" in "${r}": expected an object but found ${typeof i} at key "${s}"`);let a=i[s];if(a===void 0)throw new Error(`Cannot navigate JSON Pointer "${t}" in "${r}": key "${s}" not found`);i=a}return i}function znc(e,t,r){return r&&e!=null&&typeof e=="object"&&!Array.isArray(e)?{...e,...t}:e}function Vnc(e,t,r,n){if(e===r)return"#"+t;let i=`${e}#${t}`,o=n.get(i);if(o!==void 0)return o;for(let[s,a]of n){let c=s.indexOf("#"),u=s.slice(0,c),l=s.slice(c+1);if(u===e&&t.startsWith(l+"/")){let p=t.slice(l.length);return a+p}}return null}async function LXe(e,t,r,n,i=!1,o=new Set,s=new Map,a){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return Promise.all(e.map(p=>LXe(p,t,r,n,i,o,s,a)));let c=e,u=c.$ref;if(typeof u=="string"&&u.startsWith("#")&&a!=null){let p=u.substring(1),{siblingProperties:d,hasSiblings:f}=Lnc(c),m=Vnc(a,p,r,n);if(m!==null)return f?{$ref:m,...d}:{$ref:m};let h=`${a}#${p}`;if(o.has(h))throw new Error(`Circular $ref detected: "${u}" (resolved to "${h}")`);let A=new Set(o);A.add(h);let b=await Mnc(a,s),v=Unc(b,p,a),x=(0,fQt.dirname)(a),C=await LXe(v,x,r,n,!0,A,s,a);return znc(C,d,f)}if(typeof u=="string"&&!u.startsWith("#")&&!Gnc(u)){let{jsonPointer:p,absolutePath:d}=$nc(u,t),{siblingProperties:f,hasSiblings:m}=Lnc(c);if(i){let w=Vnc(d,p,r,n);if(w!==null)return{$ref:w,...f}}let h=`${d}#${p}`;if(o.has(h))throw new j({message:`Circular $ref detected: "${u}" (resolved to "${h}")`,code:j.Code.ReferenceError});let A=new Set(o);A.add(h);let b=await Mnc(d,s),v=Unc(b,p,d),x=(0,fQt.dirname)(d),C=await LXe(v,x,r,n,!0,A,s,d);return znc(C,f,m)}let l={};for(let[p,d]of Object.entries(c))l[p]=await LXe(d,t,r,n,i,o,s,a);return l}async function yno({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,Hnc.readFile)(t)).toString(),i=await Tr.load(n),o=(0,Knc.dirname)(t),s=Wnc(i,o),a=await LXe(i,o,t,s),c=[];r!=null&&(Array.isArray(r)?c=r:c=[r]);let u=a;for(let l of c)u=await MXe({absoluteFilePathToOverrides:l,context:e,data:u});return u}Jt();var Ino=require("fs/promises");Rt();var Ekr=require("fs/promises");var bkr=Ie(require("path"),1),Jnc=Ie(nS(),1),bno;async function Lzf(){return bno===void 0&&(bno=(await Jnc.default.dir({prefix:"fern-overlay-"})).path),bno}async function Ync({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:n}){let i=await Uzf(e,n);if(!zzf(i,n))return r;n.logger.debug(`Applying overlay "${i.info.title}" v${i.info.version}`);let o=cqe({data:r,overlay:i}),s=await Lzf(),a=bkr.default.basename(t),c=`${bkr.default.parse(a).name}.overlaid.json`,u=bkr.default.join(s,c);return await(0,Ekr.writeFile)(u,JSON.stringify(o,null,2),"utf8"),n.logger.debug(`Wrote overlaid OpenAPI spec to: ${u}`),o}async function Uzf(e,t){let r;try{r=await(0,Ekr.readFile)(e,"utf8")}catch(n){return t.failAndThrow(`Failed to read overlay file at ${e}: ${n}`,void 0,{code:j.Code.ConfigError})}try{try{return JSON.parse(r)}catch{return Tr.load(r,{json:!0})}}catch(n){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${n}`,void 0,{code:j.Code.ParseError})}}function zzf(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let n=e.actions[r];if(!n?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(n.update===void 0&&!n.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var hQt=Ie(Yvr(),1);Jt();var Xnc=Ie(Yvr(),1),dQt=Ie(require("path"),1),mQt=class extends Xnc.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let n=super.resolveExternalRef(t,r);if(n.startsWith("http://")||n.startsWith("https://")||Q$($t.of(n)))return n;if(this.absolutePathToOpenAPIOverlays!=null){let i=dQt.default.resolve(dQt.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(Q$($t.of(i)))return i}return this.absolutePathToOpenAPIOverrides!=null?dQt.default.resolve(dQt.default.dirname(this.absolutePathToOpenAPIOverrides),r):n}};async function Ikr({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:n}){return(n!=null?await(0,hQt.bundle)({...Xvr,doc:{source:new hQt.Source(e,"<openapi>"),parsed:n},externalRefResolver:new mQt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,hQt.bundle)({...Xvr,ref:e,externalRefResolver:new mQt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}Rt();var Znc=require("fs/promises"),eic=require("path");async function Eno(e,t,r){await vkr(e,t,r,"",void 0)}var Vzf=new Set(["properties","patternProperties"]);async function vkr(e,t,r,n,i){if(Array.isArray(e)){await Promise.all(e.map((o,s)=>vkr(o,t,r,`${n}[${s}]`,i)));return}if(fa(e))for(let[o,s]of Object.entries(e)){let a=n===""?o:`${n}.${o}`;if(o==="description"&&!(i!=null&&Vzf.has(i))){if(typeof s=="string"||s==null)continue;if(qzf(s)){e[o]=await $zf(s.$ref,t,r,a);continue}if(Gzf(s)){r.logger.warn(`OpenAPI description at "${a}" is a \`$ref\` object we can't resolve (${Wzf(s)}). Descriptions must be plain strings, and we only inline relative \`.md\` file refs. Coercing to empty string so generation can continue.`),e[o]="";continue}await vkr(s,t,r,a,o)}else await vkr(s,t,r,a,o)}}function qzf(e){if(!fa(e))return!1;let t=Object.keys(e);if(t.length!==1||t[0]!=="$ref")return!1;let r=e.$ref;return typeof r!="string"||r.length===0||r.startsWith("#")||r.startsWith("http://")||r.startsWith("https://")?!1:r.toLowerCase().endsWith(".md")}function Gzf(e){return fa(e)&&typeof e.$ref=="string"&&e.$ref.length>0}function Wzf(e){let t=e.$ref,r=Object.keys(e).filter(i=>i!=="$ref"),n=r.length>0?`, sibling keys: ${r.map(i=>`"${i}"`).join(", ")}`:"";return`target="${t}"${n}`}async function $zf(e,t,r,n){let i=(0,eic.resolve)(t,e);try{return(await(0,Znc.readFile)(i,"utf-8")).trimEnd()}catch(o){return r.logger.warn(`Failed to resolve markdown description $ref at "${n}" \u2192 "${e}" (${i}): ${o instanceof Error?o.message:String(o)}. Coercing to empty string so generation can continue.`),""}}function Hzf(e,t){if(t.includes(e))return e;for(let r of t){let n=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${n}$`).test(e))return r}}var Kzf=["examples","example",Bn.EXAMPLES,cB.REDOCLY_CODE_SAMPLES_CAMEL,cB.REDOCLY_CODE_SAMPLES_KEBAB];async function gQt({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:n,loadAiExamples:i=!1}){let o=await(0,Ino.readFile)(t,"utf-8"),s=Tr.load(o);await Eno(s,xn(t),e);let a=await Ikr({absolutePathToOpenAPI:t,parsed:s}),c=[];r!=null?Array.isArray(r)?c=r:c=[r]:typeof a=="object"&&a[Bn.OPENAPI_OVERIDES_FILEPATH]!=null&&(c=[$e(xn(t),Te.of(a[Bn.OPENAPI_OVERIDES_FILEPATH]))]);let u=a;for(let p of c)u=await MXe({absoluteFilePathToOverrides:p,context:e,data:u,allowNullKeys:Kzf}),await Eno(u,xn(p),e),u=await Ikr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:p,parsed:u});if(n!=null&&(u=await Ync({absoluteFilePathToOverlay:n,absoluteFilePathToOpenAPI:t,context:e,data:u})),i){let p=$e(xn(t),Te.of("ai_examples_override.yml"));try{let d=await(0,Ino.readFile)(p,"utf-8"),f=Tr.load(d);if(f?.paths&&u.paths){for(let[m,h]of Object.entries(f.paths))if(h&&typeof h=="object")for(let[A,b]of Object.entries(h)){let v=A.toLowerCase(),x=u.paths[m];if(!x&&u.paths){let C=Hzf(m,Object.keys(u.paths));C&&(x=u.paths[C],e.logger.debug(`Matched override path "${m}" to OpenAPI path "${C}" using pattern matching`))}if(x&&typeof x=="object"){let w=x[v];if(w&&typeof w=="object"){let B=w;!B["x-fern-examples"]&&b["x-fern-examples"]&&(B["x-fern-examples"]=b["x-fern-examples"],e.logger.debug(`Added AI examples for ${A.toUpperCase()} ${m} from override file`))}}}}e.logger.debug(`Processed AI examples from ${p}`)}catch{}}return u!==a&&c.length===0||n!=null?await Ikr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverlays:n,parsed:u}):u}var R7=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:n=!1}){return(await Promise.all(r.map(o=>this.loadDocument({context:t,spec:o,loadAiExamples:n})))).filter(o=>o!=null)}async loadDocument({context:t,spec:r,loadAiExamples:n}){try{let i=(await(0,tic.readFile)(r.absoluteFilepath)).toString(),o=$s(this.absoluteFilePath,r.source.file);r.source.relativePathToDependency!=null&&(o=$e(r.source.relativePathToDependency,o));let s=r.source.type==="protobuf"?lO.protobuf({file:o}):lO.openapi({file:o});if(i.includes("openapi")||i.includes("swagger"))try{let a=await gQt({absolutePathToOpenAPI:r.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:r.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:r.absoluteFilepathToOverlays,loadAiExamples:n});if(b2i(a))return{type:"openapi",value:a,source:s,namespace:r.namespace,settings:C4({options:r.settings})};if(UR(a))return(!a.schemes||a.schemes.length===0)&&(a.schemes=["https"]),{type:"openapi",value:await uF(a),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.debug(`Failed to parse OpenAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("asyncapi"))try{return{type:"asyncapi",value:await yno({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.error(`Failed to parse AsyncAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("openrpc"))try{return{type:"asyncapi",value:await yno({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:C4({options:r.settings})}}catch(a){t.logger.error(`Failed to parse OpenRPC document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}t.logger.warn(`${r.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`);return}catch(i){t.logger.error(`Failed to read or process file ${r.absoluteFilepath}: ${i}. Skipping...`);return}}};var oo=class e{breadcrumbs=[];context;static STRING=Yt.TypeReference.primitive({v1:"STRING",v2:Yt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Yt.TypeReference.container(Yt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};Wi();Jt();var nic=require("fs/promises");var vno=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},ric=vno;var ub;(function(e){e.WARNING="warning",e.ERROR="error"})(ub||(ub={}));var TU=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new Cno({logger:t,relativePathToFile:Te.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||ub.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===ub.ERROR?t++:(n.level===ub.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??ub.WARNING;if(!(n===ub.WARNING&&!t))switch(n){case ub.ERROR:if(this.logger.log(Xn.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Xn.Debug,` - at location (${o})`)}break;case ub.WARNING:if(this.logger.log(Xn.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Xn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Xn.Warn,` - resolution: ${r.resolution}`);break}}}},Cno=class{logger;relativePathToFile;map=new ric;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,nic.readFile)(this.relativePathToFile,"utf-8");Tr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Xn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var A0=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=sw({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((i,o)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||o===0&&i==="components"||o===1&&i==="schemas"||t[0]==="paths"&&(o===0||o===1&&["get","post","put","delete","patch"].includes(i)||o===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=Wn(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:ub.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:ub.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};s=l;let p=await fetch(l);if(!p.ok)return{resolved:!1};try{let d=await p.text();try{o=JSON.parse(d),r=o}catch{o=Tr.load(d),r=o}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,u=s.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return Yt.ObjectPropertyAccess.ReadOnly;if(i)return Yt.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new uw.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}let i=new uw.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:vC.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var qa=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}};Wi();var uw={};ee(uw,{AudienceExtension:()=>UXe,FernAvailabilityExtension:()=>Ckr,FernDiscriminatorContextExtension:()=>zXe,FernEnumExtension:()=>VXe,FernIgnoreExtension:()=>aQe,FernOptionalExtension:()=>xkr,FernTypeExtension:()=>Bkr,FernTypeNameExtension:()=>Tkr,SdkGroupNameExtension:()=>wkr,SdkMethodNameExtension:()=>Skr,ServerFromOperationNameExtension:()=>_kr});var UXe=class extends qa{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var Ckr=class extends qa{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return vC.InDevelopment;case"PRE_RELEASE":case"BETA":return vC.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return vC.GeneralAvailability;case"DEPRECATED":return vC.Deprecated;default:return}}};var zXe=class extends qa{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}};ts();var Jzf=It.object({snake:It.string().optional(),camel:It.string().optional(),screamingSnake:It.string().optional(),pascal:It.string().optional()}),Yzf=It.object({description:It.string().optional(),name:It.string().optional(),casing:Jzf.optional()}),iic=It.record(Yzf);var VXe=class extends qa{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=iic.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var aQe=class extends qa{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var xkr=class extends qa{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var wkr=class extends qa{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var Skr=class extends qa{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var _kr=class extends qa{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var Bkr=class extends qa{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var Tkr=class extends qa{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var F7=class extends oo{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new eNe(n),this.ir={auth:{docs:void 0,requirement:Yt.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Yt.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new aQe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new aQe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n};let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i));let o=this.context.exampleGenerationArgs,s=ZHi({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=_kt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let o of Object.values(t.services)){let s=[];for(let a of o.endpoints)r.has(a.id)&&s.push(a);o.endpoints=s}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([o])=>n.has(o))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([o,s])=>{let a=s.filter(c=>c.id!=null&&i.has(c.id));return[o,a]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:o}){let s=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),a=this.getOrCreatePackage({group:n}),c=[...s].map(p=>this.context.casingsGenerator.generateName(p)),u=c[c.length-1];a.service==null&&(a.service=o??`service_${s.map(p=>Wn(p)).join("/")}`),this.ir.services[a.service]==null&&(this.ir.services[a.service]=this.createNewService({allParts:c,finalpart:u,endpointGroupDisplayName:i})),this.ir.services[a.service]?.endpoints.push(t);let l=this.ir.services[a.service];l!=null&&(this.irGraph.addEndpoint(l,t),this.irGraph.markEndpointForAudience(l.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let o=i?.join(".")??r,s=this.getOrCreatePackage({group:i});this.ir.webhookGroups[o]==null&&(this.ir.webhookGroups[o]=[]),this.ir.webhookGroups[o].push(t),s.webhooks=o;let a=this.context.createFernFilepath();this.irGraph.addWebhook(a,t),n!=null&&this.irGraph.markWebhookForAudiences(a,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=Wn(i?.join(".")),s=Wn(r),a=this.context.namespace?`${Wn(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:ob(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>Wn(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}};var Yd={};ee(Yd,{AbstractConverters:()=>Sno,ExampleConverter:()=>vv,SchemaConverters:()=>wno,ServersConverter:()=>v6});var Sno={};ee(Sno,{AbstractMediaTypeObjectConverter:()=>Dkr,AbstractParameterConverter:()=>Rkr});Wi();Rt();var Xzf=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function oic(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function Zzf(e){if(!oic(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>oic(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function e8f(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function sic(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var vv=class e extends oo{MAX_DEPTH=12;EXAMPLE_STRING=ki.STRING;EXAMPLE_NUMBER=ki.DOUBLE;EXAMPLE_BOOLEAN=ki.BOOLEAN;EXAMPLE_INTEGER=ki.INT;EXAMPLE_DATE=ki.DATE;EXAMPLE_DATE_TIME=ki.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=Object.entries(t.properties??{}).map(([p,d])=>{if(typeof d!="object")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:p,resolvedSchema:t}))return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let f=Zzf(d),m=!(p in r)||!f&&r[p]==null||f&&r[p]===void 0,h=!t.required?.includes(p);if(m&&h){if(this.example===void 0&&this.generateOptionalProperties){let A=this.maybeResolveSchemaExample(d),b=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:A,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:p,result:b.convert()}}return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let A=r[p],b=A!==void 0?A:this.maybeResolveSchemaExample(d),x=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:p,result:x}}}),i=(t.allOf??[]).map((p,d)=>{let f=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],skipErrorCollector:!0});return f&&this.isConstraintOnlySchema(f)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...p,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),o=this.example!==void 0&&(n.some(({result:p})=>p.usedProvidedExample)||i.some(p=>p.usedProvidedExample)),s=Object.fromEntries(n.map(({key:p,result:d})=>[p,d.validExample]).filter(([p,d])=>d!==void 0));for(let p of i)if(typeof p.validExample=="object"&&p.validExample!==null){let d=p.validExample;s={...s,...Object.fromEntries(Object.entries(d).filter(([f,m])=>m!==void 0))}}let a=[],c=this.collectAllPropertyKeys(t),u=Object.keys(r).filter(p=>!c.has(p));if(u.length>0)if(t.additionalProperties===!1)u.forEach(p=>{let d=[...this.breadcrumbs,p].join("."),f={message:`Found unexpected property '${p}' in example. This property does not exist in the schema${d?` at path: ${d}`:""}`,path:[...this.breadcrumbs,p]};a.push({key:p,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[f]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)u.forEach(p=>{a.push({key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[p],errors:[]}})});else{let p=t.additionalProperties;u.forEach(d=>{let m=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:p,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();a.push({key:d,result:m})})}for(let{key:p,result:d}of a)d.validExample!==void 0&&s[p]===void 0&&(s[p]=d.validExample);let l=n.every(p=>p.result.isValid)&&i.every(p=>p.isValid)&&a.every(({result:p})=>p.isValid);if(Object.keys(s).length===0){let p=i.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));p&&(s=p.validExample)}return{isValid:l,coerced:!1,usedProvidedExample:o,validExample:s,errors:[...n.flatMap(({result:p})=>p.errors),...i.flatMap(p=>p.errors),...a.flatMap(({result:p})=>p.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let h=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});h&&d.push(h)}if(d.length>0&&d.every(m=>e8f(m))){let m=d.findIndex(h=>sic(h)!==void 0);if(m!==-1){let h=n[m],A=d[m];if(h&&A){let b=sic(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...h,oneOf:void 0}:h,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,h=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(b.isValid&&!b.coerced&&b.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:b.validExample,errors:[]};if(b.isValid&&!b.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:b.usedProvidedExample,validExample:b.validExample,errors:[]};o.push(b),b.isValid&&b.usedProvidedExample&&a===null&&(a=b),b.isValid&&s===null&&(s=b)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(Xzf);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}};var wno={};ee(wno,{ArraySchemaConverter:()=>$Xe,EnumSchemaConverter:()=>fbe,ObjectSchemaConverter:()=>GXe,OneOfSchemaConverter:()=>cQe,PrimitiveSchemaConverter:()=>WXe,SchemaConverter:()=>mbe,SchemaOrReferenceConverter:()=>nP});function aic(e){return ev({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return kr.primitive({v1:"BASE_64",v2:$n.base64({})});case"BOOLEAN":return kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})});case"DATE":return kr.primitive({v1:"DATE",v2:$n.date({})});case"DATE_TIME":return kr.primitive({v1:"DATE_TIME",v2:$n.dateTime({})});case"DATE_TIME_RFC_2822":return kr.primitive({v1:"DATE_TIME_RFC_2822",v2:$n.dateTimeRfc2822({})});case"FLOAT":return kr.primitive({v1:"FLOAT",v2:$n.float({default:void 0,validation:void 0})});case"DOUBLE":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:void 0,validation:void 0})});case"UINT":return kr.primitive({v1:"UINT",v2:$n.uint({default:void 0,validation:void 0})});case"UINT_64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:void 0,validation:void 0})});case"INTEGER":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:void 0,validation:void 0})});case"LONG":return kr.primitive({v1:"LONG",v2:$n.long({default:void 0,validation:void 0})});case"STRING":return kr.primitive({v1:"STRING",v2:$n.string({default:void 0,validation:void 0})});case"UUID":return kr.primitive({v1:"UUID",v2:$n.uuid({})});case"BIG_INTEGER":return kr.primitive({v1:"BIG_INTEGER",v2:$n.bigInteger({default:void 0})});default:return}},unknown:()=>kr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return kr.container(Qs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return kr.container(Qs.list(t))},optional:t=>{if(t!=null)return kr.container(Qs.optional(t))},nullable:t=>{if(t!=null)return kr.container(Qs.nullable(t))},set:t=>{if(t!=null)return kr.container(Qs.set(t))},literal:t=>kr.container(Qs.literal(t._visit({string:r=>ZI.string(r),boolean:r=>ZI.boolean(r),_other:()=>{throw new j({message:"Unexpected literal type",code:j.Code.InternalError})}}))),named:()=>{}}})}var fbe=class extends oo{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:vc.enum({default:n!=null?r.find(i=>Xt(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}};var Okr=class extends oo{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=kr.container(Qs.map({keyType:oo.STRING,valueType:kr.unknown()}));return{type:vc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new nP({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=kr.container(Qs.map({keyType:oo.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return{type:vc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};var t8f=["description","title","format","type","discriminator","xml","externalDocs","extensions"],cic=["example","default"],uic=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],r8f=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],n8f=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],i8f=["allOf","oneOf","anyOf"];function lic(e,t){let r=pic(t),n={};for(let i of r)n=xno(n,i);return s8f(n,e),n}function pic(e){let t=[];for(let r of e)if(Array.isArray(r.allOf)&&r.allOf.length>0){let{allOf:n,...i}=r,o=n.filter(s=>!("$ref"in s));t.push(...pic(o)),Object.keys(i).length>0&&t.push(i)}else t.push(r);return t}function xno(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||i8f.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=o8f(o??{},i);continue}if(n==="items"){dbe(o)&&dbe(i)?r[n]=xno(o,i):r[n]=i;continue}if(cic.includes(n)){dbe(o)&&dbe(i)?r[n]=fic(o,i):r[n]=i;continue}if(uic.includes(n)){r[n]=!!o||!!i;continue}if(r8f.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(n8f.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function o8f(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];dbe(o)&&dbe(i)?r[n]=xno(o,i):r[n]=i}return r}function fic(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];dbe(o)&&dbe(i)?r[n]=fic(o,i):r[n]=i}return r}function s8f(e,t){for(let r of t8f){let n=t[r];n!=null&&(e[r]=n)}for(let r of cic){let n=t[r];n!=null&&(e[r]=n)}for(let r of uic)t[r]===!0&&(e[r]=!0)}function dbe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Rt();function qXe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let o=[],s={},a={},c=new Set;for(let[u,l]of Object.entries(e??{})){let p=[...r,"properties",u];if(typeof l!="object"){i.collect({message:`Schema property ${u} should be an object`,path:p});continue}let d=c8f(r,l,n)??n.convertBreadcrumbsToName(p),f="nullable"in l?l.nullable:!1,h=new nP({context:n,breadcrumbs:p,schemaOrReference:l,schemaIdOverride:d,wrapAsOptional:!t.includes(u),wrapAsNullable:f}).convert();if(h!=null){o.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:h.type,docs:l.description,availability:h.availability,propertyAccess:n.getPropertyAccess(l),v2Examples:h.schema?.typeDeclaration?.v2Examples??a8f({propertySchema:l,breadcrumbs:p,context:n,propertyId:d})}),s={...s,...h.inlinedTypes},h.schema?.typeDeclaration.referencedTypes!=null&&h.schema.typeDeclaration.referencedTypes.forEach(A=>{c.add(A)});for(let A of h.schema?.audiences??[])a[A]==null&&(a[A]=new Set),a[A].add(u)}}for(let u of Object.keys(s))c.add(u);return{convertedProperties:o,propertiesByAudience:a,inlinedTypesFromProperties:s,referencedTypes:c}}function a8f({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new vv({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:h}=m.convert();u[f]=h}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new vv({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function c8f(e,t,r){return r.isReferenceObject(t)?void 0:new uw.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var GXe=class extends oo{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:vc.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=qXe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,u=n,l=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,h]of Object.entries(f.properties))!this.context.isReferenceObject(h)&&p[m]==null&&(p[m]=h)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],h,A=!1;if(this.context.isReferenceObject(f)){let O=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(O==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(h=O,typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0),!c||Object.keys(h.properties??{}).every(F=>!this.schema.required?.includes(F))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else h=f,A=!0;typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0);let b=h.oneOf??h.anyOf;if(b!=null&&h.type==null&&h.properties==null){let O=new Set(r.map(F=>Xt(F.name)));for(let[F,T]of b.entries()){let V=[...m,h.oneOf!=null?"oneOf":"anyOf",F.toString()],K=this.context.isReferenceObject(T)?this.context.resolveMaybeReference({schemaOrReference:T,breadcrumbs:V}):T;if(K==null)continue;let Z={};for(let[Re,ne]of Object.entries(K.properties??{}))!this.context.isReferenceObject(ne)&&"not"in ne||(Z[Re]=ne);let Y=Object.keys(Z).filter(Re=>!O.has(Re));if(Y.length===0)continue;let le={};for(let Re of Y){let ne=Z[Re];ne!=null&&(le[Re]=ne,O.add(Re))}let{convertedProperties:Ae,inlinedTypesFromProperties:ae,referencedTypes:me,propertiesByAudience:Pe}=qXe({properties:le,required:[],breadcrumbs:V,context:this.context,errorCollector:this.context.errorCollector});r.push(...Ae),u={...u,...ae},l={...l,...Pe},me.forEach(Re=>{a.add(Re)})}continue}let v=h.properties??{};if(A){v={};for(let[O,F]of Object.entries(h.properties??{})){let T=p[O];T!=null&&!this.context.isReferenceObject(F)?v[O]={...T,...F}:v[O]=F}}let{convertedProperties:x,inlinedTypesFromProperties:C,referencedTypes:w,propertiesByAudience:B}=qXe({properties:v,required:[...this.schema.required??[],...h.required??[]],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector});r.push(...x),u={...u,...C},l={...l,...B},w.forEach(O=>{a.add(O)})}for(let d of Object.keys(u))a.add(d);return{type:vc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(Ra),extendedProperties:[],extraProperties:t}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}};var Pkr=class extends qa{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var cQe=class extends oo{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new Pkr({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null)return this.convertAsDiscriminatedUnion();if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new VXe({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new fbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let[l,p]of Object.entries(this.schema.discriminator.mapping??{})){let d=this.context.getTypeIdFromSchemaReference({$ref:p}),f=[...this.breadcrumbs,"discriminator","mapping",l],m=this.context.resolveReference({reference:{$ref:p},breadcrumbs:f}),h={$ref:p};m.resolved&&m.value.properties!=null&&t in m.value.properties&&(h=this.filterDiscriminantFromSchema(m.value,t));let A=new nP({context:this.context,schemaOrReference:h,schemaIdOverride:d??void 0,breadcrumbs:f});d!=null&&n.add(d);let b=A.convert();if(b?.type!=null&&d!=null){for(let O of Object.keys(b?.inlinedTypes??{}))n.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])n.add(O);let v=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),x=p.split("/").pop()??d,C=m.resolved?m.value.title:void 0,w=m.resolved?m.value.description:void 0,B=C??l??x;b.schema?.typeDeclaration!=null&&C!=null&&(b.schema.typeDeclaration.name.displayName=C),r.push({docs:w,discriminantValue:v,availability:b.availability,displayName:B,shape:uS.samePropertiesAsObject({typeId:d,name:this.context.casingsGenerator.generateName(x),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:B})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=qXe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let h=this.context.typeReferenceToDeclaredTypeName(f.reference);h!=null&&c.push(h)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let l of Object.keys({...i,...a}))n.add(l);let u=new zXe({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:vc.union({baseProperties:o,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:u.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[i,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else{let f=this.getDiscriminatorKeyForRef(o);f!=null?p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:f,displayNameOverrideSource:"discriminator_key"}):p=this.context.convertReferenceToTypeReference({reference:o,breadcrumbs:this.breadcrumbs})}if(p.ok){let f=this.context.resolveReference({reference:o,breadcrumbs:this.breadcrumbs}),m=f.resolved?f.value.description:void 0;t.push({type:p.reference,docs:m})}let d=this.context.getTypeIdFromSchemaReference(o);d!=null&&r.add(d);continue}let s=this.extendSubSchema(o),a=this.context.convertBreadcrumbsToName([`${this.id}_${i}`]),c=o.title,l=new mbe({context:this.context,id:a,nameOverride:c,breadcrumbs:[...this.breadcrumbs,`oneOf[${i}]`],schema:s??o}).convert();if(l!=null){let p=l.convertedSchema.typeDeclaration.shape;if(p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf))t.push({type:p.aliasOf,docs:o.description});else if(p.type==="object"&&p.properties.length===0&&p.extends.length===0)t.push({type:kr.container(Qs.map({keyType:oo.STRING,valueType:kr.unknown()})),docs:o.description});else{t.push({type:this.context.createNamedTypeReference(a,c),docs:o.description});let d=this.context.getNamespacedSchemaId(a);n={...n,...l.inlinedTypes,[d]:l.convertedSchema}}l.convertedSchema.typeDeclaration.referencedTypes.forEach(d=>{r.add(d)})}}return{type:vc.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new nP({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:vc.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return kr.container(Qs.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}};var WXe=class extends oo{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return kr.container(Qs.literal(ZI.string(t)));if(this.schema.format==="date-time-rfc-2822")return kr.primitive({v1:fs.DateTimeRfc2822,v2:$n.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return kr.primitive({v1:fs.Date,v2:$n.date({})});if(this.schema.format==="date-time")return kr.primitive({v1:fs.DateTime,v2:$n.dateTime({})})}return kr.primitive({v1:"STRING",v2:$n.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return kr.primitive({v1:"FLOAT",v2:$n.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return kr.primitive({v1:"LONG",v2:$n.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return kr.primitive({v1:"UINT",v2:$n.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return kr.primitive({v1:"DOUBLE",v2:$n.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return kr.primitive({v1:"FLOAT",v2:$n.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return kr.primitive({v1:"LONG",v2:$n.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return kr.primitive({v1:"UINT",v2:$n.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return kr.primitive({v1:"UINT_64",v2:$n.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return kr.primitive({v1:"INTEGER",v2:$n.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?kr.container(Qs.literal(ZI.boolean(t))):kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}};var u8f=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],mbe=class e extends oo{schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let o=this.tryConvertArraySchema();if(o!=null)return o;let s=this.tryConvertTypeArraySchema();if(s!=null)return s;let a=this.tryConvertOneOfAnyOfSchema();if(a!=null)return a;let c=this.tryConvertMapSchema();if(c!=null)return c;let u=this.tryConvertDiscriminatorMappingSchema();if(u!=null)return u;let l=this.tryConvertObjectAllOfSchema();if(l!=null)return l;let p=this.tryConvertUntypedSchema();if(p!=null)return p;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new uw.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new fbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let u;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,h]of Object.entries(f.properties??{}))!this.context.isReferenceObject(h)&&"not"in h||m in p||(p[m]=h)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(u)}if(i)return;let o=lic(this.schema,n),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryConvertPrimitiveSchema(){let r=new WXe({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new $Xe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new cQe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new Okr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new cQe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new GXe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:kr.unknown(),resolvedType:kr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new uw.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=aic(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:vc.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...u8f,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}};var nP=class extends oo{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{}}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>!i.properties&&!i.enum&&!i.oneOf&&!i.anyOf&&!i.allOf&&!i.format&&!("items"in i))&&!r.some(i=>i.type==="null"||Array.isArray(i.type)&&i.type.includes("null"))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{}}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new mbe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return kr.container(Qs.optional(t))}wrapInNullable(t){return kr.container(Qs.nullable(t))}};var $Xe=class e extends oo{static LIST_UNKNOWN=kr.container(Qs.list(kr.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),{typeReference:kr.container(Qs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Dkr=class extends oo{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new nP({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=Wn(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}};var Rkr=class extends oo{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??oo.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??oo.OPTIONAL_STRING,env:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??oo.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},n=this.parameter.example,i=this.parameter.examples;for(let[o,s]of Object.entries(i??{})){let a=this.context.resolveExampleWithValue(s);a!=null&&(r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:a,exampleName:o}))}if(n!=null){let o=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:n,exampleName:o})}if(Object.keys(r.userSpecifiedExamples).length===0){let o=`${this.parameter.name}_example`;r.autogeneratedExamples[o]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:o})}return r}generateOrValidateExample({schema:t,example:r}){let n=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};Rt();var Fkr=class extends qa{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var dic="Base",l8f="x-fern-default-url",v6=class e extends oo{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=this.endpointLevelServers?.map(h=>[e.getServerName({server:h,context:this.context}),this.getServerUrl(h)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,environments:q0.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(Ra);return{value:{defaultEnvironment:r[0]?.id,environments:q0.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new Fkr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new UXe({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?dic:e.getServerExtensionName({server:this.servers[0],context:this.context})??dic}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[l8f];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}};var uQe=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new vv({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?ub.WARNING:ub.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:ub.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?ub.WARNING:ub.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:ub.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf)return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:h,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let v of b){n++;let x={endpointPath:c,method:p,exampleName:v.name,exampleSource:v.source,requestExample:v.request,responseExample:v.response,requestSchema:m,responseSchema:h,responseStatusCode:v.statusCode,responseSchemas:A},C=this.validateEndpointExample({exampleToValidate:x});f.push(C),C.isValid?i++:(o++,v.source==="human"?s.push(C):v.source==="ai"&&a.push(C))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(v=>!v.isValid),invalidExampleCount:f.filter(v=>!v.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}};var HXe=new RegExp("[^\\x00-\\x7F]"),p8f=/(?:^|\n)\s*---\s*(?:\n|$)/;function mic({tags:e,errorCollector:t}){for(let r of e)if(HXe.test(r.name)){let n=[...r.name].filter(i=>HXe.test(i));t.collect({level:ub.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(HXe,"").trim()}".`})}}function hic({description:e,path:t,errorCollector:r}){p8f.test(e)&&r.collect({level:ub.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function _no({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");mic({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let u=c;if(typeof u.description=="string"&&hic({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&HXe.test(l)){n.add(l);let p=[...l].filter(d=>HXe.test(d));t.collect({level:ub.ERROR,message:`Tag name "${l}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${l}" to "${l.replace(HXe,"").trim()}".`})}}}}}}var kkr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},f8f=new Set(Object.values(kkr));function Bno(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}Wi();ts();var d8f=It.object({type:It.string(),channelId:It.string().optional(),messageId:It.string(),value:It.any()}),m8f=It.object({summary:It.string().optional(),description:It.string().optional(),"query-parameters":It.record(It.string()).optional(),headers:It.record(It.string()).optional(),messages:It.array(d8f)}),gic=It.array(m8f);var Nkr=class extends qa{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=gic.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}};var KXe=class extends oo{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new Nkr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var h8f="x-fern-server-name",k7=class e extends oo{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,environments:q0.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[h8f];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var hbe=class extends Yd.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new uw.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}};var Qkr=class extends qa{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var gbe=class extends qa{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}};var jkr=class extends qa{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}};var Mkr=class extends KXe{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new gbe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let l=new Qkr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=ob(p),m=Wn(this.channelPath),h=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})}},audiences:h,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=OPe(Wn(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=kr.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=Z1.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new gbe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new hbe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0}}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new hbe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0}}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return k7.getServerName(t,n)}return t}getOperationMethodName(t){return new jkr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new hbe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1}}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}};var Lkr=class extends k7{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Tno="$message.",Aic="#/channels/",Ono="#/servers/",Ukr=class extends KXe{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new gbe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((f,[m,h])=>{try{this.getChannelPathFromOperation(h)===this.channelPath&&(f[m]=h)}catch{}return f},{}),a=[];for(let[f,m]of Object.entries(s)){let A=new gbe({breadcrumbs:[...this.breadcrumbs,f],node:m,context:this.context}).convert()??f;for(let b of m.messages){let v=this.context.convertReferenceToTypeReference({reference:b});if(v.ok){let x=Z1.reference({bodyType:v.reference,docs:m.description});a.push({type:f,displayName:A,origin:m.action==="send"?"client":"server",body:x,availability:this.context.getAvailability({node:m,breadcrumbs:this.breadcrumbs}),docs:m.description,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=ob(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:l,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:u,baseUrl:c,asyncApiVersion:"v3"})}},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(Ono,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:u}=a,p=new hbe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(Tno)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${Tno} prefix`,path:this.breadcrumbs});return}let i=r.substring(Tno.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(Ono)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(Ono.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return k7.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return k7.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(Aic))throw new j({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:j.Code.ReferenceError});return t.channel.$ref.substring(Aic.length)}};var zkr=class extends k7{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var AQt=class extends F7{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let u=`${r}_${i}`;this.convertSchema({id:u,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new zkr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Lkr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=Ckt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return Gp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:t.description});if(t.scheme?.toLowerCase()==="basic")return Gp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,docs:t.description});break}case"apiKey":{if(t.in==="header")return Gp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:oo.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:t.description});break}case"oauth2":return Gp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:t.description})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new uw.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new Ukr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new Mkr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}};var yQt=class extends A0{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let u=a[1],l=a[2];return o=`${u}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:kr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};Rt();Jt();var wic=Ie(Vkr(),1);var qkr=class extends qa{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Gkr=class extends qa{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function y8f(e){if(e!=null){if(typeof e=="string")return Yt.Literal.string(e);if(typeof e=="boolean")return Yt.Literal.boolean(e)}}function yic({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:oo.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:oo.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:y8f(i.default)})}return r}function b8f(e){if(e!=null){if(typeof e=="string")return Yt.Literal.string(e);if(typeof e=="boolean")return Yt.Literal.boolean(e)}}function bic({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?oo.OPTIONAL_STRING:oo.STRING,env:r.env,v2Examples:r.optional?void 0:E8f({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:b8f(r["x-fern-default"])}))}function E8f({header:e,context:t}){let r=new vv({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}Wi();var Wkr=class extends Yd.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let n=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),o=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:n}).convert();o!=null&&(t=o.type,r=o.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};Rt();var $kr=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:u,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u,this.queryParameters=l??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if($f.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=$f.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=$f.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:fd.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes})}:{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:fd.reference({contentType:t,docs:this.description,requestBodyType:kr.unknown(),v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:fd.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[Xt(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:fd.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?xC.file(_2.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):xC.file(_2.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):xC.bodyProperty({...t,contentType:n?.contentType??r,style:v8f({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i==null||this.context.isReferenceObject(i))return;let o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let u=c.schema?.typeDeclaration.shape;if(u?.type==="object")return{requestBody:fd.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>Xt(n.name).toLowerCase()));return t.some(n=>r.has(Xt(n.name).toLowerCase()))}},I8f={"application/json":"json"};function v8f({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return I8f[e.contentType]}}var C8f=/{([^}]+)}/g,x8f=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),JXe=class extends oo{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o}convertHttpMethod(){switch(this.method){case"get":return kd.Get;case"post":return kd.Post;case"put":return kd.Put;case"delete":return kd.Delete;case"patch":return kd.Patch;case"head":return kd.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let o of this.operation.parameters){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t});if(s==null)continue;let c=new Wkr({context:this.context,breadcrumbs:t,parameter:s}).convert();if(c!=null)switch(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type){case"path":r.push(c.parameter);break;case"query":n.push(c.parameter);break;case"header":{let u=Vr(c.parameter.name),l=Xt(c.parameter.name),p=!1,d=this.context.authOverrides?.["auth-schemes"];if(d!=null){for(let m of Object.values(d))if(B8f(m)&&m.header.toLowerCase()===l.toLowerCase()){p=!0;break}}let f=this.context.globalHeaderNames;if(f!=null){for(let m of f)if(m.toLowerCase()===l.toLowerCase()){p=!0;break}}!x8f.has(u.toLowerCase())&&!p&&i.push(c.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}checkMissingPathParameters(t){let n=[...this.path.matchAll(C8f)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:oo.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,u]of Object.entries(s.content)){let p=new $kr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new uw.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new uw.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?Wn(this.operation.summary):Wn(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let n=Eic(t),i=Eic(r);return JE(n,i)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:n,methodName:r,methodNameTokens:i})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:n};let s=i.slice(r.length);return{group:[t],method:Wn(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Yd.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}};function Eic(e){let t=w8f(e)?S8f(e):_8f(e);return t=t.map(r=>r.toLowerCase()),t=B3(t),t}function w8f(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function S8f(e){return e.split(/(?=[A-Z])/)}function _8f(e){return e.split(/[^a-zA-Z0-9]+/)}function B8f(e){return e?.header!=null}var YXe=class extends JXe{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let u,l;if(c.type==="inlinedRequestBody")u=lS.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=lS.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")l={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=lS.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let p=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:u,signatureVerification:void 0,fileUploadPayload:l,responses:p.length>0?p:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}};var Rno=Ie(Vkr(),1);var Iic=["get","post","put","delete","patch","head"];var Hkr=class extends qa{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};ts();var T8f=It.object({cursor:It.string(),next_cursor:It.string(),results:It.string()}),O8f=It.object({offset:It.string(),results:It.string(),step:It.string().optional(),"has-next-page":It.string().optional()}),P8f=It.object({next_uri:It.string(),results:It.string()}),D8f=It.object({next_path:It.string(),results:It.string()}),Pno=It.union([It.boolean(),T8f,O8f,P8f,D8f]);var Dno="$request.",ybe="$response.",Kkr=class extends qa{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Pno.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=Pno.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:A0.maybeTrimPrefix(r.cursor,Dno),nextCursor:A0.maybeTrimPrefix(r.next_cursor,ybe),results:A0.maybeTrimPrefix(r.results,ybe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:A0.maybeTrimPrefix(n.next_uri,ybe),results:A0.maybeTrimPrefix(n.results,ybe)};let i=t;if("next_path"in i)return{type:"path",nextPath:A0.maybeTrimPrefix(i.next_path,ybe),results:A0.maybeTrimPrefix(i.results,ybe)};let o=t;return{type:"offset",offset:A0.maybeTrimPrefix(o.offset,Dno),results:A0.maybeTrimPrefix(o.results,ybe),step:o.step!=null?A0.maybeTrimPrefix(o.step,Dno):void 0,hasNextPage:o["has-next-page"]!=null?A0.maybeTrimPrefix(o["has-next-page"],ybe):void 0}}};ts();var R8f="$request.",F8f=It.object({"stream-condition":It.string().optional(),format:It.enum(["sse","json"]).optional(),"stream-description":It.string().optional(),"stream-request-name":It.string().optional(),"response-stream":It.any(),response:It.any(),terminator:It.string().optional()}),k8f=It.union([It.boolean(),F8f]),Jkr=class extends qa{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=k8f.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:A0.maybeTrimPrefix(r.data["stream-condition"],R8f),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response}}};var Ykr=class extends qa{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};Wi();Rt();var Zkr=require("fs"),vic=require("path");function N8f(e){return fa(e)&&typeof e.$ref=="string"}function Q8f(e,t){if(e!=null){if(typeof e=="string")return e;if(N8f(e)){let r=(0,vic.resolve)(t??process.cwd(),e.$ref);if((0,Zkr.existsSync)(r))try{return(0,Zkr.readFileSync)(r,"utf-8")}catch{return}}}}var Xkr=class extends qa{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=fa(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!fa(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=Q8f(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}};Rt();var t2r=require("fs"),Cic=require("path");function j8f(e){return fa(e)&&typeof e.$ref=="string"}function M8f(e,t){if(e!=null){if(typeof e=="string")return e;if(j8f(e)){let r=(0,Cic.resolve)(t??process.cwd(),e.$ref);if((0,t2r.existsSync)(r))try{return(0,t2r.readFileSync)(r,"utf-8")}catch{return}}}}function L8f(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!fa(n))continue;let o=M8f(n.code,t);o!=null&&r.push({...n,code:o})}return r}var e2r=class extends qa{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!fa(o))return o;let a=o["code-samples"];if(a!=null){let c=L8f(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=oh.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}};var bQt=class extends qa{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};Rt();var EQt=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:yu.json(Wb.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:yu.streaming(XE.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:yu.streaming(XE.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:yu.streaming(XE.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:yu.json(Wb.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:yu.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:yu.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:yu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return $f.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=oo.OPTIONAL_STRING;if(s!=null){let u=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});u!=null&&(u.type==="number"||u.type==="integer"?a=kr.primitive({v1:u.type==="integer"?"INTEGER":"DOUBLE",v2:u.type==="integer"?$n.integer({default:void 0,validation:void 0}):$n.double({default:void 0,validation:void 0})}):u.type==="boolean"&&(a=kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})})))}let c=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:c,availability:void 0,clientDefault:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,c]of Object.entries(s??{})){let u=this.context.resolveExampleWithValue(c);u!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:u}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};var r2r=class extends Yd.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:kr.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:xic(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return kkr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?xic(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=oo.OPTIONAL_STRING;if(s!=null){let u=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});u!=null&&(u.type==="number"||u.type==="integer"?a=kr.primitive({v1:u.type==="integer"?"INTEGER":"DOUBLE",v2:u.type==="integer"?$n.integer({default:void 0,validation:void 0}):$n.double({default:void 0,validation:void 0})}):u.type==="boolean"&&(a=kr.primitive({v1:"BOOLEAN",v2:$n.boolean({default:void 0})})))}let c=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:c,availability:void 0,clientDefault:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,c]of Object.entries(s??{})){let u=this.context.resolveExampleWithValue(c);u!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:u}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new vv({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};function xic(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var n2r=class e extends JXe{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,idempotent:s,idToAuthScheme:a,topLevelServers:c,pathLevelServers:u,streamingExtension:l}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o}),this.idempotent=s,this.idToAuthScheme=a,this.topLevelServers=c,this.pathLevelServers=u,this.streamingExtension=l}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),{headers:o,pathParameters:s,queryParameters:a}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),c=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:a}),u=c?.[0]?.requestBody,l=c?.[0]?.streamRequestBody,p={requestBodies:c?.map(me=>me.requestBody)},d=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),f=d?.response,m=d?.streamResponse,h=d!=null?d.errors:[],A={},b=h.map(me=>me.error),v=ob(this.path),x=this.getEndpointBaseUrl(),C=this.getEndpointBaseUrls(),w=this.convertExamples({httpPath:v,httpMethod:t,baseUrl:x});if(Object.keys(w.examples).length===0&&Object.keys(w.streamExamples).length===0){let me=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:v,httpMethod:t,baseUrl:x});if(me!=null)for(let[Pe,Re]of Object.entries(me))w.examples[Pe]=Re}let B=new Set(this.operation.security?.flatMap(me=>Object.keys(me))??[]),O=this.authSchemeToHeaders(Array.from(B));O.length>0&&o.push(...O);for(let me of h){let Pe=me.error,Re=me.errorType,ne=Pe.error.errorId,ie=me.examples;A[ne]={name:Pe.error,displayName:me.displayName,discriminantValue:{name:Pe.error.name,wireValue:ne},type:Re,statusCode:me.statusCode,isWildcardStatusCode:me.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:ie??{},autogeneratedExamples:{}},headers:me.headers}}let F=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],V=new bQt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),Y=new bQt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??V,le={displayName:this.operation.summary,method:t,baseUrl:x,v2BaseUrls:C,path:v,pathParameters:s,queryParameters:a,headers:o.filter((me,Pe,Re)=>Pe===Re.findIndex(ne=>Xt(ne.name)===Xt(me.name))),responseHeaders:d?.responseHeaders,sdkRequest:void 0,errors:b,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:v,allPathParameters:s,pagination:void 0,transport:void 0,source:YT.openapi(),audiences:F,retries:void 0,apiPlayground:Y},Ae=this.context.namespace!=null?[this.context.namespace]:[],ae=r?.map(me=>Wn(me));return Ae.push(...ae??[]),{audiences:F,group:r,groupDisplayName:i,errors:A,endpoint:{...le,id:`endpoint_${Ae.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:u,v2RequestBodies:p,response:f,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w.examples},v2Responses:{responses:d?.v2Responses}},streamEndpoint:m!=null&&m.body!=null?{...le,id:`endpoint_${Ae.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:l,v2RequestBodies:void 0,response:m,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:m.body,docs:m.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let h=new EQt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(h==null){a=!0;continue}h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.streamResponseBody,docs:f.description},h.headers!=null&&(o.responseHeaders=h.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:h.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let h=new r2r({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!0:void 0}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},o.errors.push(h))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new EQt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:yu.json(Wb.response({...c.value,responseBodyType:kr.container(Qs.optional(u))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():Bno(this.operation.security??this.context.spec.security)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:oo.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new e2r({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new Xkr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={displayName:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:Yt.V2HttpEndpointResponseBody.json(c)}}}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Yt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Yt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new uw.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${Bn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return v6.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(n=>{let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return v6.getServerName({server:o,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let n=t?.[t.length-1];if(n!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===n?r:void 0}};var i2r=class extends oo{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s}convert(){let t=[],r=[],n={};for(let i of Iic){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let u=new Jkr({breadcrumbs:s,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new Ykr({breadcrumbs:n,operation:t,context:i}).convert()?new YXe({context:this.context,breadcrumbs:n,operation:t,method:Rno.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new Kkr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new Hkr({breadcrumbs:n,operation:t,context:this.context}).convert();return new n2r({context:this.context,breadcrumbs:n,operation:t,method:Rno.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:c,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}};var o2r=class extends oo{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",n=t?.env;return Gp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:n,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",n=t?.password?.name??"password",i=t?.username?.env,o=t?.password?.env;return Gp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(n),usernameEnvVar:i,passwordEnvVar:o,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",n=t?.env,i=t?.prefix;return Gp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:oo.OPTIONAL_STRING,prefix:i,headerEnvVar:n,docs:this.securityScheme.description})}break}case"oauth2":return Gp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var IQt=class extends F7{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),_no({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=yic({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new Gkr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=bic({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertBasePath(){let r=new qkr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=ob(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=Ckt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new o2r({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let i=xkt({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return i!=null&&this.addEnvironmentsToIr({environmentConfig:i.environmentsConfig,audiences:i.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let n=new v6({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new YXe({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:wic.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[n,i]of Object.entries(this.context.spec.paths??{})){if(i==null)continue;let s=new i2r({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:i,path:n}).convert();if(s!=null){for(let a of s.endpoints){if(a.streamEndpoint!=null&&this.addEndpointToIr({endpoint:a.streamEndpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),this.addEndpointToIr({endpoint:a.endpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),a.servers)for(let c of a.servers)this.shouldAddServerToCollectedServers({server:c,currentServers:t})&&t.push(c);if(a.errors)for(let[c,u]of Object.entries(a.errors))r[c]=u}for(let a of s.webhooks){let c=this.context.getGroup({groupParts:a.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:a.webhook,operationId:c.join("."),group:c,audiences:a.audiences})}this.addTypesToIr(s.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security&&delete i.security}}}};var s2r=class extends qa{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var bue=class extends A0{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let u;if(o.includes("/")){let p=new Yd.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>Xt(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new s2r({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=i}return this.tagToDisplayName[t]??t}};var U8f={GET:kd.Get,POST:kd.Post,PUT:kd.Put,PATCH:kd.Patch,DELETE:kd.Delete};function kno({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=aDe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>z8f({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function z8f({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"],i=Sic({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=Fno({ir:e,endpoint:o,wireValue:N7(c?.["client-id"],"client_id")}),p=Fno({ir:e,endpoint:o,wireValue:N7(c?.["client-secret"],"client_secret")}),d=XXe({ir:e,endpoint:o,wireValue:N7(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return Gp.oauth({key:t,docs:r.docs,configuration:G$.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:l,clientSecret:p,scopes:void 0,customProperties:G8f({ir:e,endpoint:o,excludeWireValues:[N7(c?.["client-id"],"client_id"),N7(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:XXe({ir:e,endpoint:o,wireValue:N7(u?.["expires-in"],"expires_in")}),refreshToken:XXe({ir:e,endpoint:o,wireValue:N7(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?V8f({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function V8f({ir:e,refreshTokenConfig:t}){let r=Sic({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=Fno({ir:e,endpoint:n,wireValue:N7(s?.["refresh-token"],"refresh_token")}),u=XXe({ir:e,endpoint:n,wireValue:N7(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:XXe({ir:e,endpoint:n,wireValue:N7(a?.["expires-in"],"expires_in")}),refreshToken:XXe({ir:e,endpoint:n,wireValue:N7(a?.["refresh-token"],"refresh_token")})}}}function Sic({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=U8f[r[0]?.toUpperCase()??""],i=r[1]?.replace(/\/+$/,"");if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(q8f(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function q8f(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t.replace(/\/+$/,"")}function N7(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function _ic(e,t){return e.find(r=>Xt(r.name)===t)}function Nno(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function Fno({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties:t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=Nno(e,t.requestBody.requestBodyType.typeId));let i=n!=null?_ic(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:J1.body({...i})}}function G8f({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties:t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=Nno(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(Xt(s.name))).map(s=>({propertyPath:void 0,property:J1.body({...s})}));return o.length>0?o:void 0}function XXe({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=Nno(e,n.typeId),o=i!=null?_ic(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}Rt();ts();var W8f=It.object({description:It.string().optional(),required:It.boolean().optional(),deprecated:It.boolean().optional(),allowEmptyValue:It.boolean().optional(),style:It.string().optional(),explode:It.boolean().optional(),allowReserved:It.boolean().optional(),schema:It.any().optional(),example:It.any().optional(),examples:It.record(It.string(),It.any()).optional(),content:It.record(It.string(),It.any()).optional()}),$8f=W8f.extend({name:It.string(),in:It.string()}),H8f=It.array($8f),a2r=class extends qa{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return H8f.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${oi(r)}`,path:this.breadcrumbs});return}}};var c2r=class extends oo{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=ob(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let h=this.context.resolveReference({reference:l});if(h.resolved)p=h.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Yd.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Yd.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?fd.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:yu.json(Wb.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:YT.openrpc(),audiences:a,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return v6.getServerName({server:s,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let n of this.method.examples??[]){let i;if(this.context.isReferenceObject(n)){let c=this.context.resolveReference({reference:n});if(c.resolved)i=c.value;else continue}else i=n;let o;if(i.result)if(this.context.isReferenceObject(i.result)){let c=this.context.resolveReference({reference:i.result});c.resolved&&(o=c.value)}else o=i.result;let s=i.name??`Example ${r+1}`,a=[];if(i.params&&Array.isArray(i.params)){a=[];for(let c of i.params)if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c});if(u.resolved)a.push(u.value);else continue}else a.push(c)}t[s]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:a.map(c=>c.value)??void 0},response:{docs:void 0,statusCode:void 0,body:o?.value?Yt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:i.examplePairedRequest?.id||"1",result:o.value}):void 0},codeSamples:[]}}++r}return t}};var u2r=class extends Yd.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Yd.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var vQt=class extends F7{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new v6({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Yd.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new a2r({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new u2r({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new c2r({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}};var CQt=class extends A0{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:kr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};var ooo=require("fs/promises");var Bic=require("fs/promises");async function Qno({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,Bic.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Tr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await MXe({absoluteFilePathToOverrides:a,context:e,data:s});return s}Jt();var rsc=Ie(tsc(),1);function Uqf(e,t){if(!t)return;if(e.catch(()=>{}),t.aborted){e.kill();return}let r=()=>{e.kill()};t.addEventListener("abort",r,{once:!0}),e.finally(()=>t.removeEventListener("abort",r)).catch(()=>{})}function C6(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let c=i.reduce((p,d)=>({...p,[d]:"<redacted>"}),o),u=[t,...r].join(" ");for(let[p,d]of Object.entries(c))u=u.replaceAll(p,d);e?.debug(`+ ${u}`);let l=(0,rsc.default)(t,r,a);return Uqf(l,s),l}async function Eu(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let c=C6(e,t,r,{doNotPipeOutput:n,secrets:i,substitutions:o,signal:s,...a});n||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let u=await c;return u.stdout==null&&(u.stdout=""),u.stderr==null&&(u.stderr=""),u}function Q7(e,{logger:t,...r}={}){return(n,i)=>Eu(t,e,n,{...r,...i})}var lF=require("fs/promises"),hsc=Ie(require("path"),1),oio=Ie(nS(),1);Rt();Jt();var lQe=require("fs/promises"),ssc=Ie(nS(),1);Jt();var y0=require("fs/promises"),A2r=Ie(require("os"),1),rio=Ie(require("path"),1),Eue="v1.50.0",zqf="https://github.com/bufbuild/buf/releases/download",BQt="buf",Vqf=".fern",qqf="bin",nsc=12e4,eio=200;function nio(){let e=A2r.default.platform(),t=A2r.default.arch(),r;switch(e){case"linux":r="Linux";break;case"darwin":r="Darwin";break;case"win32":r="Windows";break;default:throw new j({message:`Unsupported platform: ${e}`,code:j.Code.EnvironmentError})}let n;switch(t){case"x64":n="x86_64";break;case"arm64":n=e==="linux"?"aarch64":"arm64";break;default:throw new j({message:`Unsupported architecture: ${t}`,code:j.Code.EnvironmentError})}return{os:r,arch:n,extension:r==="Windows"?".exe":""}}function TQt(){let e=A2r.default.homedir();return $t.of(rio.default.join(e,Vqf,qqf))}function Gqf(){let{extension:e}=nio(),t=TQt();return $e(t,Te.of(`${BQt}-${Eue}${e}`))}function Wqf(){let{extension:e}=nio(),t=TQt();return $e(t,Te.of(`${BQt}${e}`))}function $qf(){let e=TQt();return $e(e,Te.of(`${BQt}.version`))}function Hqf(){let e=TQt();return rio.default.join(e,`${BQt}.lock`)}function Kqf(){let{os:e,arch:t,extension:r}=nio();return`${zqf}/${Eue}/${BQt}-${e}-${t}${r}`}async function isc(e){try{return await(0,y0.access)(e),!0}catch{return!1}}async function Jqf(e){let t=Hqf(),r=Date.now()+nsc;for(;Date.now()<r;)try{return await(0,y0.mkdir)(t,{recursive:!1}),tio(t,e)}catch{e.debug(`Waiting for buf lock on ${t}...`),await new Promise(n=>setTimeout(n,eio))}e.debug(`Buf lock timed out after ${nsc}ms, breaking stale lock`);try{await(0,y0.rm)(t,{recursive:!0})}catch(n){e.debug(`Failed to remove stale buf lock: ${n instanceof Error?n.message:String(n)}`)}try{await(0,y0.mkdir)(t,{recursive:!1})}catch{let n=Math.max(eio*5,r-Date.now()),i=Date.now()+n;for(;Date.now()<i;)try{return await(0,y0.mkdir)(t,{recursive:!1}),tio(t,e)}catch{e.debug(`Waiting for buf lock on ${t} (post-break retry)...`),await new Promise(o=>setTimeout(o,eio))}throw new j({message:"Failed to acquire buf lock after timeout and retry",code:j.Code.InternalError})}return tio(t,e)}function tio(e,t){return async()=>{try{await(0,y0.rm)(e,{recursive:!0})}catch(r){t.debug(`Failed to release buf lock: ${r instanceof Error?r.message:String(r)}`)}}}async function OQt(e){try{let t=TQt();await(0,y0.mkdir)(t,{recursive:!0});let r=await Jqf(e);try{return await Yqf(e)}finally{await r()}}catch(t){e.debug(`Failed to resolve buf: ${t instanceof Error?t.message:String(t)}`);return}}async function Yqf(e){let t=Gqf(),r=Wqf(),n=$qf();if(await isc(t))return await Xqf(n,e)===Eue&&await isc(r)?(e.info(`Using cached buf ${Eue}`),r):(await osc(t,r),await(0,y0.writeFile)(n,Eue),e.info(`Updated buf to ${Eue}`),r);let i=Kqf();e.info(`Downloading buf ${Eue}...`);let o=$t.of(`${t}.download`);try{let s=await fetch(i,{redirect:"follow"});if(!s.ok){e.debug(`Failed to download buf: ${s.status} ${s.statusText}`);return}let a=await s.arrayBuffer();return await(0,y0.writeFile)(o,new Uint8Array(a)),await(0,y0.chmod)(o,493),await(0,y0.rename)(o,t),await osc(t,r),await(0,y0.writeFile)(n,Eue),e.info(`Downloaded buf ${Eue}`),r}catch(s){e.debug(`Failed to download buf: ${s instanceof Error?s.message:String(s)}`);try{await(0,y0.rm)(o,{force:!0})}catch(a){e.debug(`Failed to clean up partial buf download: ${a instanceof Error?a.message:String(a)}`)}return}}async function Xqf(e,t){try{return(await(0,y0.readFile)(e,"utf-8")).trim()}catch(r){t.debug(`Failed to read buf version marker: ${r instanceof Error?r.message:String(r)}`);return}}async function osc(e,t){let r=$t.of(`${t}.tmp`);await(0,y0.copyFile)(e,r),await(0,y0.chmod)(r,493),await(0,y0.rename)(r,t)}function DQt(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var PQt,iio;async function RQt(e,t,r=5e3){return PQt!==void 0?PQt:(iio==null&&(iio=Zqf(e,t,r)),iio)}async function Zqf(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),PQt=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(n){let i=oi(n);return DQt(i)?(PQt=!0,t.debug(`Network check failed - entering air-gapped mode: ${i}`),!0):(PQt=!1,!1)}}async function FQt(e,t,r="buf"){let n=$e(e,Te.of("buf.lock")),i=!1;try{await(0,lQe.access)(n),i=!0,t.debug(`Found buf.lock at: ${n}`)}catch{t.debug(`No buf.lock found at: ${n}`)}if(!i)return!1;let o=$t.of((await ssc.default.dir()).path);try{let s=$e(e,Te.of("buf.yaml"));try{await(0,lQe.cp)(s,$e(o,Te.of("buf.yaml"))),await(0,lQe.cp)(n,$e(o,Te.of("buf.lock")))}catch{return!1}try{return await C6(t,r,["dep","update"],{cwd:o,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(a){let c=oi(a);return DQt(c)?(t.debug(`Network check failed - entering air-gapped mode: ${c.substring(0,100)}`),!0):!1}}finally{try{await(0,lQe.rm)(o,{recursive:!0,force:!0})}catch{}}}async function kQt(e){let t=Q7("which",{cwd:$t.of(process.cwd()),logger:void 0,doNotPipeOutput:!0});try{let n=(await t(["buf"])).stdout?.trim();return n?e.debug(`Found buf on PATH: ${n}`):e.debug("Found buf on PATH"),"buf"}catch{e.debug("buf not found on PATH, attempting auto-download");let r=await OQt(e);if(r!=null)return e.debug(`Using auto-downloaded buf: ${r}`),r;throw new j({message:"Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').",code:j.Code.EnvironmentError})}}var asc="buf.gen.yaml",e5f="output",csc=`${e5f}/ir.json`,usc="protoc-gen-fern",lsc=`version: v1
|
|
1630
1630
|
`,psc=`version: v2
|
|
1631
1631
|
`,NQt=e=>{let t=`version: v1
|
|
1632
1632
|
`;if(e.length>0){t+=`deps:
|
|
@@ -1736,7 +1736,7 @@ ${Nbc.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Slo(th
|
|
|
1736
1736
|
`+HQe.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?HQe.default.cyan(Gbc(t,this.opt.mask)):HQe.default.italic(HQe.default.dim("[hidden]")):this.opt.mask?Gbc(t,this.opt.mask):HQe.default.italic(HQe.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var k3r=Ie(dw(),1);var qEc=Ie(apo(),1),R3r=require("child_process"),Ket=require("fs"),D3r=Ie(require("path"),1),GEc=Ie(require("os"),1),WEc=require("crypto"),Gpo=Ie(zEc(),1);var T3r=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var GMt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var O3r=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var P3r=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function F3r(e="",t,r){let n=new Wpo(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function VEc(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function nId(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var Wpo=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=nId(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??GEc.default.tmpdir(),r=(0,WEc.randomUUID)(),n=VEc(this.fileOptions.prefix),i=VEc(this.fileOptions.postfix),o=`${n}${r}${i}`,s=D3r.default.resolve(t,o),a=D3r.default.resolve(t)+D3r.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,Ket.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new T3r(t)}}readTemporaryFile(){try{let t=(0,Ket.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,qEc.detect)(t)??"utf8";Gpo.default.encodingExists(r)||(r="utf8"),this.text=Gpo.default.decode(t,r)}}catch(t){throw new O3r(t)}}removeTemporaryFile(){try{(0,Ket.unlinkSync)(this.tempFile)}catch(t){throw new P3r(t)}}launchEditor(){try{let t=(0,R3r.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new GMt(t)}}launchEditorAsync(t){try{(0,R3r.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new GMt(r)}}};var $Ec=Ie(N6(),1);var WMt=class extends mw{_run(t){this.done=t,this.editorResult=new $Ec.Subject;let r=$B(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?k3r.default.dim("Received"):k3r.default.dim("Press <enter> to launch your preferred editor."),t&&(r=k3r.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),F3r(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var XEc=require("stream");var JEc=Ie(require("readline"),1),YEc=Ie(KEc(),1),XQe=class{constructor(t){this.rl||=JEc.default.createInterface(oId(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function oId(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new YEc.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var $Mt=class extends XQe{constructor(t={}){super(t),this.log=new XEc.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return OMt(this.rl,this.bottomBar.split(`
|
|
1737
1737
|
`).length),this}updateBottomBar(t){return OMt(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
|
|
1738
1738
|
`}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&n3r(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Cd=Ie(N6(),1),tIc=Ie(aMt(),1);var N3r=Ie(N6(),1),ZEc=Ie(aMt(),1),Q3r=function(e,t,r){return typeof e[t]!="function"?(0,N3r.of)(e):(0,N3r.from)((0,ZEc.default)(e[t])(r).then(n=>(e[t]=n,e)))};var eIc={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Jet=class extends XQe{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,Cd.from)(t):(0,Cd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Cd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Cd.from)([t]),this.process=n.pipe((0,Cd.concatMap)(this.processQuestion.bind(this)),(0,Cd.publish)()),this.process.connect(),this.process.pipe((0,Cd.reduce)((i,o)=>(eIc.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Cd.defer)(()=>(0,Cd.of)(t).pipe((0,Cd.concatMap)(this.setDefaultType.bind(this)),(0,Cd.concatMap)(this.filterIfRunnable.bind(this)),(0,Cd.concatMap)(()=>Q3r(t,"message",this.answers)),(0,Cd.concatMap)(()=>Q3r(t,"default",this.answers)),(0,Cd.concatMap)(()=>Q3r(t,"choices",this.answers)),(0,Cd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Cd.defer)(()=>(0,Cd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Cd.defer)(()=>(0,Cd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&eIc.get(this.answers,t.name)!==void 0)return Cd.EMPTY;if(t.when===!1)return Cd.EMPTY;if(typeof t.when!="function")return(0,Cd.of)(t);let{answers:r}=this;return(0,Cd.defer)(()=>(0,Cd.from)((0,tIc.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Cd.filter)(n=>n!=null)))}};function rIc(e){let t=function(r,n){let i;try{i=new Jet(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",DMt),this.registerPrompt("input",$Qe),this.registerPrompt("number",RMt),this.registerPrompt("confirm",FMt),this.registerPrompt("rawlist",kMt),this.registerPrompt("expand",NMt),this.registerPrompt("checkbox",QMt),this.registerPrompt("password",jMt),this.registerPrompt("editor",WMt)},t.restoreDefaultPrompts(),t}var Hpo=rIc();function aId(e,t){Hpo.registerPrompt(e,t)}function cId(){Hpo.restoreDefaultPrompts()}var uId={prompt:Hpo,ui:{BottomBar:$Mt,Prompt:Jet},createPromptModule:rIc,registerPrompt:aId,restoreDefaultPrompts:cId,Separator:VN},jp=uId;var Yet=require("path");function iIc(){let e=lId();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function lId(e=process.argv[1]?(0,Yet.dirname)(process.argv[1]):process.cwd(),t=Yet.sep==="\\"){let r=t?nIc(e):e;return n=>{if(!n)return;let i=t?nIc(n):n,{dir:o,base:s,ext:a}=Yet.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function nIc(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Kpo=e=>{if("flags"in e){let t=oIc(e.flags),r=sIc(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Jpo(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,pId(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function pId(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var oIc=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,HMt(r)]).filter(([,t])=>t!==void 0)),sIc=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?Jpo(n):void 0]}))};var HMt=e=>e===void 0?void 0:e.variant??e.enabled,Jpo=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};function aIc(){return"CompressionStream"in globalThis}async function j3r(e,t=!0){try{let n=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(n).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var M3r="0123456789abcdef",L3r=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=M3r.charAt(this.bytes[r]>>>4),t+=M3r.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=M3r.charAt(this.bytes[r]>>>4),t+=M3r.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Ypo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??fId()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return L3r.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,L3r.ofInner(t)}},fId=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),cIc,mEe=()=>dId().toString(),dId=()=>(cIc||(cIc=new Ypo)).generate();var GN=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});var mId=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],uIc=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return mId.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var gId=Array.isArray,lIc=Object.prototype,vxb=lIc.hasOwnProperty,Xpo=lIc.toString,Zpo=gId||function(e){return Xpo.call(e)==="[object Array]"};var efo=e=>e===Object(e)&&!Zpo(e);var KMt=e=>e===void 0,JMt=e=>Xpo.call(e)=="[object String]",pIc=e=>JMt(e)&&e.trim().length===0;var fIc=e=>Xpo.call(e)=="[object Number]"&&e===e;var tfo=e=>e instanceof Error;function U3r(e){return e===null||typeof e!="object"}function ZQe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function dIc(e){return ZQe(e,"ErrorEvent")}function Xet(e){return typeof Event<"u"&&AId(e,Event)}function mIc(e){return ZQe(e,"Object")}function AId(e,t){try{return e instanceof t}catch{return!1}}function YMt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),fIc(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),YMt(i||r,t,r,n))}var yId=864e5,z3r=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=YMt(t.bucketSize,0,100,t._logger),this._refillRate=YMt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=YMt(t.refillInterval,0,yId,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var V3r=class{add(t){let r=mEe();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function bId(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var hIc=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>hIc(`${e} ${o}`,t,r)}},EId=e=>e();function gIc(e,t=EId){return hIc(e,t,bId())}var ett="Mobile",G3r="iOS",Zet="Android",AIc="Tablet",Fxb=Zet+" "+AIc;var IId="Apple",kxb=IId+" Watch",yIc="Safari",W3r="BlackBerry",bIc="Samsung",vId=bIc+"Browser",CId=bIc+" Internet",$3r="Chrome",xId=$3r+" OS",wId=$3r+" "+G3r,EIc="Internet Explorer",SId=EIc+" "+ett,nfo="Opera",Nxb=nfo+" Mini",IIc="Edge",_Id="Microsoft "+IIc,ifo="Firefox",BId=ifo+" "+G3r,ofo="Nintendo",sfo="PlayStation",q3r="Xbox",TId=Zet+" "+ett,OId=ett+" "+yIc,XMt="Windows",PId=XMt+" Phone";var vIc="Generic",Qxb=vIc+" "+ett.toLowerCase(),jxb=vIc+" "+AIc.toLowerCase(),DId="Konqueror",hF="(\\d+(\\.\\d+)?)",rfo=new RegExp("Version/"+hF),Mxb=new RegExp(q3r,"i"),Lxb=new RegExp(sfo+" \\w+","i"),Uxb=new RegExp(ofo+" \\w+","i"),RId=new RegExp(W3r+"|PlayBook|BB10","i"),FId={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var zxb={[SId]:[new RegExp("rv:"+hF)],[_Id]:[new RegExp(IIc+"?\\/"+hF)],[$3r]:[new RegExp("("+$3r+"|CrMo)\\/"+hF)],[wId]:[new RegExp("CriOS\\/"+hF)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+hF)],[yIc]:[rfo],[OId]:[rfo],[nfo]:[new RegExp("("+nfo+"|OPR)\\/"+hF)],[ifo]:[new RegExp(ifo+"\\/"+hF)],[BId]:[new RegExp("FxiOS\\/"+hF)],[DId]:[new RegExp("Konqueror[:/]?"+hF,"i")],[W3r]:[new RegExp(W3r+" "+hF),rfo],[TId]:[new RegExp("android\\s"+hF,"i")],[CId]:[new RegExp(vId+"\\/"+hF)],[EIc]:[new RegExp("(rv:|MSIE )"+hF)],Mozilla:[new RegExp("rv:"+hF)]};var Vxb=[[new RegExp(q3r+"; "+q3r+" (.*?)[);]","i"),e=>[q3r,e&&e[1]||""]],[new RegExp(ofo,"i"),[ofo,""]],[new RegExp(sfo,"i"),[sfo,""]],[RId,[W3r,""]],[new RegExp(XMt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[PId,""];if(new RegExp(ett).test(t)&&!/IEMobile\b/.test(t))return[XMt+" "+ett,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=FId[n]||"";return/arm/i.test(t)&&(i="RT"),[XMt,i]}return[XMt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[G3r,t.join(".")]}return[G3r,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=KMt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Zet+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Zet+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Zet,t.join(".")]}return[Zet,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[xId,""]],[/Linux|debian/i,["Linux",""]]];var CIc="utf8";function xIc(e,t){if(!e||typeof e!="string"||kId(e))throw new Error(t)}function kId(e){return e.trim().length===0}function wIc(e){return e?.replace(/\/+$/,"")}async function SIc(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function H3r(){return new Date().toISOString()}function que(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var _Ic=e=>e instanceof Error;function afo(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var K3r=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};var eje=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},ttt=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function BIc(e){if(e instanceof eje){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function cfo(e){return typeof e=="object"&&(e instanceof eje||e instanceof ttt)}function TIc(e){return typeof e=="object"&&e instanceof eje&&e.status===413}var ZMt=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new V3r,this._events=new K3r,this._isInitialized=!1,xIc(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=wIc(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:cfo},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=gIc("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!aIc()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(GN.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(GN.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(GN.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:Kpo(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof eje)return{type:"api_error",statusCode:t.status};if(t instanceof ttt){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=HMt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={};(o??this.disableGeoip)&&(a.geoip_disable=!0),s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let u=c.response;return u.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),u.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(GN.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(GN.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(GN.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(GN.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(GN.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=que(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:H3r()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,c=this.disableCompression?null:await j3r(s,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||s};try{await this.fetchWithRetry(a,u)}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:H3r(),uuid:n?.uuid?n.uuid:mEe()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await BIc(t)})}async flush(){let t=afo([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),afo([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(GN.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(GN.Queue)||[]).slice(i.length);this.setPersistedProperty(GN.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:H3r()};this.historicalMigration&&(a.historical_migration=!0);let c=JSON.stringify(a),u=`${this.host}/batch/`,l=this.disableCompression?null:await j3r(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||c},d={retryCheck:f=>TIc(f)?!1:cfo(f)};try{await this.fetchWithRetry(u,p,d)}catch(f){if(TIc(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof ttt||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,CIc)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await SIc(async()=>{let a=new AbortController,c=i??this.requestTimeout,u=que(()=>a.abort(),c),l=null;try{l=await this.fetch(t,{signal:a.signal,...r})}catch(d){throw new ttt(d)}finally{clearTimeout(u)}if(!(r.mode==="no-cors")&&(l.status<200||l.status>=400))throw new eje(l,s);return l},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(GN.Queue)||[]).length===0||(await this.flush(),r)););}catch(o){if(!cfo(o))throw o;await BIc(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=que(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}finally{clearTimeout(i)}}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var WN={};ee(WN,{DOMExceptionCoercer:()=>ffo,ErrorCoercer:()=>dfo,ErrorEventCoercer:()=>mfo,ErrorPropertiesBuilder:()=>ufo,EventCoercer:()=>Afo,ObjectCoercer:()=>gfo,PrimitiveCoercer:()=>yfo,PromiseRejectionEventCoercer:()=>bfo,ReduceableCache:()=>Efo,StringCoercer:()=>hfo,chromeStackLineParser:()=>lfo,createDefaultStackParser:()=>JId,createStackParser:()=>LIc,geckoStackLineParser:()=>pfo,nodeStackLineParser:()=>NIc,opera10StackLineParser:()=>RIc,opera11StackLineParser:()=>FIc,reverseAndStripFrames:()=>MIc,winjsStackLineParser:()=>DIc});var J3r,OIc,Y3r;function PIc(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Y3r&&r.length===OIc||(OIc=r.length,Y3r=r.reduce((n,i)=>{J3r||(J3r={});let o=J3r[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,J3r[i]=[u,l];break}}}return n},{})),Y3r}var QId=4,ufo=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&Zpo(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:PIc(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=QId){let c=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var KB="?";function ZY(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?KB:r,in_app:!0};return KMt(n)||(o.lineno=n),KMt(i)||(o.colno=i),o}var X3r=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:KB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var jId=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,MId=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,LId=/\((\S*)(?::(\d+))(?::(\d+))\)/,lfo=(e,t)=>{let r=jId.exec(e);if(r){let[,i,o,s]=r;return ZY(t,i,KB,+o,+s)}let n=MId.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=LId.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=X3r(n[1]||KB,n[2]);return ZY(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var UId=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zId=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pfo=(e,t)=>{let r=UId.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=zId.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||KB;return[o,i]=X3r(o,i),ZY(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var VId=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,DIc=(e,t)=>{let r=VId.exec(e);return r?ZY(t,r[2],r[1]||KB,+r[3],r[4]?+r[4]:void 0):void 0};var qId=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,RIc=(e,t)=>{let r=qId.exec(e);return r?ZY(t,r[2],r[3]||KB,+r[1]):void 0},GId=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,FIc=(e,t)=>{let r=GId.exec(e);return r?ZY(t,r[5],r[3]||r[4]||KB,+r[1],+r[2]):void 0};var WId=/^\s*[-]{4,}$/,$Id=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,NIc=(e,t)=>{let r=e.match($Id);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||KB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:kIc(r[3]),colno:kIc(r[4]),in_app:HId(c||"",u),platform:t}}if(e.match(WId))return{filename:e,platform:t}};function HId(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function kIc(e){return parseInt(e||"",10)||void 0}var QIc=/\(error: (.*)\)/,jIc=50;function MIc(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,jIc).map(r=>({...r,filename:r.filename||KId(t).filename,function:r.function||KB}))}function KId(e){return e[e.length-1]||{}}function JId(){return LIc("web:javascript",lfo,pfo)}function LIc(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
1739
|
-
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=QIc.test(a)?a.replace(QIc,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=jIc)break}}return MIc(i)}}var ffo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=JMt(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return ZQe(t,"DOMException")}isDOMError(t){return ZQe(t,"DOMError")}};var dfo=class{match(t){return tfo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var mfo=class{constructor(){}match(t){return dIc(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var YId=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,hfo=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(YId);return i&&(r=i[1],n=i[2]),[r,n]}};var UIc=["fatal","error","warning","log","info","debug"];function Z3r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var gfo=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Xet(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Z3r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return JMt(t)&&!pIc(t)&&UIc.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(_Ic(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Afo=class{match(t){return Xet(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Z3r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var yfo=class{match(t){return U3r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var bfo=class{match(t){return ZQe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xet(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return U3r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var Efo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var qIc=require("fs"),GIc=require("readline"),e4r=new WN.ReduceableCache(25),WIc=new WN.ReduceableCache(20),Ifo=7,XId=1e3,ZId=1e4;async function $Ic(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||nvd(s)||ivd(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(WIc.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=svd(o);if(s.every(c=>ovd(i,c)))continue;let a=avd(e4r,i,{});n.push(evd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&tvd(e,e4r),e4r.reduce(),e}function evd(e,t,r){return new Promise(n=>{let i=(0,qIc.createReadStream)(e),o=(0,GIc.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){WIc.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=cvd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function tvd(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;rvd(r.lineno,r,n)}}function rvd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=HIc(e);i<e;i++){let o=r[i];if(o===void 0)return void zIc(t);t.pre_context.push(o)}if(r[e]===void 0)return void zIc(t);t.context_line=r[e];let n=KIc(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function zIc(e){delete e.pre_context,delete e.context_line,delete e.post_context}function nvd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ivd(e){return e.lineno!==void 0&&e.lineno>ZId||e.colno!==void 0&&e.colno>XId}function ovd(e,t){let r=e4r.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function svd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=VIc(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+Ifo:(i.push(n),n=VIc(o)),t++}return i}function VIc(e){return[HIc(e),KIc(e)]}function HIc(e){return Math.max(1,e-Ifo)}function KIc(e){return e+Ifo}function avd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function cvd(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function uvd(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function JIc(e,t){globalThis.process?.on("uncaughtException",uvd(e,t))}function YIc(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var lvd=2e3,n9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new z3r({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return efo(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(JIc(this.onException.bind(this),this.onFatalError.bind(this)),YIc(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(lvd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var XIc="5.29.1";var e6t={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function ZIc(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var pvd=6e4,fvd=1152921504606847e3,dvd=["is_not"],rtt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},xd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},eX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},t4r=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof eX||u instanceof xd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof eX||u instanceof xd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new xd("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new xd("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new xd(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new xd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new xd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new xd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new xd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new xd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new xd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new xd(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof eX)throw l;if(l instanceof xd)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new xd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?ivc(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):nvc(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await evc(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await evc(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(pvd,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rtt(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new rtt(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rtt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof rtt&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=que(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function evc(e,t,r=""){let n=await ZIc(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/fvd}function nvc(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new xd("Operator is_not_set is not supported")}else throw new xd(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!dvd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return tvc(String(i))&&String(s).match(String(i))!==null;case"not_regex":return tvc(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new xd("Date operations cannot be performed on boolean values");let u=yvd(String(i));if(u==null&&(u=rvc(i)),u==null)throw new xd(`Invalid date: ${i}`);let l=rvc(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return KU(JB(String(s)),JB(String(i)))===0;case"semver_neq":return KU(JB(String(s)),JB(String(i)))!==0;case"semver_gt":return KU(JB(String(s)),JB(String(i)))>0;case"semver_gte":return KU(JB(String(s)),JB(String(i)))>=0;case"semver_lt":return KU(JB(String(s)),JB(String(i)))<0;case"semver_lte":return KU(JB(String(s)),JB(String(i)))<=0;case"semver_tilde":{let u=JB(String(s)),{lower:l,upper:p}=hvd(String(i));return KU(u,l)>=0&&KU(u,p)<0}case"semver_caret":{let u=JB(String(s)),{lower:l,upper:p}=gvd(String(i));return KU(u,l)>=0&&KU(u,p)<0}case"semver_wildcard":{let u=JB(String(s)),{lower:l,upper:p}=Avd(String(i));return KU(u,l)>=0&&KU(u,p)<0}default:throw new xd(`Unknown operator: ${o}`)}}function mvd(e,t){if(!(e in t))throw new eX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function ivc(e,t,r,n=!1){let i=String(e.value);mvd(i,r);let o=r[i];return ovc(o,t,r,n)}function ovc(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=ovc(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof eX)throw c;if(c instanceof xd)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new xd("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=ivc(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=nvc(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof eX)throw c;if(c instanceof xd)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new xd("can't match cohort without a given cohort property value");return i==="AND"}function tvc(e){try{return new RegExp(e),!0}catch{return!1}}function JB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new xd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new xd(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function KU(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function hvd(e){let t=JB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function gvd(e){let t=JB(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Avd(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new xd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new xd(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new xd(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function rvc(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new xd(`${e} is in an invalid date format`)}throw new xd(`The date provided ${e} must be a string, number, or date object`)}function yvd(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var r4r=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var bvd=100,svc=3e4,Evd=5e4,Ivd=50,vvd=500,n4r=class extends ZMt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new r4r,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,bvd):svc,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new t4r({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new n9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Evd}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??vvd,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Ivd;this._waitUntilCycle.timer=que(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return XIc}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=svc){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let B=this._flagOverrides[t];if(B===void 0)return;let O=this._payloadOverrides?.[t];return{key:t,enabled:B!==!1,variant:typeof B=="string"?B:void 0,payload:O}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,A,b,v,x,C;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let B=this.featureFlagsPoller?.featureFlagsByKey[t];if(B)try{let O=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(B,d,{matchValue:i});if(O){m=!0;let F=O.value;v=B.id,C="Evaluated locally",f={key:t,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:O.payload??void 0}}}catch(O){if(O instanceof eX||O instanceof xd)this._logger?.info(`${O.name} when computing flag locally: ${t}: ${O.message}`);else throw O}}if(!m&&!c){let B=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(B===void 0)b=e6t.UNKNOWN_ERROR;else{h=B.requestId,A=B.evaluatedAt;let O=[];B.errorsWhileComputingFlags&&O.push(e6t.ERRORS_WHILE_COMPUTING),B.quotaLimited?.includes("feature_flags")&&O.push(e6t.QUOTA_LIMITED);let F=B.flags[t];if(F===void 0)O.push(e6t.FLAG_MISSING);else{v=F.metadata?.id,x=F.metadata?.version,C=F.reason?.description??F.reason?.code;let T;if(F.metadata?.payload!==void 0)try{T=JSON.parse(F.metadata.payload)}catch{T=F.metadata.payload}f={key:t,enabled:F.enabled,variant:F.variant,payload:T}}O.length>0&&(b=O.join(","))}}if(o){let B=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,O=`${t}_${B}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(O)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(O):this.distinctIdHasSentFlagCalls[r]=[O];let F={$feature_flag:t,$feature_flag_response:B,$feature_flag_id:v,$feature_flag_version:x,$feature_flag_reason:C,locally_evaluated:m,[`$feature/${t}`]:B,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();T!==void 0&&(F.$feature_flag_definitions_loaded_at=T)}b&&(F.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:F,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},A=!0;if(f&&(m=f.response,h=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...b.flags||{}},h={...h,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=que(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(mIc(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!n9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(n9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!n9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(n9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=mEe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let A={};if(h)for(let[v,x]of Object.entries(h))A[`$feature/${v}`]=x;let b=Object.keys(h||{}).filter(v=>h?.[v]!==!1).sort();return b.length>0&&(A.$active_feature_flags=b),A}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&uIc(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var avc=require("async_hooks"),i4r=class{constructor(){this.storage=new avc.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var cvc="posthog-node";function Cvd(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[vfo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var vfo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=cvc,this.name=cvc,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Cvd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};n9.errorPropertiesBuilder=new WN.ErrorPropertiesBuilder([new WN.EventCoercer,new WN.ErrorCoercer,new WN.ObjectCoercer,new WN.StringCoercer,new WN.PrimitiveCoercer],WN.createStackParser("node:javascript",WN.nodeStackLineParser),[iIc(),$Ic]);var hEe=class extends n4r{getLibraryId(){return"posthog-node"}initializeContext(){return new i4r}};var o4r=class{posthog;constructor({posthogApiKey:t}){this.posthog=new hEe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.86.0",usingAccessToken:!0}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var t6t=class{async sendEvent(){}async identify(){}async flush(){}};Jt();var ntt=require("fs/promises"),uvc=require("os"),lvc=require("path");var xvd="id",wvd=".fern",r6t=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new hEe(r),this.userId=t==null?void 0:Moo(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"4.86.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Cf({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=$e($t.of((0,uvc.homedir)()),Te.of(wvd),Te.of(xvd));await cr(t)||(await(0,ntt.mkdir)((0,lvc.dirname)(t),{recursive:!0}),await(0,ntt.writeFile)(t,ZS())),this.persistedDistinctId=(await(0,ntt.readFile)(t)).toString()}return this.persistedDistinctId}};var Cfo;async function n6t(){return Cfo==null&&(Cfo=await Svd()),Cfo}async function Svd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new t6t;let r=await gNr();return r!=null?new r6t({token:r,posthogApiKey:e}):await NY()!=null?new o4r({posthogApiKey:e}):new r6t({token:void 0,posthogApiKey:e})}catch{return new t6t}}Rt();var i6t=Ie(require("process"),1);OVe();var dvc=Ie(zJi(),1),mvc=Ie(fvc(),1);function A_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=M5(e),e.length===0))return 0;e=e.replace((0,mvc.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(dvc.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function s4r(e){let t=0;for(let r of e.split(`
|
|
1739
|
+
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=QIc.test(a)?a.replace(QIc,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=jIc)break}}return MIc(i)}}var ffo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=JMt(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return ZQe(t,"DOMException")}isDOMError(t){return ZQe(t,"DOMError")}};var dfo=class{match(t){return tfo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var mfo=class{constructor(){}match(t){return dIc(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var YId=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,hfo=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(YId);return i&&(r=i[1],n=i[2]),[r,n]}};var UIc=["fatal","error","warning","log","info","debug"];function Z3r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var gfo=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Xet(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Z3r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return JMt(t)&&!pIc(t)&&UIc.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(_Ic(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Afo=class{match(t){return Xet(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Z3r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var yfo=class{match(t){return U3r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var bfo=class{match(t){return ZQe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xet(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return U3r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var Efo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var qIc=require("fs"),GIc=require("readline"),e4r=new WN.ReduceableCache(25),WIc=new WN.ReduceableCache(20),Ifo=7,XId=1e3,ZId=1e4;async function $Ic(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||nvd(s)||ivd(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(WIc.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=svd(o);if(s.every(c=>ovd(i,c)))continue;let a=avd(e4r,i,{});n.push(evd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&tvd(e,e4r),e4r.reduce(),e}function evd(e,t,r){return new Promise(n=>{let i=(0,qIc.createReadStream)(e),o=(0,GIc.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){WIc.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=cvd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function tvd(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;rvd(r.lineno,r,n)}}function rvd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=HIc(e);i<e;i++){let o=r[i];if(o===void 0)return void zIc(t);t.pre_context.push(o)}if(r[e]===void 0)return void zIc(t);t.context_line=r[e];let n=KIc(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function zIc(e){delete e.pre_context,delete e.context_line,delete e.post_context}function nvd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ivd(e){return e.lineno!==void 0&&e.lineno>ZId||e.colno!==void 0&&e.colno>XId}function ovd(e,t){let r=e4r.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function svd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=VIc(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+Ifo:(i.push(n),n=VIc(o)),t++}return i}function VIc(e){return[HIc(e),KIc(e)]}function HIc(e){return Math.max(1,e-Ifo)}function KIc(e){return e+Ifo}function avd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function cvd(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function uvd(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function JIc(e,t){globalThis.process?.on("uncaughtException",uvd(e,t))}function YIc(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var lvd=2e3,n9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new z3r({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return efo(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(JIc(this.onException.bind(this),this.onFatalError.bind(this)),YIc(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(lvd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var XIc="5.29.1";var e6t={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function ZIc(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var pvd=6e4,fvd=1152921504606847e3,dvd=["is_not"],rtt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},xd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},eX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},t4r=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof eX||u instanceof xd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof eX||u instanceof xd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new xd("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new xd("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new xd(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new xd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new xd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new xd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new xd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new xd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new xd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new xd(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof eX)throw l;if(l instanceof xd)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new xd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?ivc(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):nvc(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await evc(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await evc(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(pvd,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rtt(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new rtt(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rtt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof rtt&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=que(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function evc(e,t,r=""){let n=await ZIc(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/fvd}function nvc(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new xd("Operator is_not_set is not supported")}else throw new xd(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!dvd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return tvc(String(i))&&String(s).match(String(i))!==null;case"not_regex":return tvc(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new xd("Date operations cannot be performed on boolean values");let u=yvd(String(i));if(u==null&&(u=rvc(i)),u==null)throw new xd(`Invalid date: ${i}`);let l=rvc(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return KU(JB(String(s)),JB(String(i)))===0;case"semver_neq":return KU(JB(String(s)),JB(String(i)))!==0;case"semver_gt":return KU(JB(String(s)),JB(String(i)))>0;case"semver_gte":return KU(JB(String(s)),JB(String(i)))>=0;case"semver_lt":return KU(JB(String(s)),JB(String(i)))<0;case"semver_lte":return KU(JB(String(s)),JB(String(i)))<=0;case"semver_tilde":{let u=JB(String(s)),{lower:l,upper:p}=hvd(String(i));return KU(u,l)>=0&&KU(u,p)<0}case"semver_caret":{let u=JB(String(s)),{lower:l,upper:p}=gvd(String(i));return KU(u,l)>=0&&KU(u,p)<0}case"semver_wildcard":{let u=JB(String(s)),{lower:l,upper:p}=Avd(String(i));return KU(u,l)>=0&&KU(u,p)<0}default:throw new xd(`Unknown operator: ${o}`)}}function mvd(e,t){if(!(e in t))throw new eX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function ivc(e,t,r,n=!1){let i=String(e.value);mvd(i,r);let o=r[i];return ovc(o,t,r,n)}function ovc(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=ovc(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof eX)throw c;if(c instanceof xd)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new xd("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=ivc(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=nvc(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof eX)throw c;if(c instanceof xd)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new xd("can't match cohort without a given cohort property value");return i==="AND"}function tvc(e){try{return new RegExp(e),!0}catch{return!1}}function JB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new xd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new xd(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function KU(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function hvd(e){let t=JB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function gvd(e){let t=JB(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Avd(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new xd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new xd(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new xd(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function rvc(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new xd(`${e} is in an invalid date format`)}throw new xd(`The date provided ${e} must be a string, number, or date object`)}function yvd(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var r4r=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var bvd=100,svc=3e4,Evd=5e4,Ivd=50,vvd=500,n4r=class extends ZMt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new r4r,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,bvd):svc,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new t4r({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new n9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Evd}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??vvd,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Ivd;this._waitUntilCycle.timer=que(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return XIc}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=svc){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let B=this._flagOverrides[t];if(B===void 0)return;let O=this._payloadOverrides?.[t];return{key:t,enabled:B!==!1,variant:typeof B=="string"?B:void 0,payload:O}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,A,b,v,x,C;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let B=this.featureFlagsPoller?.featureFlagsByKey[t];if(B)try{let O=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(B,d,{matchValue:i});if(O){m=!0;let F=O.value;v=B.id,C="Evaluated locally",f={key:t,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:O.payload??void 0}}}catch(O){if(O instanceof eX||O instanceof xd)this._logger?.info(`${O.name} when computing flag locally: ${t}: ${O.message}`);else throw O}}if(!m&&!c){let B=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(B===void 0)b=e6t.UNKNOWN_ERROR;else{h=B.requestId,A=B.evaluatedAt;let O=[];B.errorsWhileComputingFlags&&O.push(e6t.ERRORS_WHILE_COMPUTING),B.quotaLimited?.includes("feature_flags")&&O.push(e6t.QUOTA_LIMITED);let F=B.flags[t];if(F===void 0)O.push(e6t.FLAG_MISSING);else{v=F.metadata?.id,x=F.metadata?.version,C=F.reason?.description??F.reason?.code;let T;if(F.metadata?.payload!==void 0)try{T=JSON.parse(F.metadata.payload)}catch{T=F.metadata.payload}f={key:t,enabled:F.enabled,variant:F.variant,payload:T}}O.length>0&&(b=O.join(","))}}if(o){let B=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,O=`${t}_${B}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(O)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(O):this.distinctIdHasSentFlagCalls[r]=[O];let F={$feature_flag:t,$feature_flag_response:B,$feature_flag_id:v,$feature_flag_version:x,$feature_flag_reason:C,locally_evaluated:m,[`$feature/${t}`]:B,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();T!==void 0&&(F.$feature_flag_definitions_loaded_at=T)}b&&(F.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:F,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},A=!0;if(f&&(m=f.response,h=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...b.flags||{}},h={...h,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=que(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(mIc(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!n9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(n9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!n9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(n9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=mEe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let A={};if(h)for(let[v,x]of Object.entries(h))A[`$feature/${v}`]=x;let b=Object.keys(h||{}).filter(v=>h?.[v]!==!1).sort();return b.length>0&&(A.$active_feature_flags=b),A}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&uIc(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var avc=require("async_hooks"),i4r=class{constructor(){this.storage=new avc.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var cvc="posthog-node";function Cvd(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[vfo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var vfo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=cvc,this.name=cvc,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Cvd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};n9.errorPropertiesBuilder=new WN.ErrorPropertiesBuilder([new WN.EventCoercer,new WN.ErrorCoercer,new WN.ObjectCoercer,new WN.StringCoercer,new WN.PrimitiveCoercer],WN.createStackParser("node:javascript",WN.nodeStackLineParser),[iIc(),$Ic]);var hEe=class extends n4r{getLibraryId(){return"posthog-node"}initializeContext(){return new i4r}};var o4r=class{posthog;constructor({posthogApiKey:t}){this.posthog=new hEe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.86.1",usingAccessToken:!0}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var t6t=class{async sendEvent(){}async identify(){}async flush(){}};Jt();var ntt=require("fs/promises"),uvc=require("os"),lvc=require("path");var xvd="id",wvd=".fern",r6t=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new hEe(r),this.userId=t==null?void 0:Moo(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"4.86.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Cf({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=$e($t.of((0,uvc.homedir)()),Te.of(wvd),Te.of(xvd));await cr(t)||(await(0,ntt.mkdir)((0,lvc.dirname)(t),{recursive:!0}),await(0,ntt.writeFile)(t,ZS())),this.persistedDistinctId=(await(0,ntt.readFile)(t)).toString()}return this.persistedDistinctId}};var Cfo;async function n6t(){return Cfo==null&&(Cfo=await Svd()),Cfo}async function Svd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new t6t;let r=await gNr();return r!=null?new r6t({token:r,posthogApiKey:e}):await NY()!=null?new o4r({posthogApiKey:e}):new r6t({token:void 0,posthogApiKey:e})}catch{return new t6t}}Rt();var i6t=Ie(require("process"),1);OVe();var dvc=Ie(zJi(),1),mvc=Ie(fvc(),1);function A_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=M5(e),e.length===0))return 0;e=e.replace((0,mvc.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(dvc.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function s4r(e){let t=0;for(let r of e.split(`
|
|
1740
1740
|
`))t=Math.max(t,A_(r));return t}var Fvc=Ie(wfo(),1);var Bvd=/[\p{Lu}]/u,Tvd=/[\p{Ll}]/u,Avc=/^[\p{Lu}](?![\p{Lu}])/gu,Evc=/([\p{Alpha}\p{N}_]|$)/u,Sfo=/[_.\- ]+/,Ovd=new RegExp("^"+Sfo.source),yvc=new RegExp(Sfo.source+Evc.source,"gu"),bvc=new RegExp("\\d+"+Evc.source,"gu"),Pvd=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&Bvd.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Tvd.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},Dvd=(e,t)=>(Avc.lastIndex=0,e.replace(Avc,r=>t(r))),Rvd=(e,t)=>(yvc.lastIndex=0,bvc.lastIndex=0,e.replace(yvc,(r,n)=>t(n)).replace(bvc,r=>t(r)));function _fo(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?Sfo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Pvd(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Ovd,""),e=t.preserveConsecutiveUppercase?Dvd(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Rvd(e,n))}var Pfo=Ie(vvc(),1);OVe();var Cvc=(e=0)=>t=>`\x1B[${t+e}m`,xvc=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,wvc=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,mb={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Y_b=Object.keys(mb.modifier),Qvd=Object.keys(mb.color),jvd=Object.keys(mb.bgColor),X_b=[...Qvd,...jvd];function Mvd(){let e=new Map;for(let[t,r]of Object.entries(mb)){for(let[n,i]of Object.entries(r))mb[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=mb[n],e.set(i[0],i[1]);Object.defineProperty(mb,t,{value:r,enumerable:!1})}return Object.defineProperty(mb,"codes",{value:e,enumerable:!1}),mb.color.close="\x1B[39m",mb.bgColor.close="\x1B[49m",mb.color.ansi=Cvc(),mb.color.ansi256=xvc(),mb.color.ansi16m=wvc(),mb.bgColor.ansi=Cvc(10),mb.bgColor.ansi256=xvc(10),mb.bgColor.ansi16m=wvc(10),Object.defineProperties(mb,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>mb.rgbToAnsi256(...mb.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>mb.ansi256ToAnsi(mb.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>mb.ansi256ToAnsi(mb.hexToAnsi256(t)),enumerable:!1}}),mb}var Lvd=Mvd(),Svc=Lvd;var a4r=new Set(["\x1B","\x9B"]),Uvd=39,Tfo="\x07",Tvc="[",zvd="]",Ovc="m",Ofo=`${zvd}8;;`,_vc=e=>`${a4r.values().next().value}${Tvc}${e}${Ovc}`,Bvc=e=>`${a4r.values().next().value}${Ofo}${e}${Tfo}`,Vvd=e=>e.split(" ").map(t=>A_(t)),Bfo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=A_(M5(e[e.length-1]));for(let[a,c]of n.entries()){let u=A_(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),a4r.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(Ofo)),i){o?c===Tfo&&(i=!1,o=!1):c===Ovc&&(i=!1);continue}s+=u,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},qvd=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(A_(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Gvd=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=Vvd(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=A_(a[a.length-1]);if(u!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),Bfo(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){Bfo(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){Bfo(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>qvd(u)));let c=[...a.join(`
|
|
1741
1741
|
`)];for(let[u,l]of c.entries()){if(n+=l,a4r.has(l)){let{groups:d}=new RegExp(`(?:\\${Tvc}(?<code>\\d+)m|\\${Ofo}(?<uri>.*)${Tfo})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Uvd?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=Svc.codes.get(Number(i));c[u+1]===`
|
|
1742
1742
|
`?(o&&(n+=Bvc("")),i&&p&&(n+=_vc(p))):l===`
|
|
@@ -2255,7 +2255,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
|
|
|
2255
2255
|
`)}var q4t=class{cwd;logger;deleteOriginals;constructor(t){this.cwd=t.cwd,this.logger=t.logger,this.deleteOriginals=t.deleteOriginals??!0}async migrate(){let t=[],r=[],n=await this.findFernDirectory();if(n==null)return{success:!1,warnings:[{type:"conflict",message:"Could not find fern directory",suggestion:"Run this command from a directory containing a 'fern' folder"}],migratedFiles:r};let o=await new V4t({cwd:n}).migrate();if(t.push(...o.warnings),!o.success||o.org==null)return{success:!1,warnings:[...t,{type:"conflict",message:"Failed to migrate fern.config.json - organization is required"}],migratedFiles:r};o.absoluteFilePath!=null&&r.push(o.absoluteFilePath);let s=$e(n,Te.of(xR)),a=await cr(s,"directory"),c;if(a){let d=await this.migrateMultiApi({fernDir:n,apisDir:s,org:o.org,warnings:t,migratedFiles:r});if(!d.success)return{success:!1,warnings:t,migratedFiles:r};c=d.fernYml}else{let d=await this.migrateSingleApi({fernDir:n,org:o.org,warnings:t,migratedFiles:r});if(!d.success)return{success:!1,warnings:t,migratedFiles:r};c=d.fernYml}let u=await $1o(n);u.docsRef!=null&&(c.docs=u.docsRef);let l=$e(this.cwd,Te.of(Qv)),p=this.serializeFernYml(c);if(await(0,Mmt.writeFile)(l,p,"utf-8"),this.deleteOriginals)for(let d of r)try{await(0,Mmt.rm)(d),this.logger.debug(`Deleted ${d}`)}catch{t.push({type:"info",message:`Could not delete ${d}`})}return this.logger.info(`Created ${l}`),t.push(...await H1o(this.cwd)),{success:!0,warnings:t,migratedFiles:r,outputPath:l}}async migrateSingleApi(t){let{fernDir:r,org:n,warnings:i,migratedFiles:o}=t,a=await new GMe({cwd:r}).migrate();i.push(...a.warnings),a.absoluteFilePath!=null&&o.push(a.absoluteFilePath);let c=await G1o({fernDir:r,generatorsYmlApi:a.rawApi});i.push(...c.warnings);let u={org:n};return c.api!=null&&(u.api=c.api),a.sdks!=null&&(u.sdks=a.sdks),{success:!0,fernYml:u}}async migrateMultiApi(t){let{fernDir:r,apisDir:n,org:i,warnings:o,migratedFiles:s}=t,c=(await(0,Mmt.readdir)(n,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>A.name);if(c.length===0)return o.push({type:"conflict",message:"No API directories found in fern/apis/"}),{success:!1,fernYml:{org:i}};let u={},l={targets:{}},p;for(let A of c){let b=$e(n,Te.of(A)),x=await new GMe({cwd:b,apiName:A}).migrate();if(o.push(...x.warnings),x.absoluteFilePath!=null&&s.push(x.absoluteFilePath),u[A]=x.rawApi,x.sdks!=null){for(let[C,w]of Object.entries(x.sdks.targets))l.targets[C]=w;x.sdks.autorelease!=null&&p==null&&(p=x.sdks.autorelease)}}let d=await W1o({fernDir:r,apisDir:n,generatorsYmlApis:u});o.push(...d.warnings);let f={org:i,apis:d.apis};Object.keys(l.targets).length>0&&(p!=null&&(l.autorelease=p),f.sdks=l);let h=await new GMe({cwd:r}).detect();return h.found&&h.absoluteFilePath!=null&&(o.push({type:"info",message:"Found generators.yml in fern root alongside apis/ directory",suggestion:"Review the migrated configuration to ensure it's correct"}),s.push(h.absoluteFilePath)),{success:!0,fernYml:f}}async findFernDirectory(){if(this.cwd.split("/").pop()===xA)return this.cwd;let r=$e(this.cwd,Te.of(xA));if(await cr(r,"directory"))return r}serializeFernYml(t){let r={edition:t.edition,org:t.org};return t.api!=null&&(r.api=t.api),t.apis!=null&&(r.apis=t.apis),t.ai!=null&&(r.ai=t.ai),t.cli!=null&&(r.cli=t.cli),t.docs!=null&&(r.docs=t.docs),t.sdks!=null&&(r.sdks=this.simplifySdks(t.sdks)),Tr.dump(r,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1})}simplifySdks(t){let r={...t},n={};for(let[i,o]of Object.entries(t.targets)){let s=o.output;if(typeof s=="string"){n[i]=o;continue}if(s.git==null&&s.path!=null){n[i]={...o,output:s.path};continue}n[i]=o}return r.targets=n,r}};var K1o=class{async handle(t,r){let i=await new q4t({cwd:t.cwd,logger:t.stdout,deleteOriginals:r.delete}).migrate();for(let o of i.warnings){switch(o.type){case"deprecated":t.stdout.warn(`Deprecated: ${o.message}`);break;case"unsupported":t.stdout.warn(`Unsupported: ${o.message}`);break;case"conflict":t.stderr.error(`Error: ${o.message}`);break;case"info":t.stdout.info(o.message);break}o.suggestion!=null&&t.stdout.info(` Suggestion: ${o.suggestion}`)}if(i.success){i.outputPath!=null&&t.stdout.debug(`Created: ${i.outputPath}`);return}throw new j({message:"Migration failed",code:j.Code.ConfigError})}};function J1o(e){let t=new K1o;Io(e,"migrate","Migrate legacy configuration files to fern.yml",(r,n)=>t.handle(r,n),r=>r.option("delete",{type:"boolean",description:"Keep original files after migration",default:!0}))}function Y1o(e){HE(e,"config","Configure, edit, and inspect your settings",[J1o])}var X1o=class{async handle(t,r){let n=await t.loadWorkspaceOrThrow();if(n.docs==null)throw new j({message:`No docs configuration found in fern.yml.
|
|
2256
2256
|
|
|
2257
2257
|
Add a 'docs:' section to your fern.yml to get started.`,code:j.Code.ConfigError});let o=await new K_e({context:t}).check({workspace:n,strict:r.strict}),s=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let a=this.buildJsonResponse({result:o,hasErrors:s});if(t.stdout.info(JSON.stringify(a,null,2)),s)throw new j({code:j.Code.ValidationError});return}if(o.violations.length>0)for(let a of o.violations){let c=a.severity==="warning"?ve.yellow:ve.red;process.stderr.write(`${c(`${a.displayRelativeFilepath}:${a.line}:${a.column}: ${a.message}`)}
|
|
2258
|
-
`)}if(s)throw new j({code:j.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${In.warning} ${ve.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(ve.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${In.success} ${ve.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>iX(i))),{success:!r,results:n}}};function Z1o(e){let t=new X1o;Io(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var tqc=Ie(require("net"),1),rqc=Ie(require("os"),1),wVn=class extends Error{constructor(t){super(`${t} is locked`)}},Lmt={old:new Set,young:new Set},eem=1e3*15,nqc=new Set;var G4t,tem=()=>{let e=rqc.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},ZVc=e=>new Promise((t,r)=>{let n=tqc.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),eqc=async(e,t)=>{if(e.host||e.port===0)return ZVc(e);for(let r of t)try{await ZVc({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},rem=e=>Lmt.old.has(e)||Lmt.young.has(e)||nqc.has(e),nem=function*(e){e&&(yield*e),yield 0};async function J_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};G4t===void 0&&(G4t=setTimeout(()=>{G4t=void 0,Lmt.old=Lmt.young,Lmt.young=new Set},eem),G4t.unref&&G4t.unref());let o=tem();for(let s of nem(t))try{if(r.has(s))continue;let a=await eqc({...i,port:s},o);for(;rem(a);){if(s!==0)throw new wVn(s);a=await eqc({...i,port:s},o)}return n?nqc.add(a):Lmt.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof wVn))throw a}throw new Error("No available ports found")}var sqc=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,iqc="docs.buildwithfern.com",oqc=62;function WMe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),sqc.test(t)}function aqc(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function W4t({orgId:e,previewId:t}){let r=aqc(t),n=`${e}-preview-${r}.${iqc}`;if(n.length<=oqc)return n;let i=`${e}-preview-`,o=oqc-i.length;if(o<8)throw new j({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:j.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${iqc}`}Rt();Cg();Jt();var LPo=require("child_process"),SZc=Ie(rBo(),1),_Zc=Ie(pqn(),1),UPo=Ie(require("fs"),1),ezt=require("fs/promises"),BZc=Ie(require("http"),1),qPo=Ie(require("path"),1);var oWc=require("events"),gqn=Ie(require("fs"),1),r6e=Ie(require("path"),1);var U9c=Ie(require("os"),1),z9c=300,n1e=20,AUt=1e7,V9c=U9c.default.platform();var yam=V9c==="darwin",ITo=V9c==="win32",i1e=yam||ITo,q9c=3e3,G9c=2e4,vTo=1250;var Wte;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Wte||(Wte={}));var t6e;(function(e){e.CHANGE="change",e.RENAME="rename"})(t6e||(t6e={}));var yUt;(function(e){e.CHANGE="change",e.ERROR="error"})(yUt||(yUt={}));var Oc;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Oc||(Oc={}));var Ek;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Ek||(Ek={}));var bam=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let C=Date.now(),w=C-c,B=C-u,O=w>=t||B>=o;return[C,O]},p=C=>{if(u=C,!s)return;let w=s;s=void 0,e.apply(void 0,w)},d=()=>{v(0)},f=()=>{a&&(d(),p(Date.now()))},m=C=>{if(u=C,n)return p(C)},h=C=>{if(i&&s)return p(C);s=void 0},A=()=>{a=void 0;let[C,w]=l();return w?h(C):b(C)},b=C=>{let w=C-c,B=C-u,O=t-w,F=o-B,T=Math.min(O,F);return v(T)},v=C=>{a&&clearTimeout(a),!(C<=0)&&(a=setTimeout(A,C))},x=(...C)=>{let[w,B]=l(),O=!!a;if(s=C,c=w,(B||!a)&&v(t),B)return O?p(w):m(w)};return x.cancel=d,x.flush=f,x},fqn=bam;var STo=Ie(require("fs"),1),mqn=Ie(require("path"),1);var Sd=Ie(require("fs"),1),lT=require("util");var spe=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},$te=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var CTo=Ie(require("process"),1),W9c=CTo.default.getuid?!CTo.default.getuid():!1,$9c=1e4,ij=()=>{};var bUt={isChangeErrorOk:e=>{if(!bUt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!W9c&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!bUt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!bUt.isNodeError(e))throw e;if(!bUt.isChangeErrorOk(e))throw e}},qv=bUt;var xTo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=$9c,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},H9c=new xTo;var ape=(e,t)=>function(n){return function i(...o){return H9c.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},cpe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var Eam={attempt:{chmod:spe((0,lT.promisify)(Sd.default.chmod),qv.onChangeError),chown:spe((0,lT.promisify)(Sd.default.chown),qv.onChangeError),close:spe((0,lT.promisify)(Sd.default.close),ij),fsync:spe((0,lT.promisify)(Sd.default.fsync),ij),mkdir:spe((0,lT.promisify)(Sd.default.mkdir),ij),realpath:spe((0,lT.promisify)(Sd.default.realpath),ij),stat:spe((0,lT.promisify)(Sd.default.stat),ij),unlink:spe((0,lT.promisify)(Sd.default.unlink),ij),chmodSync:$te(Sd.default.chmodSync,qv.onChangeError),chownSync:$te(Sd.default.chownSync,qv.onChangeError),closeSync:$te(Sd.default.closeSync,ij),existsSync:$te(Sd.default.existsSync,ij),fsyncSync:$te(Sd.default.fsync,ij),mkdirSync:$te(Sd.default.mkdirSync,ij),realpathSync:$te(Sd.default.realpathSync,ij),statSync:$te(Sd.default.statSync,ij),unlinkSync:$te(Sd.default.unlinkSync,ij)},retry:{close:ape((0,lT.promisify)(Sd.default.close),qv.isRetriableError),fsync:ape((0,lT.promisify)(Sd.default.fsync),qv.isRetriableError),open:ape((0,lT.promisify)(Sd.default.open),qv.isRetriableError),readFile:ape((0,lT.promisify)(Sd.default.readFile),qv.isRetriableError),rename:ape((0,lT.promisify)(Sd.default.rename),qv.isRetriableError),stat:ape((0,lT.promisify)(Sd.default.stat),qv.isRetriableError),write:ape((0,lT.promisify)(Sd.default.write),qv.isRetriableError),writeFile:ape((0,lT.promisify)(Sd.default.writeFile),qv.isRetriableError),closeSync:cpe(Sd.default.closeSync,qv.isRetriableError),fsyncSync:cpe(Sd.default.fsyncSync,qv.isRetriableError),openSync:cpe(Sd.default.openSync,qv.isRetriableError),readFileSync:cpe(Sd.default.readFileSync,qv.isRetriableError),renameSync:cpe(Sd.default.renameSync,qv.isRetriableError),statSync:cpe(Sd.default.statSync,qv.isRetriableError),writeSync:cpe(Sd.default.writeSync,qv.isRetriableError),writeFileSync:cpe(Sd.default.writeFileSync,qv.isRetriableError)}},K9c=Eam;var dqn=Ie(require("fs"),1),EUt=Ie(require("path"),1);var wTo=()=>{};var Iam=()=>{let e=wTo,t=wTo,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},J9c=Iam;var vam=()=>{let{promise:e,resolve:t,isPending:r}=J9c(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},Y9c=vam;var X9c={then:e=>{e()}};var Z9c=e=>Array.isArray(e)?e:[e],eWc=e=>typeof e=="function";var Cam=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=Z9c(o).map(ne=>eWc(ne)?ne:ie=>ne.test(ie)),a=ne=>s.some(ie=>ie(ne)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},A=[],b=new Set,v={},x={},C=new Set,w={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},B={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:A,symlinksNames:b,symlinksNamesToPaths:v,map:x},{promise:O,increment:F,decrement:T}=Y9c(),V=0,K=(ne,ie,xe,Ee)=>{C.has(ie)||V>=i||(V+=1,ne.directories.push(ie),ne.directoriesNames.add(xe),l.push(ie),p.add(xe),d.propertyIsEnumerable(xe)||(d[xe]=[]),d[xe].push(ie),C.add(ie),!(Ee>=n)&&(V>=i||me(ie,Ee+1)))},Z=(ne,ie,xe)=>{C.has(ie)||V>=i||(V+=1,ne.files.push(ie),ne.filesNames.add(xe),f.push(ie),m.add(xe),h.propertyIsEnumerable(xe)||(h[xe]=[]),h[xe].push(ie),C.add(ie))},Y=(ne,ie,xe,Ee)=>{C.has(ie)||V>=i||(V+=1,ne.symlinks.push(ie),ne.symlinksNames.add(xe),A.push(ie),b.add(xe),v.propertyIsEnumerable(xe)||(v[xe]=[]),v[xe].push(ie),C.add(ie),r&&(Ee>=n||V>=i||Pe(ie,Ee+1)))},le=(ne,ie,xe,Ee,Oe)=>{c.aborted||a(ie)||(Ee.isDirectory()?K(ne,ie,xe,Oe):Ee.isFile()?Z(ne,ie,xe):Ee.isSymbolicLink()&&Y(ne,ie,xe,Oe))},Ae=(ne,ie,xe,Ee)=>{if(c.aborted)return;let Oe=ie===EUt.default.sep?"":EUt.default.sep,je=xe.name,Je=`${ie}${Oe}${je}`;a(Je)||(xe.isDirectory()?K(ne,Je,je,Ee):xe.isFile()?Z(ne,Je,je):xe.isSymbolicLink()&&Y(ne,Je,je,Ee))},ae=(ne,ie,xe,Ee)=>{for(let Oe=0,je=xe.length;Oe<je;Oe++)Ae(ne,ie,xe[Oe],Ee)},me=(ne,ie)=>{c.aborted||ie>n||V>=i||(F(),dqn.default.readdir(ne,{withFileTypes:!0},(xe,Ee)=>{if(xe||c.aborted||!Ee.length)return T();(u(Ee)||X9c).then(()=>{let je=x[ne]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ae(je,ne,Ee,ie),T()})}))},Pe=(ne,ie)=>{F(),dqn.default.realpath(ne,(xe,Ee)=>{if(xe||c.aborted)return T();dqn.default.stat(Ee,(Oe,je)=>{if(Oe||c.aborted)return T();let Je=EUt.default.basename(Ee),nt=x[ne]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};le(nt,Ee,Je,je,ie),T()})})};return(async(ne,ie=1)=>(ne=EUt.default.normalize(ne),C.add(ne),me(ne,ie),await O,c.aborted?w:B))(e)},tWc=Cam;var Hte={lang:{debounce:fqn,attempt:e=>{try{return e()}catch(t){return Hte.lang.castError(t)}},castArray:e=>Hte.lang.isArray(e)?e:[e],castError:e=>Hte.lang.isError(e)?e:Hte.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Hte.lang.isNaN(e))return Hte.lang.isNaN(t);if(Hte.lang.isPrimitive(e)||Hte.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(mqn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?STo.default.realpathSync.native(e):STo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===mqn.default.sep&&t.length-e.length>mqn.default.sep.length,poll:(e,t=G9c)=>K9c.retry.stat(t)(e,{bigint:!0}).catch(Hte.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await tWc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Xl=Hte;var hqn=Ie(require("path"),1);var _To=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Xl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=z9c){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Xl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Oc.CHANGE&&a===Oc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===Oc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Oc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??n1e:Math.min(1,this.options.depth??n1e),s=this.options.limit??AUt,[a,c]=await Xl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Xl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Oc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!i1e&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Oc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Oc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(hqn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Oc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(hqn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Oc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Oc.ADD?this.onTargetAdd(n):r===Oc.ADD_DIR?this.onTargetAddDir(n):r===Oc.CHANGE?this.onTargetChange(n):r===Oc.UNLINK?this.onTargetUnlink(n):r===Oc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=t6e.CHANGE,r){if(this.watcher.isClosed())return;let n=hqn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){ITo&&t.code==="EPERM"?this.onWatcherChange(t6e.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(yUt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(yUt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(t6e.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&i1e&&this.options.native!==!1?this.options.depth??n1e:Math.min(1,this.options.depth??n1e),n=this.options.limit??AUt,[i,o]=await Xl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(t6e.CHANGE,a,t)}))}}},rWc=_To;var Ik={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ik.intervalId||(Ik.intervalId=setInterval(Ik.resolve,Ik.interval))},reset:()=>{Ik.intervalId&&(clearInterval(Ik.intervalId),delete Ik.intervalId)},add:(e,t)=>{Ik.fns.set(e,Date.now()+t),Ik.init()},remove:e=>{Ik.fns.delete(e)},resolve:()=>{if(!Ik.fns.size)return Ik.reset();let e=Date.now();for(let[t,r]of Ik.fns)r>=e||(Ik.remove(t),t())}},IUt=Ik;var vUt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=vTo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Xl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),IUt.remove(u)},u=()=>{c(),a()};IUt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=vTo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),IUt.remove(u)},u=()=>{c(),a()};IUt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Oc.ADD,Wte.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Oc.ADD_DIR,Wte.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Oc.UNLINK,Wte.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Oc.UNLINK_DIR,Wte.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};vUt.DIR_EVENTS={add:Oc.ADD_DIR,rename:Oc.RENAME_DIR,unlink:Oc.UNLINK_DIR};vUt.FILE_EVENTS={add:Oc.ADD,change:Oc.CHANGE,rename:Oc.RENAME,unlink:Oc.UNLINK};var nWc=vUt;var BTo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Xl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Xl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Xl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Xl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Xl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Xl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},TTo=BTo;var OTo=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},iWc=OTo;var PTo=class{constructor(){this.inos={},this.paths=new TTo,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Xl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new iWc(n)}reset(){this.inos={},this.paths=new TTo,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Oc.ADD,i),[Oc.ADD];if(i.isDirectory())return this.updateIno(t,Oc.ADD_DIR,i),[Oc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Oc.UNLINK,n),[Oc.UNLINK];if(n.isDirectory())return this.updateIno(t,Oc.UNLINK_DIR,n),[Oc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Oc.CHANGE,i),[Oc.CHANGE]);if(i.isDirectory())return this.updateIno(t,Oc.UNLINK,n),this.updateIno(t,Oc.ADD_DIR,i),[Oc.UNLINK,Oc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Oc.UNLINK_DIR,n),this.updateIno(t,Oc.ADD,i),[Oc.UNLINK_DIR,Oc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Oc.UNLINK_DIR,n),this.updateIno(t,Oc.ADD_DIR,i),[Oc.UNLINK_DIR,Oc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?Wte.FILE:Wte.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},DTo=PTo;var RTo=class e extends oWc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Ek.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(Ek.CLOSE,i)),this._readyWait=new Promise(i=>this.on(Ek.READY,i)),this._locker=new nWc(this),this._roots=new Set,this._poller=new DTo,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Xl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Ek.CLOSE))}error(t){if(this.isClosed())return!1;let r=Xl.lang.castError(t);return this.emit(Ek.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(Ek.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Ek.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Xl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Xl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Xl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new rWc(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Xl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=r6e.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??n1e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&i1e&&l.options.native!==!1)))return!0;if(!i1e)break;let u=r6e.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Xl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||i1e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:gqn.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=r6e.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||i1e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??n1e,a=r.limit??AUt,[c]=await Xl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Xl.fs.getDepth(t);for(let p of c){let d=Xl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(Ek.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(Ek.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=r6e.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new DTo,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Xl.lang.noop;if(this.pollerExists(t,r))return Xl.lang.noop;let i={...r,interval:r.pollingInterval??q9c},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(Ek.CLOSE,a),gqn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(Ek.CLOSE,a),gqn.default.unwatchFile(t,n)};return Xl.lang.attempt(s),()=>Xl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Xl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Xl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=r6e.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Xl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=r6e.default.dirname(t);return(await Xl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Xl.lang.noop){if(Xl.lang.isFunction(t))return this.watch([],{},t);if(Xl.lang.isUndefined(t))return this.watch([],r,n);if(Xl.lang.isFunction(r))return this.watch(t,{},r);if(Xl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Xl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Xl.lang.noop&&this.on(Ek.ALL,n),r.readdirMap=void 0,this.ready())}},Aqn=RTo;Dqn();Jt();var LV=require("fs/promises"),l$c=require("os"),rOo=Ie(require("path"),1),Kcm=".fern",Jcm="logs",tOo=100*1024*1024;function Ycm(){return"cli@4.86.0"}var c6e=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t){if(this.initialized)return;this.consoleLogger=t;let r=$e($t.of((0,l$c.homedir)()),Te.of(Kcm)),n=$e(r,Te.of(Jcm));await cr(n)||await(0,LV.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=$e(n,Te.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${rOo.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2258
|
+
`)}if(s)throw new j({code:j.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${In.warning} ${ve.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(ve.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${In.success} ${ve.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>iX(i))),{success:!r,results:n}}};function Z1o(e){let t=new X1o;Io(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var tqc=Ie(require("net"),1),rqc=Ie(require("os"),1),wVn=class extends Error{constructor(t){super(`${t} is locked`)}},Lmt={old:new Set,young:new Set},eem=1e3*15,nqc=new Set;var G4t,tem=()=>{let e=rqc.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},ZVc=e=>new Promise((t,r)=>{let n=tqc.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),eqc=async(e,t)=>{if(e.host||e.port===0)return ZVc(e);for(let r of t)try{await ZVc({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},rem=e=>Lmt.old.has(e)||Lmt.young.has(e)||nqc.has(e),nem=function*(e){e&&(yield*e),yield 0};async function J_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};G4t===void 0&&(G4t=setTimeout(()=>{G4t=void 0,Lmt.old=Lmt.young,Lmt.young=new Set},eem),G4t.unref&&G4t.unref());let o=tem();for(let s of nem(t))try{if(r.has(s))continue;let a=await eqc({...i,port:s},o);for(;rem(a);){if(s!==0)throw new wVn(s);a=await eqc({...i,port:s},o)}return n?nqc.add(a):Lmt.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof wVn))throw a}throw new Error("No available ports found")}var sqc=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,iqc="docs.buildwithfern.com",oqc=62;function WMe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),sqc.test(t)}function aqc(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function W4t({orgId:e,previewId:t}){let r=aqc(t),n=`${e}-preview-${r}.${iqc}`;if(n.length<=oqc)return n;let i=`${e}-preview-`,o=oqc-i.length;if(o<8)throw new j({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:j.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${iqc}`}Rt();Cg();Jt();var LPo=require("child_process"),SZc=Ie(rBo(),1),_Zc=Ie(pqn(),1),UPo=Ie(require("fs"),1),ezt=require("fs/promises"),BZc=Ie(require("http"),1),qPo=Ie(require("path"),1);var oWc=require("events"),gqn=Ie(require("fs"),1),r6e=Ie(require("path"),1);var U9c=Ie(require("os"),1),z9c=300,n1e=20,AUt=1e7,V9c=U9c.default.platform();var yam=V9c==="darwin",ITo=V9c==="win32",i1e=yam||ITo,q9c=3e3,G9c=2e4,vTo=1250;var Wte;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Wte||(Wte={}));var t6e;(function(e){e.CHANGE="change",e.RENAME="rename"})(t6e||(t6e={}));var yUt;(function(e){e.CHANGE="change",e.ERROR="error"})(yUt||(yUt={}));var Oc;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Oc||(Oc={}));var Ek;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Ek||(Ek={}));var bam=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let C=Date.now(),w=C-c,B=C-u,O=w>=t||B>=o;return[C,O]},p=C=>{if(u=C,!s)return;let w=s;s=void 0,e.apply(void 0,w)},d=()=>{v(0)},f=()=>{a&&(d(),p(Date.now()))},m=C=>{if(u=C,n)return p(C)},h=C=>{if(i&&s)return p(C);s=void 0},A=()=>{a=void 0;let[C,w]=l();return w?h(C):b(C)},b=C=>{let w=C-c,B=C-u,O=t-w,F=o-B,T=Math.min(O,F);return v(T)},v=C=>{a&&clearTimeout(a),!(C<=0)&&(a=setTimeout(A,C))},x=(...C)=>{let[w,B]=l(),O=!!a;if(s=C,c=w,(B||!a)&&v(t),B)return O?p(w):m(w)};return x.cancel=d,x.flush=f,x},fqn=bam;var STo=Ie(require("fs"),1),mqn=Ie(require("path"),1);var Sd=Ie(require("fs"),1),lT=require("util");var spe=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},$te=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var CTo=Ie(require("process"),1),W9c=CTo.default.getuid?!CTo.default.getuid():!1,$9c=1e4,ij=()=>{};var bUt={isChangeErrorOk:e=>{if(!bUt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!W9c&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!bUt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!bUt.isNodeError(e))throw e;if(!bUt.isChangeErrorOk(e))throw e}},qv=bUt;var xTo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=$9c,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},H9c=new xTo;var ape=(e,t)=>function(n){return function i(...o){return H9c.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},cpe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var Eam={attempt:{chmod:spe((0,lT.promisify)(Sd.default.chmod),qv.onChangeError),chown:spe((0,lT.promisify)(Sd.default.chown),qv.onChangeError),close:spe((0,lT.promisify)(Sd.default.close),ij),fsync:spe((0,lT.promisify)(Sd.default.fsync),ij),mkdir:spe((0,lT.promisify)(Sd.default.mkdir),ij),realpath:spe((0,lT.promisify)(Sd.default.realpath),ij),stat:spe((0,lT.promisify)(Sd.default.stat),ij),unlink:spe((0,lT.promisify)(Sd.default.unlink),ij),chmodSync:$te(Sd.default.chmodSync,qv.onChangeError),chownSync:$te(Sd.default.chownSync,qv.onChangeError),closeSync:$te(Sd.default.closeSync,ij),existsSync:$te(Sd.default.existsSync,ij),fsyncSync:$te(Sd.default.fsync,ij),mkdirSync:$te(Sd.default.mkdirSync,ij),realpathSync:$te(Sd.default.realpathSync,ij),statSync:$te(Sd.default.statSync,ij),unlinkSync:$te(Sd.default.unlinkSync,ij)},retry:{close:ape((0,lT.promisify)(Sd.default.close),qv.isRetriableError),fsync:ape((0,lT.promisify)(Sd.default.fsync),qv.isRetriableError),open:ape((0,lT.promisify)(Sd.default.open),qv.isRetriableError),readFile:ape((0,lT.promisify)(Sd.default.readFile),qv.isRetriableError),rename:ape((0,lT.promisify)(Sd.default.rename),qv.isRetriableError),stat:ape((0,lT.promisify)(Sd.default.stat),qv.isRetriableError),write:ape((0,lT.promisify)(Sd.default.write),qv.isRetriableError),writeFile:ape((0,lT.promisify)(Sd.default.writeFile),qv.isRetriableError),closeSync:cpe(Sd.default.closeSync,qv.isRetriableError),fsyncSync:cpe(Sd.default.fsyncSync,qv.isRetriableError),openSync:cpe(Sd.default.openSync,qv.isRetriableError),readFileSync:cpe(Sd.default.readFileSync,qv.isRetriableError),renameSync:cpe(Sd.default.renameSync,qv.isRetriableError),statSync:cpe(Sd.default.statSync,qv.isRetriableError),writeSync:cpe(Sd.default.writeSync,qv.isRetriableError),writeFileSync:cpe(Sd.default.writeFileSync,qv.isRetriableError)}},K9c=Eam;var dqn=Ie(require("fs"),1),EUt=Ie(require("path"),1);var wTo=()=>{};var Iam=()=>{let e=wTo,t=wTo,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},J9c=Iam;var vam=()=>{let{promise:e,resolve:t,isPending:r}=J9c(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},Y9c=vam;var X9c={then:e=>{e()}};var Z9c=e=>Array.isArray(e)?e:[e],eWc=e=>typeof e=="function";var Cam=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=Z9c(o).map(ne=>eWc(ne)?ne:ie=>ne.test(ie)),a=ne=>s.some(ie=>ie(ne)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},A=[],b=new Set,v={},x={},C=new Set,w={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},B={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:A,symlinksNames:b,symlinksNamesToPaths:v,map:x},{promise:O,increment:F,decrement:T}=Y9c(),V=0,K=(ne,ie,xe,Ee)=>{C.has(ie)||V>=i||(V+=1,ne.directories.push(ie),ne.directoriesNames.add(xe),l.push(ie),p.add(xe),d.propertyIsEnumerable(xe)||(d[xe]=[]),d[xe].push(ie),C.add(ie),!(Ee>=n)&&(V>=i||me(ie,Ee+1)))},Z=(ne,ie,xe)=>{C.has(ie)||V>=i||(V+=1,ne.files.push(ie),ne.filesNames.add(xe),f.push(ie),m.add(xe),h.propertyIsEnumerable(xe)||(h[xe]=[]),h[xe].push(ie),C.add(ie))},Y=(ne,ie,xe,Ee)=>{C.has(ie)||V>=i||(V+=1,ne.symlinks.push(ie),ne.symlinksNames.add(xe),A.push(ie),b.add(xe),v.propertyIsEnumerable(xe)||(v[xe]=[]),v[xe].push(ie),C.add(ie),r&&(Ee>=n||V>=i||Pe(ie,Ee+1)))},le=(ne,ie,xe,Ee,Oe)=>{c.aborted||a(ie)||(Ee.isDirectory()?K(ne,ie,xe,Oe):Ee.isFile()?Z(ne,ie,xe):Ee.isSymbolicLink()&&Y(ne,ie,xe,Oe))},Ae=(ne,ie,xe,Ee)=>{if(c.aborted)return;let Oe=ie===EUt.default.sep?"":EUt.default.sep,je=xe.name,Je=`${ie}${Oe}${je}`;a(Je)||(xe.isDirectory()?K(ne,Je,je,Ee):xe.isFile()?Z(ne,Je,je):xe.isSymbolicLink()&&Y(ne,Je,je,Ee))},ae=(ne,ie,xe,Ee)=>{for(let Oe=0,je=xe.length;Oe<je;Oe++)Ae(ne,ie,xe[Oe],Ee)},me=(ne,ie)=>{c.aborted||ie>n||V>=i||(F(),dqn.default.readdir(ne,{withFileTypes:!0},(xe,Ee)=>{if(xe||c.aborted||!Ee.length)return T();(u(Ee)||X9c).then(()=>{let je=x[ne]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ae(je,ne,Ee,ie),T()})}))},Pe=(ne,ie)=>{F(),dqn.default.realpath(ne,(xe,Ee)=>{if(xe||c.aborted)return T();dqn.default.stat(Ee,(Oe,je)=>{if(Oe||c.aborted)return T();let Je=EUt.default.basename(Ee),nt=x[ne]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};le(nt,Ee,Je,je,ie),T()})})};return(async(ne,ie=1)=>(ne=EUt.default.normalize(ne),C.add(ne),me(ne,ie),await O,c.aborted?w:B))(e)},tWc=Cam;var Hte={lang:{debounce:fqn,attempt:e=>{try{return e()}catch(t){return Hte.lang.castError(t)}},castArray:e=>Hte.lang.isArray(e)?e:[e],castError:e=>Hte.lang.isError(e)?e:Hte.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Hte.lang.isNaN(e))return Hte.lang.isNaN(t);if(Hte.lang.isPrimitive(e)||Hte.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(mqn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?STo.default.realpathSync.native(e):STo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===mqn.default.sep&&t.length-e.length>mqn.default.sep.length,poll:(e,t=G9c)=>K9c.retry.stat(t)(e,{bigint:!0}).catch(Hte.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await tWc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Xl=Hte;var hqn=Ie(require("path"),1);var _To=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Xl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=z9c){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Xl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Oc.CHANGE&&a===Oc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===Oc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Oc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??n1e:Math.min(1,this.options.depth??n1e),s=this.options.limit??AUt,[a,c]=await Xl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Xl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Oc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!i1e&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Oc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Oc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(hqn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Oc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(hqn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Oc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Oc.ADD?this.onTargetAdd(n):r===Oc.ADD_DIR?this.onTargetAddDir(n):r===Oc.CHANGE?this.onTargetChange(n):r===Oc.UNLINK?this.onTargetUnlink(n):r===Oc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=t6e.CHANGE,r){if(this.watcher.isClosed())return;let n=hqn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){ITo&&t.code==="EPERM"?this.onWatcherChange(t6e.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(yUt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(yUt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(t6e.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&i1e&&this.options.native!==!1?this.options.depth??n1e:Math.min(1,this.options.depth??n1e),n=this.options.limit??AUt,[i,o]=await Xl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(t6e.CHANGE,a,t)}))}}},rWc=_To;var Ik={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ik.intervalId||(Ik.intervalId=setInterval(Ik.resolve,Ik.interval))},reset:()=>{Ik.intervalId&&(clearInterval(Ik.intervalId),delete Ik.intervalId)},add:(e,t)=>{Ik.fns.set(e,Date.now()+t),Ik.init()},remove:e=>{Ik.fns.delete(e)},resolve:()=>{if(!Ik.fns.size)return Ik.reset();let e=Date.now();for(let[t,r]of Ik.fns)r>=e||(Ik.remove(t),t())}},IUt=Ik;var vUt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=vTo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Xl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),IUt.remove(u)},u=()=>{c(),a()};IUt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=vTo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),IUt.remove(u)},u=()=>{c(),a()};IUt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Oc.ADD,Wte.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Oc.ADD_DIR,Wte.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Oc.UNLINK,Wte.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Oc.UNLINK_DIR,Wte.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};vUt.DIR_EVENTS={add:Oc.ADD_DIR,rename:Oc.RENAME_DIR,unlink:Oc.UNLINK_DIR};vUt.FILE_EVENTS={add:Oc.ADD,change:Oc.CHANGE,rename:Oc.RENAME,unlink:Oc.UNLINK};var nWc=vUt;var BTo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Xl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Xl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Xl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Xl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Xl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Xl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},TTo=BTo;var OTo=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},iWc=OTo;var PTo=class{constructor(){this.inos={},this.paths=new TTo,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Xl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new iWc(n)}reset(){this.inos={},this.paths=new TTo,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Oc.ADD,i),[Oc.ADD];if(i.isDirectory())return this.updateIno(t,Oc.ADD_DIR,i),[Oc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Oc.UNLINK,n),[Oc.UNLINK];if(n.isDirectory())return this.updateIno(t,Oc.UNLINK_DIR,n),[Oc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Oc.CHANGE,i),[Oc.CHANGE]);if(i.isDirectory())return this.updateIno(t,Oc.UNLINK,n),this.updateIno(t,Oc.ADD_DIR,i),[Oc.UNLINK,Oc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Oc.UNLINK_DIR,n),this.updateIno(t,Oc.ADD,i),[Oc.UNLINK_DIR,Oc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Oc.UNLINK_DIR,n),this.updateIno(t,Oc.ADD_DIR,i),[Oc.UNLINK_DIR,Oc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?Wte.FILE:Wte.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},DTo=PTo;var RTo=class e extends oWc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Ek.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(Ek.CLOSE,i)),this._readyWait=new Promise(i=>this.on(Ek.READY,i)),this._locker=new nWc(this),this._roots=new Set,this._poller=new DTo,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Xl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Ek.CLOSE))}error(t){if(this.isClosed())return!1;let r=Xl.lang.castError(t);return this.emit(Ek.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(Ek.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Ek.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Xl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Xl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Xl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new rWc(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Xl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=r6e.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??n1e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&i1e&&l.options.native!==!1)))return!0;if(!i1e)break;let u=r6e.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Xl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||i1e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:gqn.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=r6e.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||i1e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??n1e,a=r.limit??AUt,[c]=await Xl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Xl.fs.getDepth(t);for(let p of c){let d=Xl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(Ek.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(Ek.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=r6e.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new DTo,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Xl.lang.noop;if(this.pollerExists(t,r))return Xl.lang.noop;let i={...r,interval:r.pollingInterval??q9c},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(Ek.CLOSE,a),gqn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(Ek.CLOSE,a),gqn.default.unwatchFile(t,n)};return Xl.lang.attempt(s),()=>Xl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Xl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Xl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=r6e.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Xl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=r6e.default.dirname(t);return(await Xl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Xl.lang.noop){if(Xl.lang.isFunction(t))return this.watch([],{},t);if(Xl.lang.isUndefined(t))return this.watch([],r,n);if(Xl.lang.isFunction(r))return this.watch(t,{},r);if(Xl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Xl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Xl.lang.noop&&this.on(Ek.ALL,n),r.readdirMap=void 0,this.ready())}},Aqn=RTo;Dqn();Jt();var LV=require("fs/promises"),l$c=require("os"),rOo=Ie(require("path"),1),Kcm=".fern",Jcm="logs",tOo=100*1024*1024;function Ycm(){return"cli@4.86.1"}var c6e=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t){if(this.initialized)return;this.consoleLogger=t;let r=$e($t.of((0,l$c.homedir)()),Te.of(Kcm)),n=$e(r,Te.of(Jcm));await cr(n)||await(0,LV.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=$e(n,Te.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${rOo.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2259
2259
|
`);await(0,LV.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
2260
2260
|
`;try{await(0,LV.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:Ycm(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}async enforceLogSizeLimit(t){try{let n=(await(0,LV.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=rOo.default.join(t,c);try{let l=await(0,LV.stat)(u);i.push({name:c,fullPath:u,size:l.size,mtimeMs:l.mtimeMs})}catch{}}let o=i.reduce((c,u)=>c+u.size,0),s=Math.round(o/1024/1024*100)/100,a=tOo/1024/1024;if(o<=tOo){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,u)=>c.mtimeMs-u.mtimeMs);for(let c of i){if(o<=tOo)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,LV.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var nOo={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function p$c(e){let t=Xcm();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i}=e,o=new Map;function s(c){let u=JSON.stringify(c),l=[];for(let[p]of o)try{p.send(u)}catch{l.push(p)}for(let p of l){let d=o.get(p);d&&(clearInterval(d.pingInterval),o.delete(p))}}let a=t.serve({port:r,fetch(c,u){if(c.method==="OPTIONS")return new Response(null,{status:204,headers:nOo});let l=new URL(c.url);if(c.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(c,{data:{connectionId:`${Date.now()}`}});return}if(c.method==="POST"&&l.pathname==="/v2/registry/docs/load-with-url")return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...nOo}});let p=/^\/_local\/(.*)/.exec(l.pathname);return c.method==="GET"&&p!=null?new Response(t.file(`/${p[1]}`),{headers:nOo}):new Response("Not Found",{status:404})},websocket:{open(c){let{connectionId:u}=c.data,l=setInterval(()=>{let p=o.get(c);if(!p)return;let d=Date.now();if(d-p.lastPong>9e4){c.close();return}try{c.send(JSON.stringify({type:"ping",timestamp:d}))}catch{c.close()}},3e4);o.set(c,{pingInterval:l,lastPong:Date.now()});try{c.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(c,u){try{let l=JSON.parse(u.toString());if(l.type==="pong"){let p=o.get(c);p&&(p.lastPong=Date.now())}else c6e.isMetricsMessage(l)&&n.logFrontendMetrics(l)}catch{}},close(c){let u=o.get(c);u&&(clearInterval(u.pingInterval),o.delete(c))}}});return{sendData:s,stop:c=>a.stop(c)}}function Xcm(){return globalThis.Bun}Jt();var dZc=require("child_process"),G5n=Ie(fOo(),1),mZc=Ie(wPo(),1),Ck=require("fs"),oj=require("fs/promises"),hZc=require("os"),rW=Ie(require("path"),1),gZc=Ie(nS(),1),AZc=Ie(fZc(),1),A6e=process.platform==="win32",q5n=ve.cyan("[docs]:"),Bdm="etag",Tdm=23,NPo=e=>e.padEnd(Tdm," "),Odm="preview",Pdm="app-preview",Ddm="bundle",Rdm=".next",Fdm="standalone",kdm=".fern",Ndm="packages/fern-docs/bundle/.next/server/instrumentation.js",Qdm='Cannot find matching keyid: {"signatures":';function jdm(e){try{let r=(0,dZc.execSync)('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem" /v LongPathsEnabled',{encoding:"utf-8",timeout:5e3}).match(/LongPathsEnabled\s+REG_DWORD\s+0x(\d+)/i);if(r!=null&&r[1]==="1")return}catch(t){e.debug(`Registry query for LongPathsEnabled failed: ${t}`)}e.warn(ve.yellow.bold(`
|
|
2261
2261
|
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
@@ -2461,7 +2461,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
|
|
|
2461
2461
|
|
|
2462
2462
|
Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`:r}function $gm(e,t){return t!=null&&t.includes("Invalid authorization token")?"Your authentication token is invalid or expired. Please run 'fern login' to re-authenticate.":`You are not authorized to publish docs under organization '${e}'. Please run 'fern login' to ensure you are logged in with the correct account.
|
|
2463
2463
|
|
|
2464
|
-
Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}function Hgm(e){if(e==null)return{code:void 0,message:void 0};let t=e.body;if(t!=null&&typeof t=="object"){let n=typeof t.code=="string"?t.code:void 0,i=typeof t.message=="string"?t.message:void 0;return{code:n,message:i}}return{code:void 0,message:typeof t=="string"&&t.length>0?t:typeof e.errorMessage=="string"?e.errorMessage:typeof e.message=="string"?e.message:void 0}}function Kgm(e){try{return new URL(fk(e)).pathname}catch{return}}async function Jgm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await Ygm({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let a=(await e.api.register.checkSdkDynamicIrExists({orgId:mn.OrgId(r),apiId:"",irVersions:[]})).existingDynamicIrs??{};if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let c={};for(let[u,l]of Object.entries(a??{}))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function BDo(e){return e.replace(/^https:\/\//,"")}async function Ygm({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package??void 0,explicitVersion:r.typescriptSdk?.version??void 0},{language:"python",snippetName:r.pythonSdk?.package??void 0,explicitVersion:r.pythonSdk?.version??void 0},{language:"java",snippetName:r.javaSdk?.coordinate??void 0,explicitVersion:r.javaSdk?.version??void 0},{language:"go",snippetName:r.goSdk?.githubRepo&&BDo(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version??void 0},{language:"csharp",snippetName:r.csharpSdk?.package??void 0,explicitVersion:r.csharpSdk?.version??void 0},{language:"ruby",snippetName:r.rubySdk?.gem??void 0,explicitVersion:r.rubySdk?.version??void 0},{language:"php",snippetName:r.phpSdk?.package??void 0,explicitVersion:r.phpSdk?.version??void 0},{language:"swift",snippetName:r.swiftSdk?.package??void 0,explicitVersion:r.swiftSdk?.version??void 0},{language:"rust",snippetName:r.rustSdk?.package??void 0,explicitVersion:r.rustSdk?.version??void 0}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion??void 0;a||(a=(await Xgm({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function Xgm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=Rn.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.computeSemanticVersion({githubRepository:s,language:o,package:a});return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${u.version} for package "${a}"`),{version:u.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function Zgm({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&BDo(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=y6e({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),c.language==="go"&&l&&(l=BDo(l)),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=Sg({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new gh(r,e),dynamicGeneratorConfig:u}),d=iNe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function eAm({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function tAm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(ve.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function rAm(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function ltu(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var azt=[60*1e3,300*1e3,300*1e3];async function czt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d,deployerAuthor:f}){let m=a&&!n.config.settings?.substituteEnvVars;n.config=JA(n.config,{onError:x=>i.failAndThrow(void 0,x,{code:j.Code.EnvironmentError})},{substituteAsEmpty:m});let h=n.config.instances;if(h.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.",void 0,{code:j.Code.ConfigError});return}if(h.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${h[0]?.url})`,void 0,{code:j.Code.ConfigError});return}let A=h.find(x=>x.url===s)??h[0];if(A==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`,void 0,{code:j.Code.ConfigError});return}let b=[];A.customDomain!=null&&(typeof A.customDomain=="string"?b.push(A.customDomain):Array.isArray(A.customDomain)&&b.push(...A.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${A.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let v;return await i.runInteractiveTask({name:A.url},async()=>{let x=performance.now(),C=()=>atu({docsWorkspace:n,customDomains:b,domain:A.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:A.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:A.audiences?Array.isArray(A.audiences)?A.audiences:[A.audiences]:void 0,docsUrl:A.url,cliVersion:p,ciSource:d,deployerAuthor:f});for(let B=0;;B++)try{v=await C();break}catch(O){if(!(O instanceof Rht)||B>=azt.length){if(O instanceof Rht)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:j.Code.NetworkError});throw O}let F=azt[B]??azt[azt.length-1]??6e4,T=F/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${T} minute${T===1?"":"s"} (attempt ${B+1}/${azt.length})...`),await new Promise(V=>setTimeout(V,F))}let w=performance.now()-x;i.logger.debug(`Docs publishing completed in ${w.toFixed(0)}ms`)}),v}var jGn=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Rg({context:this.context,task:this.task});try{let s=await czt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"4.86.0"});return o.getResult()===Ff.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:oi(s)}}}};Rt();var Fht=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
|
|
2464
|
+
Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}function Hgm(e){if(e==null)return{code:void 0,message:void 0};let t=e.body;if(t!=null&&typeof t=="object"){let n=typeof t.code=="string"?t.code:void 0,i=typeof t.message=="string"?t.message:void 0;return{code:n,message:i}}return{code:void 0,message:typeof t=="string"&&t.length>0?t:typeof e.errorMessage=="string"?e.errorMessage:typeof e.message=="string"?e.message:void 0}}function Kgm(e){try{return new URL(fk(e)).pathname}catch{return}}async function Jgm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await Ygm({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let a=(await e.api.register.checkSdkDynamicIrExists({orgId:mn.OrgId(r),apiId:"",irVersions:[]})).existingDynamicIrs??{};if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let c={};for(let[u,l]of Object.entries(a??{}))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function BDo(e){return e.replace(/^https:\/\//,"")}async function Ygm({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package??void 0,explicitVersion:r.typescriptSdk?.version??void 0},{language:"python",snippetName:r.pythonSdk?.package??void 0,explicitVersion:r.pythonSdk?.version??void 0},{language:"java",snippetName:r.javaSdk?.coordinate??void 0,explicitVersion:r.javaSdk?.version??void 0},{language:"go",snippetName:r.goSdk?.githubRepo&&BDo(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version??void 0},{language:"csharp",snippetName:r.csharpSdk?.package??void 0,explicitVersion:r.csharpSdk?.version??void 0},{language:"ruby",snippetName:r.rubySdk?.gem??void 0,explicitVersion:r.rubySdk?.version??void 0},{language:"php",snippetName:r.phpSdk?.package??void 0,explicitVersion:r.phpSdk?.version??void 0},{language:"swift",snippetName:r.swiftSdk?.package??void 0,explicitVersion:r.swiftSdk?.version??void 0},{language:"rust",snippetName:r.rustSdk?.package??void 0,explicitVersion:r.rustSdk?.version??void 0}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion??void 0;a||(a=(await Xgm({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function Xgm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=Rn.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.computeSemanticVersion({githubRepository:s,language:o,package:a});return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${u.version} for package "${a}"`),{version:u.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function Zgm({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&BDo(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=y6e({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),c.language==="go"&&l&&(l=BDo(l)),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=Sg({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new gh(r,e),dynamicGeneratorConfig:u}),d=iNe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function eAm({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function tAm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(ve.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function rAm(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function ltu(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var azt=[60*1e3,300*1e3,300*1e3];async function czt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d,deployerAuthor:f}){let m=a&&!n.config.settings?.substituteEnvVars;n.config=JA(n.config,{onError:x=>i.failAndThrow(void 0,x,{code:j.Code.EnvironmentError})},{substituteAsEmpty:m});let h=n.config.instances;if(h.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.",void 0,{code:j.Code.ConfigError});return}if(h.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${h[0]?.url})`,void 0,{code:j.Code.ConfigError});return}let A=h.find(x=>x.url===s)??h[0];if(A==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`,void 0,{code:j.Code.ConfigError});return}let b=[];A.customDomain!=null&&(typeof A.customDomain=="string"?b.push(A.customDomain):Array.isArray(A.customDomain)&&b.push(...A.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${A.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let v;return await i.runInteractiveTask({name:A.url},async()=>{let x=performance.now(),C=()=>atu({docsWorkspace:n,customDomains:b,domain:A.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:A.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:A.audiences?Array.isArray(A.audiences)?A.audiences:[A.audiences]:void 0,docsUrl:A.url,cliVersion:p,ciSource:d,deployerAuthor:f});for(let B=0;;B++)try{v=await C();break}catch(O){if(!(O instanceof Rht)||B>=azt.length){if(O instanceof Rht)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:j.Code.NetworkError});throw O}let F=azt[B]??azt[azt.length-1]??6e4,T=F/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${T} minute${T===1?"":"s"} (attempt ${B+1}/${azt.length})...`),await new Promise(V=>setTimeout(V,F))}let w=performance.now()-x;i.logger.debug(`Docs publishing completed in ${w.toFixed(0)}ms`)}),v}var jGn=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Rg({context:this.context,task:this.task});try{let s=await czt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"4.86.1"});return o.getResult()===Ff.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:oi(s)}}}};Rt();var Fht=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
|
|
2465
2465
|
`),this.stream.write(`${ve.cyan("\u25C6")} ${ve.bold(t.title)}
|
|
2466
2466
|
`),t.subtitle!=null&&this.stream.write(` ${ve.dim(t.subtitle)}
|
|
2467
2467
|
`),this.stream.write(`
|
|
@@ -3995,7 +3995,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
3995
3995
|
Run ${ve.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
3996
3996
|
Run ${ve.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),itt(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Qts({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!Rju(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
|
|
3997
3997
|
${await xFh(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+ve.dim(a.currentVersion)+ve.reset(" \u2192 ")+ve.green(a.latestVersion);return i+=`
|
|
3998
|
-
`,n?itt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xFh(e){let r=await new Dju.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new j({message:`Generator ${e} not found`,code:j.Code.InternalError});return r.body.displayName}async function wFh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=x2e(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await WO({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=x2e(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await WO({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await m6({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?rE(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function Nju(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=wN(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function Hni({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await wFh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...Nju(u,c,t.logger));else s.push(...Nju(a.versions,void 0,t.logger))}return s}async function Jfe({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await X_t(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new j({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:j.Code.NetworkError})}}var Qju=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Kni=class e{environment;sentryClient;posthogManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Xn.Info;isLocal;stdoutRedirector=new $ni;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await n6t();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new bNe(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new Wni({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.86.
|
|
3998
|
+
`,n?itt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xFh(e){let r=await new Dju.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new j({message:`Generator ${e} not found`,code:j.Code.InternalError});return r.body.displayName}async function wFh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=x2e(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await WO({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=x2e(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await WO({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function kju({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await m6({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?rE(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function Nju(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=wN(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function Hni({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await wFh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...Nju(u,c,t.logger));else s.push(...Nju(a.versions,void 0,t.logger))}return s}async function Jfe({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await X_t(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new j({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:j.Code.NetworkError})}}var Qju=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Kni=class e{environment;sentryClient;posthogManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Xn.Info;isLocal;stdoutRedirector=new $ni;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await n6t();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new bNe(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new Wni({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.86.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${ve.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Gl}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Gl)&&(Hkt({message:t,error:r,logger:this.logger}),Gni(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
|
|
3999
3999
|
`),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();try{await this.posthogManager.flush()}catch{}await this.sentryClient.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await Fju({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
4000
4000
|
`)||(r+=`
|
|
4001
4001
|
`),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=TAi(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new i7t(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){throw n.failWithoutThrowing(void 0,o),new Gl}finally{n.finish()}return i}instrumentPostHogEvent(t){this.isLocal||this.posthogManager.sendEvent(t)}captureException(t,r){this.sentryClient.captureException(t,r)}logger=U1((t,...r)=>this.log(t,...r));stderr=U1((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=jju(r),i=1+(this.longestWorkspaceName!=null?jju(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=Qju[this.numTasks++%Qju.length],a=ve.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:ve.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Ff.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:t=>{this.instrumentPostHogEvent(t)},shouldBufferLogs:!1,captureException:(t,r)=>{this.sentryClient.captureException(t,r)}}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>L1.indexOf(i.level)>=L1.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===Xn.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await Jfe({cliEnvironment:this.environment,includePreReleases:t}),n=wN(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await Hni({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await kts({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:ve.yellow("?"),style:{answer:i=>ve.cyan(i),message:i=>ve.bold(i),highlight:i=>ve.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
|