fern-api 5.228.0 → 5.228.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 +8 -8
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -293,7 +293,7 @@ GFS4: `),console.error(e)});Y0[oB]||(Jyl=global[oB]||[],Xyl(Y0,Jyl),Y0.close=(fu
|
|
|
293
293
|
Location: ${i.join("-> ")}`),Gr.unknown({nameOverride:p,generatedName:m,title:g,description:A,availability:b,namespace:a,groupName:f,example:void 0})}}function Ccm(e,t,r){if(!t&&r&&e.enum!=null&&e.enum.length===1&&typeof e.enum[0]=="boolean")return e.enum[0]}function xcm(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function bxe(e){if(e.$ref.startsWith(W3e))return e.$ref.replace(W3e,"")}function UNo(e,t,r,n,i){let o=Fr(e,un.TYPE_NAME),s=JA(t,n),a=e.description,c=AC(e),l=bxe(e);if(l==null)throw new T({message:`Invalid schema reference ${JSON.stringify(e)}`,code:T.Code.ReferenceError});return ba.reference({generatedName:s,nameOverride:o,title:void 0,schema:l,description:a??void 0,availability:c,namespace:i.getNamespace(l),groupName:void 0,source:r})}function Scm(e){return e.oneOf==null||e.oneOf.length===0}function qSl(e){return e.allOf==null||e.allOf.length===0}function RVr(e){return e.properties==null||Dh(e.properties)===0}function FVr(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function G5(e,t,r,n){if(e.type==="reference")return Gr.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n});if(e.type==="optional"){let i=G5(e.value,t,r,n);return Gr.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0})}else if(e.type==="nullable"){let i=G5(e.value,t,r,n);return Gr.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0})}else if(e.type==="primitive"&&t!=null&&e.description==null)return Gr.primitive({...e,description:t});return e}function kVr(e){return Mn(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>kVr(t)):e.oneOf!=null?e.oneOf.every(t=>kVr(t)):e.anyOf!=null?e.anyOf.every(t=>kVr(t)):!1}function WSl({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,nameOverride:a,generatedName:c,title:l}){let u=Gr.literal({nameOverride:a,generatedName:c,title:l,value:e,namespace:n,groupName:i,description:o,availability:s});return r&&(u=Gr.nullable({nameOverride:a,generatedName:c,title:l,value:u,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(u=Gr.optional({nameOverride:a,generatedName:c,title:l,value:u,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),u}function ET({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,generatedName:a,nameOverride:c,title:l}){i=typeof i=="string"?[i]:i;let u=Gr.primitive({nameOverride:c,generatedName:a,title:l,schema:e,description:o,availability:s,namespace:n,groupName:i});return r&&(u=Gr.nullable({nameOverride:c,generatedName:a,title:l,value:u,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(u=Gr.optional({nameOverride:c,generatedName:a,title:l,value:u,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),u}function wcm({schemas:e}){let t=new Set;for(let r of e){if(Mn(r))return;if(r.enum!=null&&FVr(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function HSl({schemas:e,context:t}){let r={};for(let n of e){let i=YSl({schema:n,context:t});for(let[o,s]of Object.entries(i)){let a=r[o];a!=null?a[s]=n:r[o]={[s]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length){let o;for(let[s,a]of Object.entries(i)){let l=(Mn(a)?t.resolveSchemaReference(a):a).properties?.[n];if(l!=null&&!Mn(l)&&(Fr(l,un.FERN_DEFAULT)??l.default)===s){o=s;break}}return{discriminant:n,schemas:i,defaultDiscriminantValue:o}}}function YSl({schema:e,context:t}){let r=Mn(e)?t.resolveSchemaReference(e):e;return Tcm({schema:r,context:t})}function Tcm({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=YSl({schema:n,context:t});for(let[o,s]of Object.entries(i??{}))r[o]=s}return r}for(let[n,i]of Object.entries(e.properties??{})){let o=Mn(i)?t.resolveSchemaReference(i):i;o.type==="string"&&o.enum!=null&&FVr(o.enum)&&Ocm(o.enum).length===1&&o.enum[0]!=null&&(r[n]=o.enum[0]);let s=XSl(o,"const");o.type==="string"&&s!=null&&(r[n]=s),n==="type"&&o.example!=null&&(r[n]=o.example)}return r}function Ocm(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function XSl(e,t){let r=e[t];if(r!=null)return r}function Pcm({schema:e,fallbackXmlName:t,logger:r}){let n=lSl({schema:e,logger:r});if(n!=null)return jSl({encodingSchema:n,fallbackXmlName:t})}var W3e,KSl,sR=h(()=>{"use strict";mt();Ic();Bt();xo();yl();M3e();Lu();kNo();uSl();fSl();xVr();hSl();gSl();LUt();SVr();ESl();Hot();NSl();zSl();PVr();MSl();LSl();_Sl();_No();JNo();jNo();YNo();XNo();GNo();zNo();Gte();Gb();W3e="#/components/schemas/",KSl=Vte()});var Yot,ZNo=h(()=>{"use strict";Bt();sR();Gb();Yot=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(W3e))throw new T({message:`Failed to resolve schema reference: ${t.$ref}`,code:T.Code.ReferenceError});let n=t.$ref.substring(W3e.length).split("/"),i=this.document.components;if(i==null||i.schemas==null)throw new T({message:"Document does not have components.schemas.",code:T.Code.ReferenceError});let[o,s,a]=n;if(o==null||o==="")throw new T({message:`${t.$ref} cannot be resolved. No schema key provided.`,code:T.Code.ReferenceError});let c=i.schemas[o];if(c==null)throw new T({message:`Schema "${o}" is undefined in document.components.schemas.`,code:T.Code.ReferenceError});if(Mn(c)&&(c=this.resolveSchemaReference(c)),s==="properties"&&a!=null){let l=c.properties?.[a];if(l==null)throw new T({message:`Property "${a}" not found on "${o}". Full ref: ${t.$ref}`,code:T.Code.ReferenceError});Mn(l)?c=this.resolveSchemaReference(l):c=l}return c}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}getNamespace(t){return this.namespace}}});var jVr,ZSl=h(()=>{"use strict";Bt();ZNo();jVr=class extends Yot{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",n=this.document.components;if(n==null||n.messages==null||!t.$ref.startsWith(r))throw new T({message:`Failed to resolve message reference: ${t.$ref} in v2 components`,code:T.Code.ReferenceError});let i=t.$ref.substring(r.length),o=n.messages[i];if(o==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return o}}});function Xot(e,t,r){let n={};if(e!=null){let o={...t},s=r!=null?o[r]:void 0;return r!=null&&s!=null&&(n[r]=s,delete o[r]),{rootSchemas:n,namespacedSchemas:{[e]:o}}}let i={};for(let[o,s]of Object.entries(t))switch(s.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(s.namespace==null){n[o]=s;continue}let a=s.namespace;i[a]??={},i[a][o]=s;continue}case"oneOf":case"unknown":n[o]=s;continue;default:Ye(s)}return{rootSchemas:n,namespacedSchemas:i}}var zVr=h(()=>{"use strict";mt()});function vxe(e){if(typeof e=="string")return oc.primitive(Po.string(e));if(typeof e=="number")return Number.isInteger(e)?oc.primitive(Po.int(e)):oc.primitive(Po.double(e));if(typeof e=="boolean")return oc.primitive(Po.boolean(e));if(Array.isArray(e)){let t=e.map(r=>vxe(r));return t.length===0?void 0:oc.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=vxe(n);i!=null&&t.push({key:Po.string(r),value:i})}return oc.map(t)}}var QVr=h(()=>{"use strict";Ic()});function qUt(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function $Sl(e){if(e!=null&&Array.isArray(e))return e}var ewl=h(()=>{"use strict"});function twl({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}var Cxe,MVr=h(()=>{"use strict";mt();Ic();Bt();QVr();ewl();Cxe=class e{schemas;nonRequestReferencedSchemas;context;constructor(t,r,n){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=n}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:o}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:o??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:o,options:s,skipReadonly:a}){switch(n.type){case"enum":if(typeof r=="string"&&twl({schema:n,value:r}))return oc.enum(r);if(r!=null){let c=n.values.map(u=>u.value),l=e.truncateExample(r);this.context.logger.debug(`Example value ${l} is not a valid enum value${s.name!=null?` for '${s.name}'`:""}. Allowed values: [${c.join(", ")}]. Using fallback value instead.`)}return n.values[0]!=null?oc.enum(n.values[0]?.value):void 0;case"literal":return oc.literal(n.value);case"nullable":{if(r===null)return oc.null({});if(r==null&&!this.hasExample(n.value,0,o,s)&&this.exceedsMaxDepth(i,s))return oc.null({});let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return c??oc.null({})}case"optional":{if(r==null&&!this.hasExample(n.value,0,o,s)&&(s.ignoreOptionals||this.exceedsMaxDepth(i,s))||Object.is(r,null))return;let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return c!=null&&c.type==="array"&&c.value.length===0||c!=null&&c.type==="map"&&c.value.length===0||c!=null&&c.type==="object"&&Object.keys(c.properties).length===0?void 0:c}case"primitive":{let c=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:s});return oc.primitive(c)}case"reference":{let c=this.schemas[n.schema];if(c!=null&&!o.has(n.schema)){o.add(n.schema);let l=c?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),u=this.buildExampleHelper({example:r,schema:c,exampleId:t,visitedSchemaIds:o,depth:i,options:s,skipReadonly:l||this.context.options.respectReadonlySchemas?a:!1});return o.delete(n.schema),u}return}case"oneOf":switch(n.value.type){case"discriminated":{let c={},l={},u={},p=qUt(r),d=p?.[n.value.discriminantProperty],f=n.value.schemas[d],m=[],g=this.getDiscriminatedUnionVariantSchema(n.value,p);g!=null&&m.push(g),m.push(...Object.entries(n.value.schemas));for(let A of m)if(d!=null&&f!=null&&f.type==="object"){l=this.getAllProperties(f),u=this.getAllRequiredProperties(f),c[n.value.discriminantProperty]=oc.primitive(Po.string(d));break}else{let b=this.buildExampleHelper({exampleId:t,schema:A[1],example:void 0,visitedSchemaIds:o,depth:i,options:s,skipReadonly:a});if(b!=null){this.mergeExampleWith(b,c),c[n.value.discriminantProperty]=oc.primitive(Po.string(A[0]));break}}for(let A of n.value.commonProperties){l[A.key]={schema:A.schema,readonly:!1};let b=this.getResolvedSchema(A.schema);b.type!=="optional"&&b.type!=="nullable"&&(u[A.key]=A.schema)}for(let[A,b]of Object.entries(l)){let I=A in u;if(I&&p?.[A]!=null){let C=this.buildExampleHelper({schema:b.schema,exampleId:t,example:p[A],visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});if(C!=null)c[A]=C;else return}else{let C=this.buildExampleHelper({exampleId:t,schema:b.schema,example:p?.[A],visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});if(C!=null)c[A]=C;else if(I)return}}return oc.oneOf(rxe.discriminated(c))}case"undiscriminated":{let c=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(c!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:c,visitedSchemaIds:o,depth:i,options:s,skipReadonly:a});break}}return;case"unknown":if(r===null)return oc.null({});if(r!=null){let c=vxe(r);if(c!=null)return oc.unknown(c)}return s.ignoreOptionals||this.exceedsMaxDepth(i,s)?void 0:s.isParameter?oc.primitive(Po.string(s.name??"string")):oc.map([{key:Po.string("key"),value:oc.primitive(Po.string("value"))}]);case"array":{let c=$Sl(r),l=[];if(c!=null&&c.length>0)for(let u of c){let p=this.buildExampleHelper({exampleId:t,example:u,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});p!=null&&l.push(p)}else if(n.example!=null&&n.example.length>0)for(let u of n.example){let p=this.buildExampleHelper({exampleId:t,example:u,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});p!=null&&l.push(p)}else{let u=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});u!=null&&l.push(u)}return oc.array(l)}case"map":{let c=qUt(r??n.example);if(c!=null&&Object.entries(c).length>0){let p=[];for(let[d,f]of Object.entries(c)){let m=this.buildExampleFromPrimitive({schema:n.key.schema,example:d,options:s}),g=this.buildExampleHelper({exampleId:t,example:f,schema:n.value,visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});g!=null&&p.push({key:m,value:g})}return oc.map(p)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return oc.map([{key:Po.string("key"),value:oc.unknown(oc.primitive(Po.string("value")))}]);let l=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...s,name:"key"}}),u=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:o,depth:i+1,options:{...s,name:"value"},skipReadonly:a});return u!=null&&u.type!=="null"?oc.map([{key:l,value:u}]):oc.map([])}case"object":{let c={},l=n.fullExamples?.find(f=>f.name===t)??n.fullExamples?.find(f=>f.name==null)??n.fullExamples?.[0],u=qUt(r)??(l!=null?qUt(l.value):{})??{},p=this.getAllProperties(n),d=this.getAllRequiredProperties(n);for(let[f,m]of Object.entries(p)){if(a&&m.readonly||m.schema._visit({optional:S=>typeof S.availability=="string"&&S.availability==="Deprecated",primitive:()=>!1,object:()=>!1,array:()=>!1,map:()=>!1,enum:()=>!1,reference:()=>!1,literal:()=>!1,oneOf:()=>!1,nullable:()=>!1,unknown:()=>!1,_other:()=>!1}))continue;let g=f in d,A=Object.keys(u).includes(f),b=u[f],I=this.getSchemaExample(m.schema),C=A?b:I,x=this.buildExampleHelper({schema:m.schema,exampleId:t,example:C,visitedSchemaIds:o,depth:i+1,options:{...s,name:f},skipReadonly:a});if(g&&x!=null)c[f]=x;else{if(g)return;(A&&x!=null||!s.ignoreOptionals&&x!=null)&&(c[f]=x)}}if(n.additionalProperties){for(let[f,m]of Object.entries(u))if(!(f in c)){let g=this.buildExampleHelper({schema:Gr.unknown({example:m,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:m,visitedSchemaIds:o,depth:i+1,options:{...s,name:f},skipReadonly:a});g!=null&&(c[f]=g)}}return oc.object({properties:c})}default:Ye(n)}}mergeExampleWith(t,r){t._visit({array:xt,enum:xt,literal:xt,map:n=>{for(let i of n){let o=i.key;o.type==="string"&&(r[o.value]=i.value)}},object:n=>{for(let[i,o]of Object.entries(n.properties))r[i]=o},oneOf:n=>{if(n.type==="discriminated")for(let[i,o]of Object.entries(n.value))r[i]=o;else this.mergeExampleWith(n.value,r)},primitive:xt,unknown:xt,null:xt,_other:xt})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){if(r==null){let o=t.schemas.find(a=>this.hasExample(a,0,new Set,{ignoreOptionals:!1,isParameter:!1}));if(o!=null)return o;let s=t.schemas.find(a=>this.hasInherentExample(a));return s??t.schemas[0]}return t.schemas.map(o=>({schema:o,heuristic:this.calcExampleHeuristic(o,r)})).sort((o,s)=>s.heuristic-o.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return twl({schema:t,value:r})?5:0;case"object":{if(!oi(r))return 0;let n=this.getAllProperties(t),i=0;for(let[o,s]of Object.entries(n))r[o]!=null?(i++,i+=this.calcExampleHeuristic(s.schema,r[o])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!oi(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,o)=>o-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",datetimeRfc2822:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let s of t.properties)if(this.hasExample(s.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let o=this.schemas[t.schema];if(o!=null&&!n.has(t.schema)){n.add(t.schema);let s=this.hasExample(o,r,n,i);return n.delete(t.schema),s}return!1}case"unknown":return t.example!=null;case"nullable":case"optional":return this.hasExample(t.value,r,n,i);case"oneOf":return Object.values(t.value.schemas).some(o=>this.hasExample(o,r,n,i));default:return!1}}hasInherentExample(t){switch(t.type){case"literal":return!0;case"enum":return t.values.length>0;case"optional":case"nullable":return this.hasInherentExample(t.value);case"reference":{let r=this.schemas[t.schema];return r!=null?this.hasInherentExample(r):!1}default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let o=this.getResolvedSchema(i);o.type==="object"&&(r={...this.getAllProperties(o),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties)this.getResolvedSchema(n.schema).type!=="optional"&&(r[n.key]=n.schema);for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let o=this.getResolvedSchema(i);o.type==="object"&&(r={...this.getAllRequiredProperties(o),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new T({message:`Unexpected error: Failed to resolve schema reference: ${t.schema}`,code:T.Code.InternalError});t=r}return t}getSchemaExample(t){return t._visit({primitive:r=>r.schema.example,object:r=>r.fullExamples?.[0]?.value,array:r=>r.example,map:r=>r.example,optional:r=>this.getSchemaExample(r.value),enum:r=>r.example,reference:r=>{let n=this.schemas[r.schema];return n!=null?this.getSchemaExample(n):void 0},literal:()=>{},oneOf:()=>{},nullable:r=>this.getSchemaExample(r.value),unknown:r=>r.example,_other:()=>{}})}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?Po.string(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string",schemaType:r.type,options:n}),Po.string(r.example??n.name??Mo.STRING));case"base64":return t!=null&&typeof t=="string"?Po.base64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (base64)",schemaType:r.type,options:n}),Po.base64(r.example??Mo.BASE64));case"boolean":return t!=null&&typeof t=="boolean"?Po.boolean(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"boolean",schemaType:r.type,options:n}),Po.boolean(r.example??Mo.BOOLEAN));case"date":return t!=null&&typeof t=="string"?Po.date(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (date)",schemaType:r.type,options:n}),Po.date(r.example??Mo.DATE));case"datetime":return t!=null&&typeof t=="string"?Po.datetime(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime)",schemaType:r.type,options:n}),Po.datetime(r.example??Mo.DATE_TIME));case"datetimeRfc2822":return t!=null&&typeof t=="string"?Po.datetimeRfc2822(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime RFC 2822)",schemaType:r.type,options:n}),Po.datetimeRfc2822(r.example??Mo.DATE_TIME_RFC_2822));case"double":return t!=null&&typeof t=="number"?Po.double(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (double)",schemaType:r.type,options:n}),Po.double(r.example??Mo.DOUBLE));case"float":return t!=null&&typeof t=="number"?Po.float(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (float)",schemaType:r.type,options:n}),Po.float(r.example??Mo.FLOAT));case"int":return t!=null&&typeof t=="number"?Po.int(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int)",schemaType:r.type,options:n}),Po.int(r.example??Mo.INT));case"int64":return t!=null&&typeof t=="number"?Po.int64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int64)",schemaType:r.type,options:n}),Po.int64(r.example??Mo.INT64));case"uint":return t!=null&&typeof t=="number"?Po.uint(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint)",schemaType:r.type,options:n}),Po.uint(r.example??Mo.UINT));case"uint64":return t!=null&&typeof t=="number"?Po.uint64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint64)",schemaType:r.type,options:n}),Po.uint64(r.example??Mo.UINT64));default:Ye(r)}}warnTypeMismatch({example:t,expected:r,schemaType:n,options:i}){let o=i.name!=null?` for '${i.name}'`:"",s=typeof t,a=e.truncateExample(t);this.context.logger.debug(`Invalid example${o}: expected ${r} but got ${s} (${a}). The provided example does not match the '${n}' schema and will be replaced with a generated value.`)}static truncateExample(t,r=100){let n=JSON.stringify(t);return n.length<=r?n:n.slice(0,r)+"..."}}});function q5(e){switch(e.type){case"object":return Gr.object({allOf:e.allOf,properties:e.properties.map(t=>Dcm(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,encoding:e.encoding,source:e.source,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties,examples:e.examples});case"array":return Gr.array({description:e.description,availability:e.availability,value:q5(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0,minItems:e.minItems,maxItems:e.maxItems,default:e.default});case"enum":return Gr.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Gr.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName});case"nullable":return Gr.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:q5(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Gr.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:q5(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Gr.primitive({description:e.description,availability:e.availability,schema:rwl(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Gr.map({description:e.description,availability:e.availability,key:Gr.primitive({description:e.key.description,availability:e.key.availability,schema:rwl(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:q5(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties});case"reference":return Gr.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Gr.oneOf(Bcm(e.value));case"unknown":return Gr.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,example:void 0,namespace:e.namespace,groupName:e.groupName,description:e.description,availability:e.availability});default:Ye(e)}}function Bcm(e){switch(e.type){case"discriminated":return U_.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:q5(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,discriminantPropertyNameOverride:e.discriminantPropertyNameOverride,discriminatorContext:e.discriminatorContext,defaultDiscriminantValue:e.defaultDiscriminantValue,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,q5(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return U_.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,commonProperties:e.commonProperties?.map(t=>({key:t.key,schema:q5(t.schema)})),schemas:e.schemas.map(t=>q5(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Ye(e)}}function rwl(e){switch(e.type){case"string":return Li.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Li.base64({example:void 0});case"boolean":return Li.boolean({default:e.default,example:void 0});case"date":return Li.date({example:void 0});case"datetime":return Li.datetime({example:void 0});case"datetimeRfc2822":return Li.datetimeRfc2822({example:void 0});case"double":return Li.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Li.float({example:void 0});case"int":return Li.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Li.int64({default:e.default,example:void 0});case"uint":return Li.uint({default:void 0,example:void 0});case"uint64":return Li.uint64({default:void 0,example:void 0});default:Ye(e)}}function Dcm(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,xml:e.xml,schema:q5(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}var nwl=h(()=>{"use strict";mt();Ic()});function LVr(e){return e.type!=="optional"&&e.type!=="nullable"}var $No=h(()=>{"use strict"});function ejo(e){return e==="POST"||e==="PUT"||e==="PATCH"}var iwl=h(()=>{"use strict"});function WUt(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var tjo=h(()=>{"use strict"});function Rcm(e,t){let r=[];if(e.length<=1){let[i,o]=e[0]??[];if(t.length===0)return r.push({id:i,request:o,response:void 0}),r;for(let[s,a]of t)r.push({id:s??i,request:o,response:a});return r}if(t.length<=1){let[i,o]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:o}),r;for(let[s,a]of e)r.push({id:s??i,request:a,response:o});return r}let n=new Set;for(let[i,o]of e){let s=t.find(([c])=>c==null)?.[1]??t[0]?.[1];if(i==null){if(s==null)continue;r.push({id:void 0,request:o,response:s});continue}let a=!1;for(let c=0;c<t.length;c++){let[l,u]=t[c];l==null||n.has(c)||i===l&&(r.push({id:i,request:o,response:u}),l!=null&&n.add(c),a=!0)}!a&&s!=null&&r.push({id:i,request:o,response:s})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[o,s]=t[i],a=e.find(([c])=>c==null)?.[1]??e[0]?.[1];a!=null&&r.push({id:o,request:a,response:s})}return r}function kcm(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:Ncm(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function Fcm(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function TK(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return TK(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return TK(e.value.value);default:return!1}case"null":return!0;default:Ye(e)}}function Ncm(e){return Gr.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:q5(t.schema.value),audiences:[],conflict:{},xml:void 0,generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(gs),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,encoding:void 0,source:e.source,inline:void 0,minProperties:void 0,maxProperties:void 0,examples:void 0})}var Zot,H3e,_Vr,rjo=h(()=>{"use strict";mt();Ic();Zot=Ae(require("fs"),1),H3e=Ae(require("path"),1);MVr();nwl();$No();iwl();tjo();_Vr=class{schemas;context;globalHeaders;exampleTypeFactory;logger;missingExamples=[];constructor(t,r,n){this.schemas=t,this.context=r,this.globalHeaders=n,this.schemas=t,this.exampleTypeFactory=new Cxe(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}addMissingExampleRecord(t,r,n,i,o={}){this.missingExamples.push({endpoint:t.path,method:t.method.toUpperCase(),type:r,schemaType:n,reason:i,operationSummary:t.summary,operationDescription:t.description,schemaDescription:o.schemaDescription,autoGeneratedExample:o.autoGeneratedExample})}writeMissingExamplesLog(){if(this.missingExamples.length===0)return;let t;if(this.context.source.type==="openapi"){let o=this.context.source.file,s=H3e.dirname(o),a=s;for(;a!==H3e.dirname(a);){let c=H3e.join(a,"fern");if(Zot.existsSync(c)&&Zot.statSync(c).isDirectory()){t=c;break}a=H3e.dirname(a)}t||(t=s)}else t=process.cwd();let r=t??process.cwd(),n=H3e.join(r,"schemas_missing_examples.txt"),i=["# Schemas Missing Examples Report",`# Generated on: ${new Date().toISOString()}`,`# Total missing examples: ${this.missingExamples.length}`,"",...this.missingExamples.flatMap(o=>{let s=[];if(s.push(`${o.method} ${o.endpoint} - ${o.type.toUpperCase()} (${o.schemaType}): ${o.reason}`),o.operationSummary&&s.push(` Operation: ${o.operationSummary}`),o.operationDescription&&o.operationDescription!==o.operationSummary&&s.push(` Description: ${o.operationDescription}`),o.schemaDescription&&s.push(` ${o.type==="request"?"Request":"Response"} Schema: ${o.schemaDescription}`),o.autoGeneratedExample){s.push(" Auto-generated example:");let c=JSON.stringify(o.autoGeneratedExample,null,4).split(`
|
|
294
294
|
`).map(l=>` ${l}`).join(`
|
|
295
295
|
`);s.push(c)}return s.push(""),s}),""].join(`
|
|
296
|
-
`);try{Zot.writeFileSync(n,i,"utf8"),this.logger.info(`Missing examples report written to: ${n}`)}catch(o){this.logger.warn(`Failed to write missing examples report to ${n}:`,String(o))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"map":{let r={};return t.value.forEach(n=>{r[String(n.key)]=this.convertExampleToJson(n.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=kcm(t.request),n=Fcm(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let p=this.isSchemaRequired(r.schema);if(r.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:ejo(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});d!=null?(i.push([void 0,d]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:d,value:f}of r.examples){let m=this.exampleTypeFactory.buildExample({skipReadonly:ejo(t.method),schema:r.schema,exampleId:d,example:f,options:{isParameter:!1,ignoreOptionals:!0}});m!=null?i.push([d,m]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(p&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];if(n!=null&&n.type==="present"){let p=this.isSchemaRequired(n.schema);if(n.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});d!=null?(t.response?.type==="json"?o.push([void 0,L5.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,L5.withStreaming({sse:t.response?.type==="streamingSse",events:[d]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(n.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(n.schema)})}else for(let{name:d,value:f}of n.examples){let m=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:d,example:f,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});m!=null?t.response?.type==="json"?o.push([d,L5.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,L5.withStreaming({sse:t.response?.type==="streamingSse",events:[m]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(n.schema)})}if(p&&o.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let s=[];for(let p of t.pathParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for path parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&s.push({name:p.name,parameterNameOverride:p.parameterNameOverride,value:f})}let a=[];for(let p of t.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&f.type!=="array"&&(this.logger.debug(`Expected a primitive or array example but got ${f.type} for query parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&a.push({name:p.name,value:f})}let c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&c.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?q5(p.schema):Gr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Li.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),f=this.exampleTypeFactory.buildExample({schema:d,exampleId:void 0,example:void 0,options:{name:p.header,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),f!=null&&c.push({name:p.header,value:f})}let l=[];t.request!=null&&t.response!=null?l=Rcm(i,o):t.request!=null?l=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(l=o.map(([p,d])=>({id:p,request:void 0,response:d})));let u=t.examples.filter(p=>WUt(p)).flatMap(p=>{if(p.type==="unknown"){if(p.value!=null){let d=p.value["code-samples"];if(d!=null)return this.convertCodeSamples(d)}return}else return p.codeSamples}).filter(p=>gs(p));return l.length===0?[M5.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:void 0,response:void 0,codeSamples:u})]:l.map(({id:p,request:d,response:f})=>M5.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:d,response:f,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?Fte.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):Fte.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?hT.Csharp:r.sdk,code:r.code})).filter(gs)}isSchemaRequired(t){return LVr(this.getResolvedSchema(t))}getResolvedSchema(t){return t}}});var $ot,njo=h(()=>{"use strict";Bt();rjo();sR();MVr();Gb();$No();$ot=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Cxe(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let s=[];for(let a of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let l=[];for(let p of n.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.headers?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(f=void 0),!(d&&f==null)&&f!=null&&l.push({name:p.name,value:f})}let u=[];for(let p of a.messages){let d=t.getExampleMessageReference(p),f=t.resolveMessageReference({$ref:d}),m=Mn(f.payload)?t.resolveSchemaReference(f.payload):f.payload,g=this.exampleTypeFactory.buildExample({schema:Fa(m,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});g!=null&&u.push({messageType:p.type,payload:g,description:void 0})}s.push({name:a.summary,queryParameters:c,headers:l,description:a.description,messages:u})}return s}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let s of t.queryParameters){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!TK(c)&&(c=void 0),a&&c==null)return;c!=null&&i.push({name:s.name,value:c})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!TK(c)&&(c=void 0),a&&c==null)return;c!=null&&o.push({name:s.name,value:c})}for(let s of r){let a=this.exampleTypeFactory.buildExample({schema:s.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});a!=null&&n.messages.push({messageType:s.type,payload:a,description:void 0})}return n}isSchemaRequired(t){return LVr(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new T({message:`Unexpected error: Failed to resolve schema reference: ${t.schema}`,code:T.Code.InternalError});t=r}return t}}});var Ny,UVr=h(()=>{"use strict";Ny={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name",FERN_SERVER_NAME:"x-fern-server-name"}});function VVr(e){return Fr(e,Ny.FERN_EXAMPLES)??[]}var ijo=h(()=>{"use strict";yl();UVr()});function GVr(e,t){return t.includes("://")?t:`${e}://${t}`}function qVr(e){return e.startsWith("/")?e:"/"+e}var ojo=h(()=>{"use strict"});function awl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[l,u]of Object.entries(i.components?.schemas??{})){let p=Fa(u,!1,!1,e,[l],r,e.namespace);o[l]=p}let a=new $ot(o,e),c={};for(let[l,u]of Object.entries(i.servers??{})){let p=Fr(u,Ny.FERN_SERVER_NAME);c[l]={name:p??l,url:GVr(u.protocol,u.url)}}for(let[l,u]of Object.entries(i.channels??{})){let p=Fr(u,Ny.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${l} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(u.parameters!=null)for(let[b,I]of Object.entries(u.parameters??{})){let C=Fr(I,Ny.FERN_PARAMETER_NAME);d.push({name:b,description:I.description,parameterNameOverride:C,schema:I.schema!=null?Fa(I.schema,!1,!1,e,t,r,e.namespace):Gr.primitive({schema:Li.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:AC(I),source:r,explode:void 0,clientDefault:void 0})}let f=[],m=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let b=u.bindings.ws.headers.required??[];for(let[I,C]of Object.entries(u.bindings.ws.headers.properties??{})){if(Mn(C)){let D=e.resolveSchemaReference(C),R=b.includes(I),[O,j]=e.options.coerceOptionalSchemasToNullable?[!1,!R]:[!R,!1];f.push({name:I,schema:V_(C,O,j,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:AC(D),source:r,clientDefault:void 0});continue}let x=b.includes(I),[S,P]=e.options.coerceOptionalSchemasToNullable?[!1,!x]:[!x,!1];f.push({name:I,schema:Fa(C,S,P,e,[...t,I],r,e.namespace),description:C.description,parameterNameOverride:void 0,env:void 0,availability:AC(C),source:r,clientDefault:void 0})}}if(u.bindings.ws.query!=null){let b=u.bindings.ws.query.required??[];for(let[I,C]of Object.entries(u.bindings.ws.query.properties??{})){if(Mn(C)){let D=e.resolveSchemaReference(C),R=b.includes(I),[O,j]=e.options.coerceOptionalSchemasToNullable?[!1,!R]:[!R,!1];m.push({name:I,schema:V_(C,O,j,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:AC(D),source:r,explode:void 0,clientDefault:void 0});continue}let x=b.includes(I),[S,P]=e.options.coerceOptionalSchemasToNullable?[!1,!x]:[!x,!1];m.push({name:I,schema:Fa(C,S,P,e,[...t,I],r,e.namespace),description:C.description,parameterNameOverride:void 0,availability:AC(C),source:r,explode:void 0,clientDefault:void 0})}}}let g;u.publish!=null&&("oneOf"in u.publish.message?g=owl({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=swl({action:"Publish",channelPath:l,message:u.publish.message,context:e,source:r}));let A;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?A=owl({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):A=swl({action:"Subscribe",channelPath:l,message:u.subscribe.message,context:e,source:r})),f.length>0||m.length>0||g!=null||A!=null){let b=VVr(u),I=[];if(b.length>0)I=a.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:b,handshake:{headers:f,queryParameters:m},source:r,namespace:e.namespace});else{let P=[];g!=null&&P.push({type:"publish",payload:g}),A!=null&&P.push({type:"subscribe",payload:A});let D=a.buildWebsocketSessionExample({handshake:{headers:f,queryParameters:m},messages:P});D!=null&&I.push(D)}let C=Fr(u,Ny.FERN_CHANNEL_ADDRESS),x=C??qVr(l),S=[];g!=null&&S.push({origin:"client",name:"publish",displayName:u.publish!=null?Fr(u.publish,Ny.FERN_DISPLAY_NAME):void 0,description:u.publish?.description,body:$f(g),methodName:u.publish!=null?Fr(u.publish,Ny.FERN_SDK_METHOD_NAME):void 0}),A!=null&&S.push({origin:"server",name:"subscribe",displayName:u.subscribe!=null?Fr(u.subscribe,Ny.FERN_DISPLAY_NAME):void 0,description:u.subscribe?.description,body:$f(A),methodName:u.subscribe!=null?Fr(u.subscribe,Ny.FERN_SDK_METHOD_NAME):void 0}),s[l]={audiences:Fr(u,un.AUDIENCES)??[],handshake:{headers:f.map(P=>({...P,schema:$f(P.schema),env:P.env})),queryParameters:m.map(P=>({...P,schema:$f(P.schema)})),pathParameters:d.map(P=>({...P,schema:$f(P.schema)}))},groupName:e.resolveGroupName([Fr(u,Ny.FERN_SDK_GROUP_NAME)??l]),messages:S,servers:(u.servers?.map(P=>c[P])??Object.values(c)).filter(P=>P!=null&&P.name!=null).map(P=>({...P,name:P.name})),summary:Fr(u,Ny.FERN_DISPLAY_NAME),connectMethodName:Fr(u,Ny.FERN_SDK_METHOD_NAME),path:x,description:u.description,examples:I,source:r}}}return{groupedSchemas:Xot(e.namespace,o),channels:s??void 0,servers:Object.values(c).map(l=>({...l,name:l.name})),basePath:Fr(i,Ny.BASE_PATH)}}function owl({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:s}){if("oneOf"in t.message&&t.message.oneOf!=null){let a=[],c=[];for(let l of t.message.oneOf){let u,p={type:"notFound"};if(Mn(l)){let d=r.resolveMessageReference(l);!Mn(d.payload)&&s.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,u={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):u=d.payload}else u=l;c.push(p),a.push(u)}return Ixe({description:t.description??t.message.description,availability:AC(t.message),subtypes:a,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:s.naming==="v2"?c:[]})}}function swl({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return Mn(r.payload)&&(o=n.resolveSchemaReference(r.payload)),Fa(o,!1,!1,n,[t,e],i,n.namespace)}}var cwl=h(()=>{"use strict";Ic();yl();Lu();Hot();sR();JNo();Kot();Gb();zVr();njo();UVr();ijo();ojo()});var WVr,lwl=h(()=>{"use strict";mt();Bt();ZNo();WVr=class extends Yot{getExampleMessageReference(t){let r=t.channelId??this.getDefaultChannelId();if(r==null)throw new T({message:"Cannot resolve example message reference: no channelId provided and no channels found in document",code:T.Code.InternalError});return`#/channels/${r}/messages/${t.messageId}`}getDefaultChannelId(){return Object.keys(this.document.channels??{})[0]}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new T({message:"Cannot resolve message reference: message is null or undefined",code:T.Code.InternalError});if(!t.$ref)throw new T({message:"Cannot resolve message reference: message.$ref is undefined or empty",code:T.Code.ReferenceError});if(t.$ref.startsWith(n)){let c=t.$ref.split("/"),l=c[2],u=c[4],p=l!=null?D0(l):void 0;if(p==null||u==null||!this.document.channels?.[p])throw new T({message:`Failed to resolve message reference ${t.$ref} in channel ${p}`,code:T.Code.ReferenceError});let f=this.document.channels[p].messages?.[u];if(f==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return"$ref"in f&&!r?this.resolveMessageReference(f):{...f,name:u}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new T({message:`Failed to resolve message reference: ${t.$ref} in v3 components`,code:T.Code.ReferenceError});let s=t.$ref.substring(i.length),a=o.messages[s];if(a==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return{...a,name:s}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}}});function dwl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){NVr();let o={},s={},a={},c=[],l={};e.logger.debug("Parsing V3 AsyncAPI...");let u=Vte();for(let[D,R]of Object.entries(i.components?.schemas??{})){let O=u.getUniqueSchemaId(D,e.logger,e.options.resolveSchemaCollisions);o[O]=Fa(R,!1,!1,e,[O],r,e.namespace)}for(let[D,R]of Object.entries(i.channels??{}))if(s[D]||(s[D]={}),R.messages)for(let[O,j]of Object.entries(R.messages))if(a[O]||(a[O]=[]),e.isReferenceObject(j)){let Y=e.resolveMessageReference(j);a[O].push({channelId:D,payload:Y.payload})}else e.isMessageWithPayload(j)&&a[O].push({channelId:D,payload:j.payload});for(let[D,R]of Object.entries(a))if(R.length===1){let O=R[0],j=O.channelId;s[j]=s[j]||{},s[j][D]=Fa(O.payload,!1,!1,e,[D],r,e.namespace)}else{c.push(D);for(let{channelId:O,payload:j}of R){let Y=`${O}_${D}`;s[O]||(s[O]={}),s[O][Y]=Fa(j,!1,!1,e,[Y],r,e.namespace)}}let p={},d=Vte();for(let[D,R]of Object.entries(s))for(let[O,j]of Object.entries(R)){let Y=d.getUniqueSchemaId(O,e.logger,e.options.resolveSchemaCollisions);p[Y]=j}let f=new $ot({...o,...p},e),m={};for(let[D,R]of Object.entries(i.servers??{})){let O=Fr(R,Ny.FERN_SERVER_NAME);m[D]={name:O??D,url:GVr(R.protocol,R.host)}}let g={},A=Object.keys(i.channels??{});for(let[D,R]of Object.entries(i.operations??{})){if(Fr(R,Ny.IGNORE))continue;let O;if(R.channel==null||!("$ref"in R.channel)||R.channel.$ref==null)if(A.length===1&&A[0]!=null)O=A[0];else continue;else O=jcm(R);g[O]||(g[O]={subscribe:[],publish:[],__parsedMessages:[]});let j=Fr(R,Ny.FERN_SDK_METHOD_NAME),Y=Fr(R,Ny.FERN_DISPLAY_NAME);if(!R.messages||!Array.isArray(R.messages))continue;let ee=R.messages.filter(ce=>ce!=null&&ce.$ref!=null).map(ce=>({ref:ce,methodName:j,displayName:Y})),te=g[O];if(te==null)throw new T({message:`Internal error: channelEvents["${O}"] is unexpectedly undefined for operation ${D}`,code:T.Code.InternalError});if(R.action==="receive")te.subscribe.push(...ee);else if(R.action==="send")te.publish.push(...ee);else throw new T({message:`Operation ${D} has an invalid action: ${R.action}`,code:T.Code.ValidationError})}for(let[D,R]of Object.entries(g)){let O=[];O.push(...fwl({messages:R.subscribe,channelPath:D,origin:"server",messageSchemas:s[D]??{},duplicatedMessageIds:c,context:e})),O.push(...fwl({messages:R.publish,channelPath:D,origin:"client",messageSchemas:s[D]??{},duplicatedMessageIds:c,context:e})),g[D]!=null&&(g[D].__parsedMessages=O)}for(let[D,R]of Object.entries(i.channels??{})){if(Fr(R,Ny.IGNORE))continue;let O=[],j=[],Y=[];if(R.parameters!=null)for(let[ee,te]of Object.entries(R.parameters)){let ce=e.isReferenceObject(te)?e.resolveParameterReference(te):te,{type:le,parameterKey:ae}=ce.location!=null?zcm(ce.location):{type:R.address?.includes(`={${ee}}`)?"query":"path",parameterKey:ee},he=Fr(ce,Ny.FERN_PARAMETER_OPTIONAL),xe=dx(ao(D))+dx(ao(ee)),Te=ce.schema!=null?Mn(ce.schema)?V_(ce.schema,!1,!1,e,[ae],void 0,r,e.namespace):Fa(ce.schema,!1,!1,e,[ae],r,e.namespace):Fa({...ce,type:"string",title:xe,example:ce.examples?.[0],default:ce.default,enum:ce.enum,required:void 0},!1,!1,e,[ae],r,e.namespace),pe=he?Gr.optional({value:Te,description:void 0,availability:void 0,generatedName:"",title:xe,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Te,ue={name:ae,description:ce.description,parameterNameOverride:void 0,schema:pe,variableReference:void 0,availability:AC(te),source:r,explode:void 0,clientDefault:void 0};le==="header"?O.push({...ue,env:void 0}):le==="path"?j.push(ue):(le==="payload"||le==="query")&&Y.push(ue)}if(R.bindings?.ws?.query!=null){let ee=new Set(Y.map(ce=>ce.name)),te=new Set(R.bindings.ws.query.required??[]);for(let[ce,le]of Object.entries(R.bindings.ws.query.properties??{})){if(ee.has(ce))continue;if(Mn(le)){let Te=e.resolveSchemaReference(le),pe=te.has(ce),[ue,Pe]=e.options.coerceOptionalSchemasToNullable?[!1,!pe]:[!pe,!1];Y.push({name:ce,schema:V_(le,ue,Pe,e,[D,ce],void 0,r,e.namespace),description:Te.description,parameterNameOverride:void 0,availability:AC(Te),source:r,explode:void 0,clientDefault:void 0});continue}let ae=te.has(ce),[he,xe]=e.options.coerceOptionalSchemasToNullable?[!1,!ae]:[!ae,!1];Y.push({name:ce,schema:Fa(le,he,xe,e,[D,ce],r,e.namespace),description:le.description,parameterNameOverride:void 0,availability:AC(le),source:r,explode:void 0,clientDefault:void 0})}}if(R.bindings?.ws?.headers!=null){let ee=new Set(O.map(ce=>ce.name)),te=new Set(R.bindings.ws.headers.required??[]);for(let[ce,le]of Object.entries(R.bindings.ws.headers.properties??{})){if(ee.has(ce))continue;if(Mn(le)){let Te=e.resolveSchemaReference(le),pe=te.has(ce),[ue,Pe]=e.options.coerceOptionalSchemasToNullable?[!1,!pe]:[!pe,!1];O.push({name:ce,schema:V_(le,ue,Pe,e,[D,ce],void 0,r,e.namespace),description:Te.description,parameterNameOverride:void 0,env:void 0,availability:AC(Te),source:r,clientDefault:void 0});continue}let ae=te.has(ce),[he,xe]=e.options.coerceOptionalSchemasToNullable?[!1,!ae]:[!ae,!1];O.push({name:ce,schema:Fa(le,he,xe,e,[D,ce],r,e.namespace),description:le.description,parameterNameOverride:void 0,env:void 0,availability:AC(le),source:r,clientDefault:void 0})}}if(O.length>0||Y.length>0||g[D]!=null&&(g[D].publish!=null||g[D].subscribe!=null)){let ee=VVr(R),te=g[D]?.__parsedMessages??[],ce=[];try{if(ee.length>0)ce=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:ee,handshake:{headers:O,queryParameters:Y},source:r,namespace:e.namespace});else{let Te=[],{examplePublishMessage:pe,exampleSubscribeMessage:ue}=Mcm({messages:te,messageSchemas:s[D]??{}});pe!=null&&Te.push(pe),ue!=null&&Te.push(ue);let Pe=f.buildWebsocketSessionExample({handshake:{headers:O,queryParameters:Y},messages:Te});Pe!=null&&ce.push(Pe)}}catch(Te){e.logger.warn(`Failed to build examples for channel ${D}: ${rn(Te)}`)}let le=Fr(R,Ny.FERN_SDK_GROUP_NAME),ae=Fr(R,Ny.FERN_SDK_METHOD_NAME),he=(R.servers?.map(Te=>Qcm(m,Te))??Object.values(m)).map(Te=>({...Te,name:Te.name})),xe=R.address?.split("?")[0]??qVr(D);l[D]={audiences:Fr(R,un.AUDIENCES)??[],handshake:{headers:O.map(Te=>({...Te,schema:$f(Te.schema),env:Te.env})),queryParameters:Y.map(Te=>({...Te,schema:$f(Te.schema)})),pathParameters:j.map(Te=>({...Te,parameterNameOverride:void 0,schema:$f(Te.schema)}))},groupName:e.resolveGroupName(typeof le=="string"?[le]:le??[D]),messages:te,summary:Fr(R,Ny.FERN_DISPLAY_NAME),connectMethodName:ae,servers:he,path:xe,description:R.description,examples:ce,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${D} as it does not qualify for inclusion (no headers, query params, or operations)`)}let b={...o,...p},I={},C=Vte();for(let[D,R]of Object.entries(b)){let O=C.getUniqueSchemaId(D,e.logger,e.options.resolveSchemaCollisions);I[O]=$f(R)}let x=Xot(e.namespace,o),S=Object.values(m).map(D=>({...D,name:D.name})),P=Fr(i,Ny.BASE_PATH);return{groupedSchemas:x,channels:l,servers:S,basePath:P}}function jcm(e){if(!e.channel)throw new T({message:"Operation is missing required 'channel' field",code:T.Code.ValidationError});if(!e.channel.$ref)throw new T({message:"Operation channel is missing required '$ref' field",code:T.Code.ValidationError});if(!e.channel.$ref.startsWith(uwl))throw new T({message:`Failed to resolve channel path from operation ${e.channel.$ref}`,code:T.Code.ReferenceError});return D0(e.channel.$ref.substring(uwl.length))}function zcm(e){let t="https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression",[r,n]=e.split("#/");if(r==null||n==null)throw new T({message:`Invalid location format: ${e}; unable to parse message type and parameter key. See ${t} for the expected format.`,code:T.Code.ValidationError});if(!r.startsWith(sjo))throw new T({message:`Invalid location format: ${e}; expected ${sjo} prefix`,code:T.Code.ValidationError});let i=r.substring(sjo.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new T({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,code:T.Code.ValidationError});return{type:i,parameterKey:n}}function Qcm(e,t){if(!t.$ref.startsWith(pwl))throw new T({message:`Failed to resolve server name from server ref ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(pwl.length),n=e[r];if(n==null)throw new T({message:`Failed to find server with name ${r}`,code:T.Code.ReferenceError});return n}function fwl({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,c)=>{try{let l=o.resolveMessageReference(a.ref,!0),u=o.resolveMessageReference(a.ref),p=l.name;i.includes(p)&&(p=`${t}_${p}`);let d=n[p];d!=null&&s.push({origin:r,name:p??`${r}Message${c+1}`,displayName:a.displayName,description:u.description??u.summary,body:$f(d),methodName:a.methodName})}catch(l){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${rn(l)}`)}}),s}function Mcm({messages:e,messageSchemas:t}){let r=e.find(s=>s.origin==="client")?.name,n=e.find(s=>s.origin==="server")?.name,i=r!=null?t[r]:void 0,o=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:o!=null&&n!=null?{type:n,payload:o}:void 0}}var uwl,pwl,sjo,mwl=h(()=>{"use strict";mt();Ic();Bt();xo();yl();W5();Hot();sR();Kot();Gb();zVr();LUt();njo();UVr();ijo();ojo();uwl="#/channels/",pwl="#/servers/",sjo="$message."});function hwl({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let s=[];if(o!=null&&s.push(o),parseFloat(e.asyncapi)<3){let a=e;a.tags?.[0]!=null?s.push(a.tags[0].name):i.naming!=="v2"&&s.push("websocket");let c=new jVr({document:a,taskContext:t,options:r,namespace:o});return awl({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,c=new WVr({document:a,taskContext:t,options:r,namespace:o});return dwl({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}var gwl=h(()=>{"use strict";ZSl();cwl();lwl();mwl()});function KVr({schema:e,name:t}){return t??e.title??HVr}function K3e(e){let t=e.errorResponses;if(!e.sharedErrorResponses||t==null)return;let r=t.schema;if(!(typeof r=="string"||"$ref"in r||ajo(r)))return KVr({schema:r,name:t.name})}function ajo(e){return Array.isArray(e)?e.some(ajo):e!=null&&typeof e=="object"?Object.entries(e).some(([t,r])=>t==="$ref"||ajo(r)):!1}var HVr,HUt=h(()=>{"use strict";HVr="ProblemDetails"});function JVr(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var cjo=h(()=>{"use strict"});function Awl(e){return Fr(e,un.ASYNC_CONFIG)}var ywl=h(()=>{"use strict";yl();Lu()});function Ewl(e,t){let r=Fr(t,un.STREAMING);if(r==null)return;if(typeof r=="boolean")return r?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=Lcm(e,r);if(r["stream-condition"]==null&&r.format!=null)return{type:"stream",format:r.format,terminator:r.terminator,resumable:n};if(r["stream-condition"]!=null)return{type:"streamCondition",format:r.format??"json",terminator:r.terminator,streamDescription:r["stream-description"],streamConditionProperty:_cm(r["stream-condition"]),streamRequestName:r["stream-request-name"],responseStream:r["response-stream"],response:r.response,resumable:n}}function Lcm(e,t){return typeof t.resumable=="boolean"?t.resumable:ljo(e)??!1}function ljo(e){let t=Fr(e,un.STREAMING);if(!(t==null||typeof t=="boolean"))return typeof t.resumable=="boolean"?t.resumable:void 0}function Iwl(e){let t=Fr(e,un.STREAMING);if(!(t==null||typeof t=="boolean"))return typeof t.resumable=="boolean"?t.resumable:void 0}function _cm(e){return e.startsWith(bwl)?e.slice(bwl.length):e}var bwl,vwl=h(()=>{"use strict";yl();Lu();bwl="$request."});function Cwl(e){let t=e;if(t.cursor!=null)return Iw.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return Iw.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return Iw.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return Iw.offset({offset:i.offset,results:i.results,step:i.step,hasNextPage:i["has-next-page"]})}if("type"in e&&e.type==="custom"){let i=e;return Iw.custom({results:i.results})}throw new T({message:"Invalid pagination extension",code:T.Code.ValidationError})}function xwl(e,t){let r=Fr(t,un.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=Fr(e,un.PAGINATION);if(typeof n=="boolean")throw new T({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",code:T.Code.ValidationError});return n==null?void 0:Cwl(n)}return Cwl(r)}}var Swl=h(()=>{"use strict";Ic();Bt();yl();Lu()});function wwl(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n,o=n.schema??i.itemSchema;return{contentType:r,schema:o??{},examples:est(n,t)}}}function Twl(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function Ucm(e){return e.includes("json")||e==="*/*"}function KUt({content:e,context:t}){for(let[r,n]of Object.entries(e))if(YVr({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function YVr({mediaType:e,mediaTypeObject:t,context:r}){if(!Ucm(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:est(t,r)}}function JUt({content:e,context:t}){let r=KUt({content:e,context:t});if(!r)return;let[n,i]=r;return YVr({mediaType:n,mediaTypeObject:i,context:t})}function Owl(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:est(n,t)}}}function est(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=Fr(e,sB.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let s=Mn(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}var tst=h(()=>{"use strict";yl();Gb();M3e()});var Vcm,ujo,Pwl=h(()=>{"use strict";nn();Vcm=Xt.object({lang:Xt.string(),label:Xt.optional(Xt.string()),source:Xt.string()}),ujo=Xt.array(Vcm)});var Bwl,Dwl=h(()=>{"use strict";Bwl={README_EXT:"x-readme"}});function Gcm(e){if(!Array.isArray(e))return!1;for(let t of e)if(!oi(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function Rwl(e){let t=Fr(e,Bwl.README_EXT);if(!oi(t))return[];let r=t["code-samples"];if(!Gcm(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}var kwl=h(()=>{"use strict";mt();yl();Dwl()});function qcm(e){return oi(e)&&typeof e.$ref=="string"}function Wcm(e,t){if(e!=null){if(typeof e=="string")return e;if(qcm(e)){let r=(0,ZVr.resolve)(t??process.cwd(),e.$ref);if((0,XVr.existsSync)(r))try{return(0,XVr.readFileSync)(r,"utf-8")}catch{return}}}}function Hcm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=Wcm(n.code,t);o!=null&&r.push({...n,code:o})}return r}function Fwl(e,t,r){let n=Fr(t,un.EXAMPLES),i=r.source.type==="openapi"?(0,ZVr.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!oi(p))return p;let f=p["code-samples"];if(f!=null){let m=Hcm(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=Qd.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=NUt(t,sB.REDOCLY_CODE_SAMPLES_KEBAB,ujo,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...NUt(t,sB.REDOCLY_CODE_SAMPLES_CAMEL,ujo,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&s.push({"code-samples":l.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let u=Rwl(t);return u.length>0&&s.push({"code-samples":u}),s.map(M5.unknown)}var XVr,ZVr,Nwl=h(()=>{"use strict";mt();lo();Ic();XVr=require("fs"),ZVr=require("path");yl();Pwl();M3e();Lu();kwl()});function jwl(e){let t=Fr(e,un.AVAILABILITY);if(t==="ga"||t==="generally-available")return ng.GenerallyAvailable;if(t==="beta"||t==="pre-release")return ng.Beta;if(t==="deprecated")return ng.Deprecated;if(t==="alpha")return ng.Alpha;if(t==="preview")return ng.Preview;if(t==="legacy")return ng.Legacy;if(e.deprecated)return ng.Deprecated}var zwl=h(()=>{"use strict";Ic();yl();Lu()});function Qwl(e){let t=Fr(e,un.RETRIES);if(t!=null&&t.disabled===!0)return Cm.RetriesConfiguration.disabled(t.disabled)}var Mwl=h(()=>{"use strict";Ic();yl();Lu()});function Kcm(e){return e["x-fern-default"]??e.default}function Lwl(e){let t=Fr(e,un.FERN_GLOBAL_PARAMETERS),r=[];for(let n of t??[])typeof n.name=="string"&&r.push({name:n.name,parameterName:n["parameter-name"],in:n.in,target:n.target,type:n.type,env:n.env,default:Kcm(n),optional:n.optional,apply:n.apply,docs:n.docs});return r}function _wl(e){let t=Fr(e,un.FERN_GLOBAL_PARAMETER);if(t!=null){if(typeof t=="string")return[t];if(Array.isArray(t))return t.filter(r=>typeof r=="string")}}var pjo=h(()=>{"use strict";yl();Lu()});function $Vr(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=Ycm(e);return{url:Zcm({url:e.url,variables:e.variables??{}}),description:e.description,name:$cm(e,t),audiences:Fr(e,un.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?Xcm(e.variables):void 0,defaultUrl:r?n:void 0}}function Ycm(e){let t=e[Jcm];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function Xcm(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function Zcm({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function $cm(e,t){let r=Fr(e,[un.SERVER_NAME_V1,un.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}var Jcm,fjo=h(()=>{"use strict";yl();Lu();Jcm="x-fern-default-url"});function Uwl(e){return Fr(e,un.PARAMETER_NAME)}var Vwl=h(()=>{"use strict";yl();Lu()});function Gwl(e){return Fr(e,un.SDK_VARIABLE)}var qwl=h(()=>{"use strict";yl();Lu()});function e5r({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let c=Mn(a)?n.resolveParameterReference(a):a,l=Fr(a,un.IGNORE)??Fr(c,un.IGNORE);if(l!=null&&l){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let u=c.required??!1,p=AC(c),d=[...i,c.name],f=JA(d,n.options.preserveSchemaIds),m=c.in==="header",[g,A]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!u]:[!u,!1],b=elm(c,n),I=b!=null?Fa(b,g,A,n,d,o,n.namespace,!1,new Set,ilm(c,n)):u?Gr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Li.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:V5({schema:c,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Gr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Gr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Li.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:V5({schema:c,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(c.in==="header"&&c.schema!=null&&!Mn(c.schema)&&c.schema.default!=null){let S=c.schema.default;typeof S=="string"&&S.length>0&&(I=Gr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:ky.string(S),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let C=Fr(a,un.FERN_DEFAULT)??Fr(c,un.FERN_DEFAULT),x={name:c.name,schema:I,description:rlm(c),parameterNameOverride:Uwl(c),availability:p,source:o,clientDefault:C};c.in==="query"?s.queryParameters.push({...x,explode:nlm(c)}):c.in==="path"?s.pathParameters.push({...x,variableReference:Gwl(c),explode:olm(c)}):c.in==="header"?!tlm.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?s.headers.push({...x,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return s}function elm(e,t){return e.schema!=null?e.schema:!t.options.respectParameterContent||e.in!=="header"||e.content==null?void 0:KUt({content:e.content,context:t})?.[1].schema}function rlm(e){if(e.description!=null)return e.description;if(!(e.schema==null||Mn(e.schema)))return e.schema.description}function nlm(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}function ilm(e,t){let r=DVr({schema:e,logger:t.logger});return r??V5({schema:e,logger:t.logger})}function olm(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}var tlm,djo=h(()=>{"use strict";Ic();yl();Hot();sR();XNo();Gte();Gb();Lu();Vwl();qwl();tst();tlm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"])});function slm({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Hwl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function Hwl({mediaType:e,mediaTypeObject:t,context:r}){if(gp.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:est(t,r)}}function alm({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Kwl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function Kwl({mediaType:e,mediaTypeObject:t,context:r}){if(gp.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:est(t,r)}}function Jwl({mediaType:e}){return gp.parse(e)?.isBinary()??!1}function clm({content:e}){for(let[t,r]of Object.entries(e))if(Jwl({mediaType:t}))return[t,r]}function llm(e,t){let r=Mn(e)?mjo(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!Mn(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function r5r({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}){let c=clm({content:e});if(c){let[f,m]=c;return qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a})}let l=alm({content:e,context:n}),u=KUt({content:e,context:n}),p=ulm({json:u,multipart:l,document:r,visitor:{json:([f,m])=>qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}),multipart:([f,m])=>qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}),neither:()=>{}}});if(p)return p;let d=slm({content:e,context:n});if(d){let[f,m]=d;return qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a})}}function ulm({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,o]=t??[void 0,void 0];return!i?.schema&&!o?.schema?e&&(i?.example!=null||i?.examples!=null&&Object.keys(i.examples).length>0)?n.json(e):n.neither():i?.schema&&o?.schema?i.schema&&llm(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function qte({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a,bodyRequired:c}){let l=plm({mediaTypeObject:t});if(Jwl({mediaType:e}))return y2.octetStream({description:r,source:s,sdkMethodName:l,contentType:e});let u=Kwl({mediaType:e,mediaTypeObject:t,context:i}),p=u?.schema,d=u?.encoding,f=u?.examples;if(p){let A=Mn(p)?mjo(p,n):{id:void 0,schema:p},b=Fa(A.schema,!1,!1,i,o,s,a,!1),I=[];if(b.type==="object"){let C=new Set(A.schema.required??[]);for(let x of b.properties){let S=C.has(x.key),{isFile:P,isOptional:D,isArray:R,description:O}=t5r({schema:x.schema,isOptional:!S});if(P){let j=Wwl(x.key,d);I.push({key:x.key,schema:Nte.file({isOptional:D,isArray:R,description:O}),description:O,contentType:j,exploded:!1,encoding:j==null?i.options.defaultFormParameterEncoding:void 0})}else{let j=Wwl(x.key,d);I.push({key:x.key,schema:Nte.json(x.schema),description:void 0,contentType:j,exploded:d?.[x.key]?.explode,encoding:j==null?i.options.defaultFormParameterEncoding:dlm(j)})}}}return y2.multipart({name:Mn(p)&&i.getNumberOfOccurrencesForRef(p)===1?A.id:void 0,description:A.schema.description,properties:I,source:s,sdkMethodName:l,fullExamples:f})}let m=YVr({mediaType:e,mediaTypeObject:t,context:i});if(m){let A=Fa(m.schema,!1,!1,i,o,s,a,!0);return y2.json({description:void 0,schema:A,contentType:m.contentType,required:c,fullExamples:m.examples,additionalProperties:!Mn(m.schema)&&_Ut(m.schema.additionalProperties,i.options),source:s,sdkMethodName:l})}let g=Hwl({mediaType:e,mediaTypeObject:t,context:i});if(g!=null&&g.schema!=null){let A=Fa(g.schema,!1,!1,i,o,s,a,!1);return y2.formUrlEncoded({schema:A,description:r,contentType:g.contentType,source:s,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:l})}}function plm({mediaTypeObject:e}){return Fr(e,un.SDK_METHOD_NAME)}function dlm(e){return e?flm[e]:void 0}function mjo(e,t){if(!e.$ref.startsWith(W3e))throw new T({message:`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`,code:T.Code.ReferenceError});let r=bxe(e);if(r==null)throw new T({message:`Failed to resolve schema reference because missing schema id: ${e.$ref}`,code:T.Code.ReferenceError});let n=t.components?.schemas?.[r];if(n==null)throw new T({message:`Failed to resolve schema reference because missing: ${e.$ref}`,code:T.Code.ReferenceError});return Mn(n)?mjo(n,t):{id:r,schema:n}}function t5r({schema:e,isOptional:t,isArray:r,description:n}){return hlm(e)?t5r({schema:e.value,isOptional:!0,isArray:r,description:e.description}):glm(e)?t5r({schema:e.value,isOptional:t,isArray:r,description:e.description}):Alm(e)?t5r({schema:e.value,isOptional:t,isArray:!0,description:e.description}):mlm(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function mlm(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function hlm(e){return e.type==="optional"}function glm(e){return e.type==="nullable"}function Alm(e){return e.type==="array"}function Wwl(e,t){return t?.[e]?.contentType}var flm,hjo=h(()=>{"use strict";mt();Ic();Bt();yl();SVr();sR();Gb();Lu();tst();flm={"application/json":"json"}});function Xwl(e){switch(e.toUpperCase()){case ylm:return 400;case blm:return 500;default:return}}var gjo,ylm,blm,Ajo,Ywl,yjo=h(()=>{"use strict";gjo={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"},ylm="4XX",blm="5XX",Ajo={400:"ClientRequestError",500:"ServerError"},Ywl=new Set([...Object.values(gjo),...Object.values(Ajo)])});function n5r({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,streamTerminator:s,streamResumable:a,source:c}){if(t==null)return{value:void 0,errors:{}};let l=Ilm({responses:t,context:r,source:c,namespace:r.namespace}),u=!1,p=!1,d;for(let f of i!=null?[i]:Elm){let m=t[f];if(m==null)continue;u=!0;let g=typeof f=="string"?parseInt(f):f;if(d==null){let A=Zwl({operationContext:e,response:m,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,streamResumable:a,source:c,namespace:r.namespace,statusCode:g});A!=null?d=A:g===204&&(p=!0)}else if(g===204){let A=Mn(m)?r.resolveResponseReference(m):m;JUt({context:r,content:A.content??{}})!=null&&r.logger.warn(`${e.method.toUpperCase()} ${e.path}: the 204 response declares a body, but a 204 (No Content) response cannot include one. Ignoring the declared 204 body and treating the success response as optional.`),p=!0}}if(p&&d!=null&&d.type==="json"){let f=d.schema;f.type!=="optional"&&(d=Jg.json({...d,schema:Gr.optional({value:f,description:f.type==="reference"?f.description:void 0,nameOverride:void 0,generatedName:"",groupName:void 0,namespace:void 0,availability:void 0,title:void 0,inline:void 0})}))}if(d==null&&!u&&t.default!=null&&(d=Zwl({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,streamResumable:a,source:c,namespace:r.namespace})),d!=null)switch(d.type){case"json":return{value:d,errors:l};case"streamingJson":case"streamingSse":return{value:d,errors:l};case"bytes":case"file":case"text":case"streamingText":return{value:d,errors:l};default:Ye(d)}return{value:void 0,errors:l}}function Zwl({operationContext:e,streamFormat:t,streamTerminator:r,streamResumable:n,response:i,context:o,responseBreadcrumbs:s,source:a,namespace:c,statusCode:l}){let u=Mn(i)?o.resolveResponseReference(i):i;if(u.content!=null&&Object.entries(u.content).find(([m,g])=>{if(g.schema==null)return!1;let A=Mn(g.schema)?o.resolveSchemaReference(g.schema):g.schema;return A.type==="string"&&(A.format==="binary"||A.format==null&&A.contentMediaType==="application/octet-stream")}))return o.options.useBytesForBinaryResponse&&t==null?Jg.bytes({description:u.description,source:a,statusCode:l}):Jg.file({description:u.description,source:a,statusCode:l});let p=wwl(u.content??{},o);if(p!=null&&t!=null)switch(t){case"json":return Jg.streamingJson({statusCode:l,description:u.description,responseProperty:Fr(e.operation,un.RESPONSE_PROPERTY),terminator:r,resumable:void 0,fullExamples:p.examples,schema:Fa(p.schema,!1,!1,o,s,a,c),source:a});case"sse":return Jg.streamingSse({description:u.description,responseProperty:void 0,terminator:r,resumable:n,fullExamples:p.examples,schema:Fa(p.schema,!1,!1,o,s,a,c),source:a,statusCode:l})}let d=JUt({context:o,content:u.content??{}});if(d){if(t!=null)switch(t){case"json":return Jg.streamingJson({description:u.description,responseProperty:void 0,terminator:r,resumable:void 0,fullExamples:d.examples,schema:Fa(d.schema,!1,!1,o,s,a,c),source:a,statusCode:l});case"sse":return Jg.streamingSse({description:u.description,responseProperty:void 0,terminator:r,resumable:n,fullExamples:d.examples,schema:Fa(d.schema,!1,!1,o,s,a,c),source:a,statusCode:l})}return Jg.json({description:u.description,schema:Fa(d.schema,!1,!1,o,s,a,c),responseProperty:Fr(e.operation,un.RESPONSE_PROPERTY),terminator:void 0,resumable:void 0,fullExamples:d.examples,source:a,statusCode:l})}for(let[f,m]of Object.entries(u.content??{})){let g=gp.parse(f);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo()||g.isMultiPartMixed())return Jg.file({description:u.description,source:a,statusCode:l});if(g.isText()&&!f.includes("event-stream")){let A=m.schema,b=g.isPlainText()?void 0:f;if(A==null)return Jg.text({description:u.description,source:a,statusCode:l,contentType:b});let I=Mn(A)?o.resolveSchemaReference(A):A;return I.type==="string"&&I.format==="byte"?Jg.file({description:u.description,source:a,statusCode:l}):Jg.text({description:u.description,source:a,statusCode:l,contentType:b})}}}}function Ilm({responses:e,context:t,source:r,namespace:n}){let i={},o=n!=null?K3e(t.options):void 0;for(let[s,a]of Object.entries(e)){if(s==="default")continue;let c=Xwl(s),l=c!=null,u=c??parseInt(s);if(u<400||u>600)continue;let p=Mn(a)?t.resolveResponseReference(a):a,d=Owl(p.content??{},t),f=l?Ajo[u]:gjo[u];if(f==null){t.logger.warn(`No error name found for status code ${s}`);continue}let m=t.options.namespacedErrors?Fr(p,un.SDK_NAMESPACE):void 0,g=l?s.toUpperCase():u.toString(),A=o!=null&&m==null&&d?.schema!=null&&Mn(d.schema)&&bxe(d.schema)===o;i[g]={statusCode:u,isWildcardStatusCode:l?!0:void 0,nameOverride:void 0,generatedName:f,description:p.description,schema:Fa(d?.schema??{},!1,!1,t,[f,"Body"],r,A?void 0:m??n),fullExamples:d?.examples,namespace:m,isShared:A?!0:void 0,source:r}}return i}var Elm,bjo=h(()=>{"use strict";mt();Ic();yl();sR();Gb();HUt();Lu();yjo();tst();Elm=["200","201","202","204"]});function Jde({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,streamResumable:s,source:a,streamRequestNameOverride:c}){let{document:l,operation:u,path:p,method:d,baseBreadcrumbs:f,pathItem:m}=e,g=Fr(u,un.IDEMPOTENT),A=Fr(u,[un.REQUEST_NAME_V1,un.REQUEST_NAME_V2]),b=[...f,"Request"],I=e5r({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:b,path:p,httpMethod:d,source:a}),C=/{([^}]+)}/g,x=[...p.matchAll(C)].map(le=>le[1]).filter(le=>le!==void 0),S=[...p.matchAll(C)].map(le=>le[1]);switch(t.options.pathParameterOrder){case Qr.PathParameterOrder.SpecOrder:{let le=S.filter(ae=>!I.pathParameters.some(he=>he.name===ae));if(le.length>0)for(let ae of le)I.pathParameters.push({name:ae??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Gr.primitive({schema:Li.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}break;case Qr.PathParameterOrder.UrlOrder:if(x.length>0){let le=new Map(I.pathParameters.map(xe=>[xe.name,xe])),ae=[],he=new Set;for(let xe of x){let Te=le.get(xe);he.add(xe),Te?ae.push(Te):ae.push({name:xe,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Gr.primitive({schema:Li.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}for(let xe of I.pathParameters)he.has(xe.name)||ae.push(xe);I.pathParameters=ae}break;default:Ye(t.options.pathParameterOrder)}let P=(()=>{if(e.method==="GET")return[void 0];if(!u.requestBody)return[void 0];let le=Mn(u.requestBody)?t.resolveRequestBodyReference(u.requestBody):u.requestBody,ae=Object.values(le.content).every(xe=>vlm({mediaTypeObject:xe})!=null),he=[];if(ae)return he.push(...Object.entries(le.content).map(([xe,Te])=>{let pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t.DUMMY,requestBreadcrumbs:b,source:a,namespace:t.namespace,bodyRequired:le.required});return e1l({context:t,convertedParameters:I})&&pe!=null&&(pe.type==="json"||pe.type==="formUrlEncoded")&&pe.schema.type!=="object"&&u.requestBody!=null?pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t,requestBreadcrumbs:[...b,"Body"],source:a,namespace:t.namespace,bodyRequired:le.required}):u.requestBody!=null&&(pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t,requestBreadcrumbs:[...b],source:a,namespace:t.namespace,bodyRequired:le.required})),pe}).filter(xe=>xe!=null)),he.length===0?[void 0]:he;{let xe=r5r({content:le.content,description:le.description,document:l,context:t.DUMMY,requestBreadcrumbs:b,source:a,namespace:t.namespace,bodyRequired:le.required});return e1l({context:t,convertedParameters:I})&&xe!=null&&(xe.type==="json"||xe.type==="formUrlEncoded")&&xe.schema.type!=="object"&&u.requestBody!=null?xe=r5r({content:le.content,description:le.description,document:l,context:t,requestBreadcrumbs:[...b,"Body"],source:a,namespace:t.namespace,bodyRequired:le.required}):u.requestBody!=null&&(xe=r5r({content:le.content,description:le.description,document:l,context:t,requestBreadcrumbs:[...b],source:a,namespace:t.namespace,bodyRequired:le.required})),[xe]}})(),D=P.length>1,R=[...f,"Response"],O=n5r({operationContext:e,streamFormat:i,streamTerminator:o,streamResumable:s,responses:u.responses,context:t,responseBreadcrumbs:R,responseStatusCode:r,source:a}),j=Qwl(u),Y=jwl(u),ee=Fwl(e,u,t),te=Fr(u,un.SERVER_NAME_V2),ce=Fr(u,un.SUBTITLE);return P.map(le=>({summary:u.summary,subtitle:ce??void 0,internal:Fr(u,sB.INTERNAL),idempotent:g,audiences:Fr(u,un.AUDIENCES)??[],operationId:u.operationId!=null&&n!=null?u.operationId+"_"+n:u.operationId,tags:t.options.ignoreTags?[]:t.resolveTagsToTagIds(u.tags),namespace:t.namespace,sdkName:Clm({operationContext:e,request:le}),pathParameters:I.pathParameters,queryParameters:I.queryParameters,headers:I.headers,requestNameOverride:c??A??void 0,generatedRequestName:wlm({baseBreadcrumbs:f,requestBreadcrumbs:b,isMultipleRequests:D,request:le,context:t}),request:le,response:O.value,errors:O.errors,servers:te!=null?[{name:te,url:void 0,audiences:void 0}]:(u.servers??m.servers??[]).map(ae=>$Vr(ae,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:u.description,authed:Slm(u,l),security:xlm(u),availability:Y,method:d,path:p,examples:ee,pagination:e.pagination,source:a,retries:j,globalParameterIds:_wl(u)}))}function $wl({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function vlm({mediaTypeObject:e}){return Fr(e,un.SDK_METHOD_NAME)}function Clm({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function xlm(e){return JVr(e.security)}function Slm(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function e1l({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function wlm({baseBreadcrumbs:e,requestBreadcrumbs:t,isMultipleRequests:r,request:n,context:i}){let o=r?$wl({breadcrumbs:t,request:n}):t,s=JA(o,i.options.preserveSchemaIds);if(!i.options.disambiguateRequestNames)return s;let a=i.document.components?.schemas;if(a==null||!Object.keys(a).some(p=>JA([p],i.options.preserveSchemaIds)===s))return s;let l=[...e,"Body"],u=r?$wl({breadcrumbs:l,request:n}):l;return JA(u,i.options.preserveSchemaIds)}var i5r=h(()=>{"use strict";yo();mt();Ic();yl();Gte();Gb();cjo();M3e();Lu();Nwl();zwl();Mwl();pjo();fjo();djo();hjo();bjo()});function r1l({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,c=r.discriminant.value,l=r["response-status-code"],u=t1l({context:t,headerToIgnore:a,parameters:o}),p=t1l({context:t,headerToIgnore:a,parameters:s}),d=Jde({operationContext:{...e,pathItemParameters:u,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==l))}},context:t,streamFormat:void 0,source:n}),f=Jde({operationContext:{...e,pathItemParameters:u,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:l,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Gr.literal({nameOverride:void 0,generatedName:JA([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:ky.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n,clientDefault:void 0})}),{sync:d,async:f}}function t1l({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=Mn(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var n1l=h(()=>{"use strict";Ic();Gte();Gb();i5r()});function a1l({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:Jde({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,streamResumable:r.resumable,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=i1l({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0}),i=o1l({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let u=t.resolveSchemaReference(n.schemaReference),p=Fr(u,un.TYPE_NAME);if(p!=null)return`${p}Streaming`}})(),s=Jde({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Ejo}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Ejo]},context:t,streamFormat:r.format,streamTerminator:r.terminator,streamResumable:r.resumable,suffix:Ejo,source:t.source,streamRequestNameOverride:o});s.forEach(u=>{u.examples=u.examples.filter(p=>s1l(p,t)!==!1)});let a=i1l({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=o1l({operation:e.operation,response:r.response}),l=Jde({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:c}},context:t,source:t.source});return l.forEach(u=>{u.examples=u.examples.filter(p=>s1l(p,t)!==!0)}),{streaming:s,nonStreaming:l}}default:Ye(r)}}function i1l({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=Mn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=JUt({content:i.content,context:e});if(o==null)return;let s=Mn(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null&&s.oneOf==null&&s.anyOf==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&Mn(a)&&(a=void 0);let c={...s,properties:{...s.properties,[r.streamConditionProperty]:{...a??{},type:"boolean","x-fern-boolean-literal":n}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{required:i.required,content:{[gp.APPLICATION_JSON]:{schema:c}}},schemaReference:Mn(o.schema)?o.schema:void 0}}function o1l({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[gp.APPLICATION_JSON]:{schema:t}}}}}function s1l(e,t){return e._visit({unknown:r=>{let n=Qd.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var Ejo,c1l=h(()=>{"use strict";mt();lo();yl();Gb();Lu();tst();i5r();Ejo="stream"});function Tlm(e){return f1l.includes(e)}function Olm(e){switch(e){case"unix-seconds":return Cm.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Cm.WebhookTimestampFormat.UnixMillis;case"iso8601":return Cm.WebhookTimestampFormat.Iso8601}}function l1l(e){if(e!=null)return{header:e.header,format:e.format!=null?Olm(e.format):void 0,tolerance:e.tolerance}}function u1l(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Cm.WebhookPayloadComponent.Body;case"timestamp":return Cm.WebhookPayloadComponent.Timestamp;case"notification-url":return Cm.WebhookPayloadComponent.NotificationUrl;case"message-id":return Cm.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter,bodySort:Plm(e["body-sort"])}}function Plm(e){if(e!=null&&e==="alphabetical")return Cm.WebhookPayloadBodySort.Alphabetical}function Blm(e,t){if(e!=null){if(!Tlm(e.algorithm)){t.warn(`Ignoring webhook body-hash-binding: unsupported algorithm "${e.algorithm}". Supported algorithms are: ${f1l.join(", ")}.`);return}if(e.location?.type!=="query-parameter"){t.warn(`Ignoring webhook body-hash-binding: unsupported location type "${e.location?.type}". The only supported location is "query-parameter".`);return}return{algorithm:Rlm(e.algorithm),encoding:Ijo(e.encoding),location:klm(e.location)}}}function Dlm(e,t){if(e==null)return;let r=e["port-variants"],n=e["legacy-query-encoding"];if(r!=null&&typeof r!="boolean"){t.warn(`Ignoring webhook url-normalization: "port-variants" must be a boolean, got "${typeof r}".`);return}if(n!=null&&typeof n!="boolean"){t.warn(`Ignoring webhook url-normalization: "legacy-query-encoding" must be a boolean, got "${typeof n}".`);return}if(!r&&!n){t.warn('Ignoring webhook url-normalization: enable at least one of "port-variants" or "legacy-query-encoding".');return}return{portVariants:r??!1,legacyQueryEncoding:n??!1}}function Rlm(e){switch(e){case"sha256":return Cm.WebhookBodyHashAlgorithm.Sha256;case"sha1":return Cm.WebhookBodyHashAlgorithm.Sha1;case"sha384":return Cm.WebhookBodyHashAlgorithm.Sha384;case"sha512":return Cm.WebhookBodyHashAlgorithm.Sha512;default:Ye(e)}}function klm(e){if(e.type==="query-parameter")return Cm.WebhookBodyHashLocation.queryParameter({name:e.name});Ye(e.type)}function Flm(e){if(e!=null)switch(e){case"sha256":return Cm.WebhookSignatureAlgorithm.Sha256;case"sha1":return Cm.WebhookSignatureAlgorithm.Sha1;case"sha384":return Cm.WebhookSignatureAlgorithm.Sha384;case"sha512":return Cm.WebhookSignatureAlgorithm.Sha512}}function Ijo(e){if(e!=null)switch(e){case"base64":return Cm.WebhookSignatureEncoding.Base64;case"hex":return Cm.WebhookSignatureEncoding.Hex}}function Nlm(e){if(e!=null)switch(e){case"rsa-sha256":return Cm.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Cm.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Cm.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Cm.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Cm.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Cm.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Cm.AsymmetricAlgorithm.Ed25519}}function d1l(e,t){if(e.type==="hmac")return Cm.WebhookSignatureVerification.hmac({header:e.header,algorithm:Flm(e.algorithm),encoding:Ijo(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:u1l(e["payload-format"]),timestamp:l1l(e.timestamp),bodyHashBinding:Blm(e["body-hash-binding"],t),notificationUrlNormalization:Dlm(e["url-normalization"],t)});if(e.type==="asymmetric"){let r=Nlm(e["asymmetric-algorithm"]);return r==null?void 0:Cm.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:r,encoding:Ijo(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],payloadFormat:u1l(e["payload-format"]),timestamp:l1l(e.timestamp)})}}function p1l(e,t){let r=Fr(e,un.WEBHOOK_SIGNATURE);if(!(r==null||typeof r=="boolean"))return d1l(r,t)}function m1l(e,t,r){let n=Fr(t,un.WEBHOOK_SIGNATURE);return n!=null?typeof n=="boolean"?p1l(e,r):d1l(n,r):p1l(e,r)}var f1l,h1l=h(()=>{"use strict";mt();Ic();yl();Lu();f1l=["sha256","sha1","sha384","sha512"]});function A1l({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:c}=t,l=[...a,"Payload"],u=[...a,"Response"],p=e5r({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:l,path:o,httpMethod:s,source:r});if(s!=="POST"&&s!=="GET")return e.logger.warn(`Skipping webhook ${s.toUpperCase()} ${o}: Only POST and GET methods are currently supported`),[];let d=i.operationId??zlm({path:o,method:s,sdkMethodName:c}),f=i.responses?n5r({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:u,source:r}):void 0,m=m1l(n,i,e.logger);if(i.requestBody==null){if(p.queryParameters.length===0)return e.logger.error(`Skipping webhook ${s.toUpperCase()} ${o}: Missing a request body and no query parameters`),[];let A=p.queryParameters.map(C=>({key:C.name,schema:C.schema,readonly:void 0,writeonly:void 0,audiences:[],conflict:{},nameOverride:C.parameterNameOverride,generatedName:JA([...l,C.name],e.options.preserveSchemaIds),availability:C.availability,xml:void 0})),b=Gr.object({description:i.description,properties:A,nameOverride:void 0,generatedName:JA(l,e.options.preserveSchemaIds),title:void 0,allOf:[],allOfPropertyConflicts:[],namespace:e.namespace,groupName:void 0,fullExamples:void 0,additionalProperties:!1,availability:void 0,encoding:void 0,source:r,inline:void 0,minProperties:void 0,maxProperties:void 0,examples:void 0});return[{summary:i.summary,audiences:Fr(i,un.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:JA(l,e.options.preserveSchemaIds),payload:b,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let g=Mn(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(g.content).map(([A,b])=>qte({mediaType:A,mediaTypeObject:b,description:g.description,document:n,context:e,requestBreadcrumbs:[...a,"Payload"],source:r,namespace:e.namespace,bodyRequired:g.required})).filter(A=>A!=null).map(A=>{if(A==null||A.type!=="json"&&A.type!=="formUrlEncoded"&&A.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let b,I;return A.type==="multipart"?(b={name:A.name,properties:A.properties,description:A.description,source:A.source},I=Gr.unknown({nameOverride:void 0,generatedName:JA(l,e.options.preserveSchemaIds),title:void 0,description:A.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):I=A.schema,{summary:i.summary,audiences:Fr(i,un.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:JA(l,e.options.preserveSchemaIds),payload:I,signatureVerification:m,multipartFormData:b,response:f?.value,description:i.description,examples:jlm(A.fullExamples),source:r}}).filter(A=>A!=null)}function jlm(e){if(e==null)return[];let t=[];for(let r of e){let n=vxe(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function zlm({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=Qlm(e);if(n===e.toLowerCase())return e;let i=(0,g1l.createHash)("sha256").update(e).digest("hex").slice(0,8);return Mlm(`${n}_${t.toLowerCase()}_${i}`)}function Qlm(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function Mlm(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}var g1l,y1l=h(()=>{"use strict";Ic();g1l=require("crypto");yl();QVr();Gte();Gb();Lu();h1l();djo();hjo();bjo()});function vjo({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=Fr(r,un.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=Llm(r,e),s=xwl(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:_lm({operation:r,sdkMethodName:o,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:s};if(n)return{type:"webhook",value:A1l({context:e,operationContext:a,source:e.source})};let c=Ewl(e.document,r);if(c==null&&Ulm({operation:r,context:e})&&(c={type:"stream",format:"sse",terminator:void 0,resumable:Iwl(r)??ljo(e.document)??!1}),c!=null){let p=a1l({context:e,operationContext:a,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let l=Awl(r);if(l!=null){let p=r1l({context:e,operationContext:a,asyncExtension:l,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:Jde({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function Llm(e,t){let r=Fr(e,un.SDK_METHOD_NAME),n=Fr(e,un.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function _lm({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let o=[];if(e!=null){if(i&&o.push(e.methodName),e.groupName.length>0){let s=e.groupName[e.groupName.length-1];s!=null&&o.push(typeof s=="string"?s:s.name)}i||o.push(e.methodName)}else t.operationId!=null?o.push(t.operationId):o.push(ao(`${r}_${n.split("/").join("_")}`));return o}function Ulm({operation:e,context:t}){if(e.responses==null)return!1;for(let[r,n]of Object.entries(e.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=Mn(n)?t.resolveResponseReference(n):n;if(o.content!=null&&Twl(o.content))return!0}return!1}var b1l=h(()=>{"use strict";xo();yl();Gb();Lu();ywl();vwl();Swl();tst();n1l();i5r();c1l();y1l()});function E1l(e,t,r,n){let i=[],o=v1l(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=Vlm({operation:a.operation}),l=vjo({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:c});l&&i.push(l)}return i}function I1l(e,t,r,n){let i=[],o=v1l(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=vjo({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});c&&i.push(c)}return i}function v1l(e){let t=[];return e.get!=null&&t.push({method:mT.Get,operation:e.get}),e.post!=null&&t.push({method:mT.Post,operation:e.post}),e.put!=null&&t.push({method:mT.Put,operation:e.put}),e.delete!=null&&t.push({method:mT.Delete,operation:e.delete}),e.patch!=null&&t.push({method:mT.Patch,operation:e.patch}),e.head!=null&&t.push({method:mT.Head,operation:e.head}),t}function Vlm({operation:e}){return Fr(e,[un.WEBHOOK])??!1}var C1l=h(()=>{"use strict";Ic();yl();Lu();b1l()});function x1l(e){let t=Fr(e,un.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Fr(e,un.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}var S1l=h(()=>{"use strict";yl();Lu()});function w1l(e){return Fr(e,un.FERN_BASIC_AUTH)}var T1l=h(()=>{"use strict";yl();Lu()});function P1l(e,t,r,n){if(Mn(e)){if(n==null)throw new T({message:`Converting referenced security schemes requires context: ${JSON.stringify(e)}`,code:T.Code.InternalError});let i=n.resolveSecuritySchemeReference(e);return O1l(i,t,r)}return O1l(e,t,r)}function O1l(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=Fr(e,sB.BEARER_FORMAT),i=Fr(e,un.FERN_HEADER_AUTH);return dT.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??Fr(e,un.HEADER_VARIABLE_NAME),headerEnvVar:i?.env,headerPlaceholder:i?.placeholder})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=Fr(e,un.FERN_BEARER_TOKEN);return dT.bearer({tokenVariableName:n?.name??Fr(e,un.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env,tokenPlaceholder:n?.placeholder})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=w1l(e),i=x1l(e);return dT.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,usernamePlaceholder:n?.username?.placeholder,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env,passwordPlaceholder:n?.password?.placeholder})}else{if(e.type==="openIdConnect")return dT.bearer({tokenVariableName:void 0,tokenEnvVar:void 0,tokenPlaceholder:void 0});if(e.type==="oauth2")return dT.oauth({scopesEnum:Glm(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function Glm(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Exe({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([o,s])=>[o,{description:s}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=$f(n);if(i.type==="enum")return i}}var B1l=h(()=>{"use strict";Ic();Bt();yl();PVr();Kot();Gb();M3e();Lu();S1l();T1l()});function D1l({document:e,context:t}){return NUt(e,un.GROUPS,qlm,t.logger)}var qlm,R1l=h(()=>{"use strict";nn();yl();Lu();qlm=Xt.record(Xt.string(),Xt.object({summary:Xt.string().optional(),description:Xt.string().optional()}))});function k1l({context:e,document:t}){return Fr(t,un.FERN_VERSION)??void 0}var F1l=h(()=>{"use strict";yl();Lu()});function N1l(e){let t=Fr(e,un.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({header:n.header,name:n.name,optional:n.optional,env:n.env,clientDefault:n["x-fern-default"],schema:n.type!=null?MUt({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}var j1l=h(()=>{"use strict";yl();Lu();xVr()});function z1l(e){let t=Fr(e,un.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?MUt({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}var Q1l=h(()=>{"use strict";yl();Lu();xVr()});function M1l(e,t){let r=Fr(e,un.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{schema:{nameOverride:void 0,generatedName:JA([n],t),title:i.title,schema:ru.string({default:Jot(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0},envVar:Wlm(n,i)}];throw new T({message:`Variable ${n} has unsupported schema ${JSON.stringify(i)}`,code:T.Code.ValidationError})}))}function Wlm(e,t){let r=Fr(t,un.SDK_VARIABLE_ENV);if(r==null)return;let n=typeof r=="string"?r.trim():void 0;if(n==null||n.length===0)throw new T({message:`Variable ${e} has invalid ${un.SDK_VARIABLE_ENV}: expected a non-empty string but got ${JSON.stringify(r)}`,code:T.Code.ValidationError});return n}var L1l=h(()=>{"use strict";Ic();Bt();yl();YNo();Gte();Lu()});function _1l(e){return Fr(e,Hlm)??{}}var Hlm,U1l=h(()=>{"use strict";yl();Hlm="webhooks"});function V1l(e){let t=Klm(e),r={};return Cjo({obj:t,occurrences:r,breadcrumbs:[]}),r}function Cjo({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)Cjo({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)Cjo({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function Klm(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?YUt(r.get):void 0,put:r?.put!=null?YUt(r.put):void 0,post:r?.post!=null?YUt(r.post):void 0,patch:r?.patch!=null?YUt(r.patch):void 0,delete:r?.delete!=null?YUt(r.delete):void 0}]))}}function YUt(e){return{...e,requestBody:e.requestBody!=null?Mn(e.requestBody)?e.requestBody:Jlm(e.requestBody):void 0}}function Jlm(e){let t,r;for(let n in e.content){let i=gp.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[gp.MULTIPART_FORM_DATA]:r}}:e}var G1l=h(()=>{"use strict";mt();Gb()});var o5r,q1l=h(()=>{"use strict";lo();o5r=class{endpoints;parser=new hde;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let n=[];for(let i of r){let o=this.parser.tryParse(i);if(o==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${o.method} ${o.path}`)}return n}}});var W1l,H1l,K1l,J1l,Y1l,rst,xjo=h(()=>{"use strict";Bt();yl();G1l();Gb();HUt();Lu();q1l();W1l="#/components/parameters/",H1l="#/components/responses/",K1l="#/components/examples/",J1l="#/components/requestBodies/",Y1l="#/components/securitySchemes/",rst=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;schemaNamespaceMapping;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s,refOccurrences:a}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=a??V1l(t),this.options=i,this.source=o,this.filter=new o5r({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=s,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Mn(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(W1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(W1l.length),n=this.document.components.parameters[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(J1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(J1l.length),n=this.document.components.requestBodies[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(H1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(H1l.length),n=this.document.components.responses[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(K1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(K1l.length),n=this.document.components.examples[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(Y1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(Y1l.length),n=this.document.components.securitySchemes[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;let r=this.namespace!=null?K3e(this.options):void 0;for(let[n,i]of Object.entries(this.document.components.schemas))if(!(!i||Mn(i))){if(n===r){t.set(n,void 0);continue}t.set(n,Fr(i,un.SDK_NAMESPACE)||this.namespace)}return t}}});var s5r,X1l=h(()=>{"use strict";xjo();s5r=class extends rst{constructor({document:t,taskContext:r,options:n,source:i,namespace:o,refOccurrences:s}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o,refOccurrences:s})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}}});var nst,Z1l=h(()=>{"use strict";xjo();X1l();nst=class extends rst{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s}){super({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s})}getDummy(){return new s5r({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace,refOccurrences:this.refOccurrences})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}}});function $1l(e){return Fr(e,un.RESOLUTIONS)}var eTl=h(()=>{"use strict";yl();Lu()});function tTl({openapi:e}){let t=$1l(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let o of n.resolutions)e=Ylm({openapi:e,schemaReference:o,schemaName:n.name}),e=rTl({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function Ylm({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(o=>o.replaceAll("~1","/")),i=e;for(let o of n){let s=i[o];if(s==null)return e;i=s}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function rTl({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,l)=>l.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let l=r.replace(i,c);return rTl({openapi:e,replaceReference:t,schemaReference:l,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),s=e;for(let c of o.slice(0,-1)){let l=s[c];if(l==null)return e;s=l}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}var nTl=h(()=>{"use strict";eTl()});function oTl({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=QUt({document:e,options:r,logger:t.logger}),e=tTl({openapi:e}),NVr();let o=new nst({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([xe,Te])=>{let pe=P1l(Te,n,t,o);return pe==null?null:[xe,pe]}).filter(xe=>xe!==null)),a=JVr(e.security?.filter(xe=>xe!=null)),c=new Set(Object.entries(s).map(([xe,Te])=>Te.type==="basic"||Te.type==="bearer"||Te.type==="oauth"?"Authorization":Te.type==="header"?Te.headerName:null).filter(xe=>xe!=null)),l=M1l(e,r.preserveSchemaIds),u=N1l(e),p=Lwl(e),d=z1l(e),f=r.audiences??[],m=[],g=[],A=new nst({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i}),b=i!=null?K3e(r):void 0,I=b!=null&&e.components?.schemas?.[b]!=null?new nst({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:void 0}):A;A.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied...");let C=$xl(e);if(C?.pathsIncludeBasePath){let xe=jUt({openApi:e,basePath:C.basePath,rootPathParameterNames:new Set(C.pathParameters.map(Te=>Te.name))});for(let Te of xe)t.logger.warn(Te)}let x=r.respectPerSpecBasePath&&C!=null&&C.pathParameters.length===0?C.basePath:void 0;Object.entries(e.paths??{}).forEach(([xe,Te])=>{if(Te==null)return;let pe=E1l(xe,Te,e,A);for(let ue of pe){let Pe=iTl({operation:ue});if(!(f.length>0&&!f.some(Ie=>Pe.includes(Ie))))switch(ue.type){case"async":m.push(...XUt(ue.sync,x)),m.push(...XUt(ue.async,x));break;case"http":m.push(...XUt(ue.value,x));break;case"streaming":m.push(...XUt(ue.streaming,x)),ue.nonStreaming&&m.push(...XUt(ue.nonStreaming,x));break;case"webhook":g.push(...ue.value);break;default:Ye(ue)}}}),Object.entries(_1l(e)).forEach(([xe,Te])=>{if(Te==null)return;t.logger.debug(`Converting path ${xe}`);let pe=I1l(xe,Te,e,A);for(let ue of pe){let Pe=iTl({operation:ue});f.length>0&&!f.some(Ie=>Pe.includes(Ie))||g.push(...ue.value)}});let S=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([xe,Te])=>{if(xe===b)return[xe,Fa(Te,!1,!1,I,[xe],n,void 0)];let pe=Fr(Te,un.SDK_NAMESPACE);if(!Mn(Te)){let ue=Fr(Te,un.IGNORE);if(ue!=null&&ue)return[];if(Ywl.has(xe))return[xe,Fa({...Te,"x-fern-type-name":`${xe}Body`},!1,!1,A,[xe],n,pe??i)]}return[xe,Fa(Te,!1,!1,A,[xe],n,pe??i)]}).filter(xe=>xe.length>0)),P=Xlm(S,A,n),D=eum(P,A),R=new Cxe(D,A.nonRequestReferencedSchemas,A),O=Vte(),j={};for(let[xe,Te]of Object.entries(D)){let pe=r.objectSchemaExamples?sTl($f(Te),Te,R):$f(Te);if(A.isSchemaExcluded(xe))continue;let ue=O.getUniqueSchemaId(xe,A.logger,r.resolveSchemaCollisions);j[ue]=pe}let Y=g.map(xe=>{let pe=xe.examples;if(!r.disableExamples&&pe.length===0){let ue=R.buildExample({schema:xe.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ue!=null&&(pe=[{name:void 0,description:void 0,payload:ue}])}return{...xe,payload:$f(xe.payload),examples:pe}}),ee=new _Vr(D,A,u),te=m.map(xe=>{let Te=xe.examples,pe=Te;if(!r.disableExamples&&(Te.length===0||Te.every(WUt))){let Ie=ee.buildEndpointExample(xe);Ie.length>0&&(pe=[...Ie,...Te.filter(je=>!WUt(je))])}let ue=xe.request,Pe=xe.response;return{...xe,request:ue?.type==="json"||ue?.type==="formUrlEncoded"?{...ue,schema:$f(ue.schema)}:ue,response:Pe?.type==="json"?{...Pe,schema:$f(Pe.schema)}:Pe,queryParameters:xe.queryParameters.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,explode:Ie.explode,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),pathParameters:xe.pathParameters.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,variableReference:Ie.variableReference,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),headers:xe.headers.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,env:Ie.env,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),examples:pe,errors:hp(xe.errors,Ie=>{let je=Ie.fullExamples?.map(_e=>{let at=vxe(_e.value);if(at!=null)return{name:_e.name,description:_e.description,example:at}}).filter(gs);if(je?.length===0){let _e=R.buildExample({schema:Ie.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});_e!=null&&je.push({name:void 0,description:void 0,example:_e})}return{generatedName:Ie.generatedName,nameOverride:Ie.nameOverride,isWildcardStatusCode:Ie.isWildcardStatusCode,schema:$f(Ie.schema),description:Ie.description,source:Ie.source,examples:je,namespace:Ie.namespace,isShared:Ie.isShared}}),retries:xe.retries,globalParameterIds:xe.globalParameterIds}});ee.finalize();let ce=D1l({document:e,context:A}),le=Fr(e,un.BASE_URL_ENV),ae;return le!=null&&(typeof le=="string"&&le.length>0?ae=le:t.logger.warn(`Expected a non-empty string value for ${un.BASE_URL_ENV}; ignoring.`)),{apiVersion:k1l({context:A,document:e}),specVersion:e.info.version!=null&&e.info.version.length>0?e.info.version:void 0,baseUrlEnv:ae,basePath:C!=null&&(!r.respectPerSpecBasePath||C.pathParameters.length>0)?C.basePath:void 0,basePathParameters:C!=null&&C.pathParameters.length>0?C.pathParameters:void 0,title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(ce??{}).map(([xe,Te])=>[xe,{summary:Te.summary??void 0,description:Te.description??void 0}])),servers:(e.servers??[]).map(xe=>$Vr(xe,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(xe=>[xe.name,{id:xe.name,description:xe.description}])),orderedTagIds:e.tags?.map(xe=>xe.name)},endpoints:te,webhooks:Y,channels:{},groupedSchemas:Xot(i,j,b),securitySchemes:s,security:a,hasEndpointsMarkedInternal:te.some(xe=>xe.internal),nonRequestReferencedSchemas:A.getReferencedSchemas(),variables:l,globalHeaders:u,globalParameters:p.length>0?p:void 0,idempotencyHeaders:d}}function Xlm(e,t,r){if(t.options.removeDiscriminantsFromSchemas===Qr.RemoveDiscriminantsFromSchemas.Never)return e;let n=$lm(e,t),i={};for(let[o,s]of Object.entries(e)){if(s.type!=="object"){i[o]=s;continue}let a={$ref:`#/components/schemas/${o}`},c=t.getReferencesFromDiscriminatedUnion(a);if(c==null){i[o]=s;continue}if(t.getReferencedSchemas().has(o)){i[o]=s;continue}let u={...s,type:"object",properties:s.properties.filter(d=>!c.discriminants.has(d.key)),allOfPropertyConflicts:s.allOfPropertyConflicts.filter(d=>!c.discriminants.has(d.propertyKey)),source:r};i[o]=u;let p=Sjo({schema:s,schemas:e});for(let d of[...new Set(p)]){if(n.has(d))continue;let f=i[d]??e[d];f==null||f.type!=="object"||(i[d]={...f,type:"object",properties:f.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:f.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return i}function Zlm(e,t){if(t==null||t==="/")return e;let r=Xh(t);if(e===r||e.startsWith(`${r}/`))return e;let n=e.replace(/^\/+/,"");return n.length>0?`${r}/${n}`:r}function XUt(e,t){return t==null||t==="/"?e:e.map(r=>({...r,path:Zlm(r.path,t)}))}function $lm(e,t){let r=new Set;for(let[n,i]of Object.entries(e)){if(i.type!=="object")continue;let o={$ref:`#/components/schemas/${n}`};if(t.getReferencesFromDiscriminatedUnion(o)==null)for(let s of Sjo({schema:i,schemas:e}))r.add(s)}return r}function eum(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let o={$ref:`#/components/schemas/${n}`},s=t.getDiscriminatedUnionMetadata(o);if(s==null){r[n]=i;continue}let a=[];for(let l of i.properties)if(s.discriminants.has(l.key)){let u=s.discriminants.get(l.key);u!=null&&a.push({...l,schema:Gr.literal({nameOverride:void 0,generatedName:JA([i.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:ky.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(l);let c={...i,type:"object",properties:a};r[n]=c}return r}function Sjo({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...Sjo({schema:i,schemas:t}))}return r}function a5r(e){return[...new Set(e)]}function iTl({operation:e}){let t=[];switch(e.type){case"async":t=a5r(e.async.flatMap(r=>r.audiences));break;case"http":t=a5r(e.value.flatMap(r=>r.audiences));break;case"streaming":t=a5r(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=a5r(e.value.flatMap(r=>r.audiences));break;default:Ye(e)}return t}function sTl(e,t,r){if(e.type==="nullable"&&t.type==="nullable")return{...e,value:sTl(e.value,t.value,r)};if(e.type!=="object"||t.type!=="object")return e;let n={ignoreOptionals:!1,isParameter:!1,maxDepth:3,maxCheckerDepth:5},i=t.fullExamples??[],o=i.length>0?i.map(s=>r.buildExample({schema:t,example:s.value,exampleId:s.name,skipReadonly:!1,options:n})).filter(gs):tum(t,r,n);return o.length>0?{...e,examples:o}:e}function tum(e,t,r){let n=new Set(e.properties.filter(a=>t.hasExample(a.schema,0,new Set,r)).map(a=>a.key));if(n.size===0)return[];let i=a=>a.schema.type!=="optional"&&a.schema.type!=="nullable";if(e.properties.some(a=>i(a)&&!n.has(a.key)))return[];let o=t.buildExample({schema:e,example:void 0,exampleId:void 0,skipReadonly:!1,options:r});if(o==null||o.type!=="object")return o==null?[]:[o];let s=Object.fromEntries(Object.entries(o.properties).filter(([a])=>n.has(a)));return[oc.object({properties:s})]}var aTl=h(()=>{"use strict";yo();mt();Ic();xo();yl();sR();QVr();MVr();Kot();Gte();Gb();HUt();zVr();cjo();LUt();C1l();B1l();fjo();yjo();rjo();Lu();ONo();R1l();F1l();j1l();pjo();Q1l();L1l();DNo();U1l();tjo();Z1l();nTl()});function J3e({context:e,documents:t,options:r}){let n={apiVersion:void 0,specVersion:void 0,baseUrlEnv:void 0,title:void 0,description:void 0,basePath:void 0,basePathParameters:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],globalParameters:void 0,idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let s=o.source!=null?o.source:oR.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=oTl({taskContext:e,openApi:o.value,options:U5({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=lum(n,a,U5({options:o.settings,overrides:r}),e),i++;break}case"asyncapi":{let a=hwl({document:o.value,taskContext:e,options:U5({options:o.settings,overrides:r}),source:s,asyncApiOptions:rum({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(c=>({...c,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),a.channels!=null&&(n.channels={...n.channels,...a.channels}),a.groupedSchemas!=null&&(n.groupedSchemas=c5r(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath),i++;break}default:Ye(o)}}catch(s){e.logger.error(`Failed to parse ${o.type} document ${o.type==="openapi"?o.value.info?.title:o.source?.file}`),s instanceof Error&&e.logger.error(s.message,s.stack?`
|
|
296
|
+
`);try{Zot.writeFileSync(n,i,"utf8"),this.logger.info(`Missing examples report written to: ${n}`)}catch(o){this.logger.warn(`Failed to write missing examples report to ${n}:`,String(o))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"map":{let r={};return t.value.forEach(n=>{r[String(n.key)]=this.convertExampleToJson(n.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=kcm(t.request),n=Fcm(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let p=this.isSchemaRequired(r.schema);if(r.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:ejo(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});d!=null?(i.push([void 0,d]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:d,value:f}of r.examples){let m=this.exampleTypeFactory.buildExample({skipReadonly:ejo(t.method),schema:r.schema,exampleId:d,example:f,options:{isParameter:!1,ignoreOptionals:!0}});m!=null?i.push([d,m]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(p&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];if(n!=null&&n.type==="present"){let p=this.isSchemaRequired(n.schema);if(n.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});d!=null?(t.response?.type==="json"?o.push([void 0,L5.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,L5.withStreaming({sse:t.response?.type==="streamingSse",events:[d]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(n.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(n.schema)})}else for(let{name:d,value:f}of n.examples){let m=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:d,example:f,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});m!=null?t.response?.type==="json"?o.push([d,L5.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,L5.withStreaming({sse:t.response?.type==="streamingSse",events:[m]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(n.schema)})}if(p&&o.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let s=[];for(let p of t.pathParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for path parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&s.push({name:p.name,parameterNameOverride:p.parameterNameOverride,value:f})}let a=[];for(let p of t.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&f.type!=="array"&&(this.logger.debug(`Expected a primitive or array example but got ${f.type} for query parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&a.push({name:p.name,value:f})}let c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&c.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?q5(p.schema):Gr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Li.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),f=this.exampleTypeFactory.buildExample({schema:d,exampleId:void 0,example:void 0,options:{name:p.header,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),f!=null&&c.push({name:p.header,value:f})}let l=[];t.request!=null&&t.response!=null?l=Rcm(i,o):t.request!=null?l=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(l=o.map(([p,d])=>({id:p,request:void 0,response:d})));let u=t.examples.filter(p=>WUt(p)).flatMap(p=>{if(p.type==="unknown"){if(p.value!=null){let d=p.value["code-samples"];if(d!=null)return this.convertCodeSamples(d)}return}else return p.codeSamples}).filter(p=>gs(p));return l.length===0?[M5.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:void 0,response:void 0,codeSamples:u})]:l.map(({id:p,request:d,response:f})=>M5.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:d,response:f,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?Fte.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):Fte.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?hT.Csharp:r.sdk,code:r.code})).filter(gs)}isSchemaRequired(t){return LVr(this.getResolvedSchema(t))}getResolvedSchema(t){return t}}});var $ot,njo=h(()=>{"use strict";Bt();rjo();sR();MVr();Gb();$No();$ot=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Cxe(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let s=[];for(let a of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let l=[];for(let p of n.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.headers?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!TK(f)&&(f=void 0),!(d&&f==null)&&f!=null&&l.push({name:p.name,value:f})}let u=[];for(let p of a.messages){let d=t.getExampleMessageReference(p),f=t.resolveMessageReference({$ref:d}),m=Mn(f.payload)?t.resolveSchemaReference(f.payload):f.payload,g=this.exampleTypeFactory.buildExample({schema:Fa(m,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});g!=null&&u.push({messageType:p.type,payload:g,description:void 0})}s.push({name:a.summary,queryParameters:c,headers:l,description:a.description,messages:u})}return s}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let s of t.queryParameters){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!TK(c)&&(c=void 0),a&&c==null)return;c!=null&&i.push({name:s.name,value:c})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!TK(c)&&(c=void 0),a&&c==null)return;c!=null&&o.push({name:s.name,value:c})}for(let s of r){let a=this.exampleTypeFactory.buildExample({schema:s.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});a!=null&&n.messages.push({messageType:s.type,payload:a,description:void 0})}return n}isSchemaRequired(t){return LVr(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new T({message:`Unexpected error: Failed to resolve schema reference: ${t.schema}`,code:T.Code.InternalError});t=r}return t}}});var Ny,UVr=h(()=>{"use strict";Ny={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name",FERN_SERVER_NAME:"x-fern-server-name"}});function VVr(e){return Fr(e,Ny.FERN_EXAMPLES)??[]}var ijo=h(()=>{"use strict";yl();UVr()});function GVr(e,t){return t.includes("://")?t:`${e}://${t}`}function qVr(e){return e.startsWith("/")?e:"/"+e}var ojo=h(()=>{"use strict"});function awl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[l,u]of Object.entries(i.components?.schemas??{})){let p=Fa(u,!1,!1,e,[l],r,e.namespace);o[l]=p}let a=new $ot(o,e),c={};for(let[l,u]of Object.entries(i.servers??{})){let p=Fr(u,Ny.FERN_SERVER_NAME);c[l]={name:p??l,url:GVr(u.protocol,u.url)}}for(let[l,u]of Object.entries(i.channels??{})){let p=Fr(u,Ny.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${l} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(u.parameters!=null)for(let[b,I]of Object.entries(u.parameters??{})){let C=Fr(I,Ny.FERN_PARAMETER_NAME);d.push({name:b,description:I.description,parameterNameOverride:C,schema:I.schema!=null?Fa(I.schema,!1,!1,e,t,r,e.namespace):Gr.primitive({schema:Li.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:AC(I),source:r,explode:void 0,clientDefault:void 0})}let f=[],m=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let b=u.bindings.ws.headers.required??[];for(let[I,C]of Object.entries(u.bindings.ws.headers.properties??{})){if(Mn(C)){let D=e.resolveSchemaReference(C),R=b.includes(I),[O,j]=e.options.coerceOptionalSchemasToNullable?[!1,!R]:[!R,!1];f.push({name:I,schema:V_(C,O,j,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:AC(D),source:r,clientDefault:void 0});continue}let x=b.includes(I),[S,P]=e.options.coerceOptionalSchemasToNullable?[!1,!x]:[!x,!1];f.push({name:I,schema:Fa(C,S,P,e,[...t,I],r,e.namespace),description:C.description,parameterNameOverride:void 0,env:void 0,availability:AC(C),source:r,clientDefault:void 0})}}if(u.bindings.ws.query!=null){let b=u.bindings.ws.query.required??[];for(let[I,C]of Object.entries(u.bindings.ws.query.properties??{})){if(Mn(C)){let D=e.resolveSchemaReference(C),R=b.includes(I),[O,j]=e.options.coerceOptionalSchemasToNullable?[!1,!R]:[!R,!1];m.push({name:I,schema:V_(C,O,j,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:AC(D),source:r,explode:void 0,clientDefault:void 0});continue}let x=b.includes(I),[S,P]=e.options.coerceOptionalSchemasToNullable?[!1,!x]:[!x,!1];m.push({name:I,schema:Fa(C,S,P,e,[...t,I],r,e.namespace),description:C.description,parameterNameOverride:void 0,availability:AC(C),source:r,explode:void 0,clientDefault:void 0})}}}let g;u.publish!=null&&("oneOf"in u.publish.message?g=owl({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=swl({action:"Publish",channelPath:l,message:u.publish.message,context:e,source:r}));let A;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?A=owl({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):A=swl({action:"Subscribe",channelPath:l,message:u.subscribe.message,context:e,source:r})),f.length>0||m.length>0||g!=null||A!=null){let b=VVr(u),I=[];if(b.length>0)I=a.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:b,handshake:{headers:f,queryParameters:m},source:r,namespace:e.namespace});else{let P=[];g!=null&&P.push({type:"publish",payload:g}),A!=null&&P.push({type:"subscribe",payload:A});let D=a.buildWebsocketSessionExample({handshake:{headers:f,queryParameters:m},messages:P});D!=null&&I.push(D)}let C=Fr(u,Ny.FERN_CHANNEL_ADDRESS),x=C??qVr(l),S=[];g!=null&&S.push({origin:"client",name:"publish",displayName:u.publish!=null?Fr(u.publish,Ny.FERN_DISPLAY_NAME):void 0,description:u.publish?.description,body:$f(g),methodName:u.publish!=null?Fr(u.publish,Ny.FERN_SDK_METHOD_NAME):void 0}),A!=null&&S.push({origin:"server",name:"subscribe",displayName:u.subscribe!=null?Fr(u.subscribe,Ny.FERN_DISPLAY_NAME):void 0,description:u.subscribe?.description,body:$f(A),methodName:u.subscribe!=null?Fr(u.subscribe,Ny.FERN_SDK_METHOD_NAME):void 0}),s[l]={audiences:Fr(u,un.AUDIENCES)??[],handshake:{headers:f.map(P=>({...P,schema:$f(P.schema),env:P.env})),queryParameters:m.map(P=>({...P,schema:$f(P.schema)})),pathParameters:d.map(P=>({...P,schema:$f(P.schema)}))},groupName:e.resolveGroupName([Fr(u,Ny.FERN_SDK_GROUP_NAME)??l]),messages:S,servers:(u.servers?.map(P=>c[P])??Object.values(c)).filter(P=>P!=null&&P.name!=null).map(P=>({...P,name:P.name})),summary:Fr(u,Ny.FERN_DISPLAY_NAME),connectMethodName:Fr(u,Ny.FERN_SDK_METHOD_NAME),path:x,description:u.description,examples:I,source:r}}}return{groupedSchemas:Xot(e.namespace,o),channels:s??void 0,servers:Object.values(c).map(l=>({...l,name:l.name})),basePath:Fr(i,Ny.BASE_PATH)}}function owl({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:s}){if("oneOf"in t.message&&t.message.oneOf!=null){let a=[],c=[];for(let l of t.message.oneOf){let u,p={type:"notFound"};if(Mn(l)){let d=r.resolveMessageReference(l);!Mn(d.payload)&&s.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,u={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):u=d.payload}else u=l;c.push(p),a.push(u)}return Ixe({description:t.description??t.message.description,availability:AC(t.message),subtypes:a,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:s.naming==="v2"?c:[]})}}function swl({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return Mn(r.payload)&&(o=n.resolveSchemaReference(r.payload)),Fa(o,!1,!1,n,[t,e],i,n.namespace)}}var cwl=h(()=>{"use strict";Ic();yl();Lu();Hot();sR();JNo();Kot();Gb();zVr();njo();UVr();ijo();ojo()});var WVr,lwl=h(()=>{"use strict";mt();Bt();ZNo();WVr=class extends Yot{getExampleMessageReference(t){let r=t.channelId??this.getDefaultChannelId();if(r==null)throw new T({message:"Cannot resolve example message reference: no channelId provided and no channels found in document",code:T.Code.InternalError});return`#/channels/${r}/messages/${t.messageId}`}getDefaultChannelId(){return Object.keys(this.document.channels??{})[0]}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new T({message:"Cannot resolve message reference: message is null or undefined",code:T.Code.InternalError});if(!t.$ref)throw new T({message:"Cannot resolve message reference: message.$ref is undefined or empty",code:T.Code.ReferenceError});if(t.$ref.startsWith(n)){let c=t.$ref.split("/"),l=c[2],u=c[4],p=l!=null?D0(l):void 0;if(p==null||u==null||!this.document.channels?.[p])throw new T({message:`Failed to resolve message reference ${t.$ref} in channel ${p}`,code:T.Code.ReferenceError});let f=this.document.channels[p].messages?.[u];if(f==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return"$ref"in f&&!r?this.resolveMessageReference(f):{...f,name:u}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new T({message:`Failed to resolve message reference: ${t.$ref} in v3 components`,code:T.Code.ReferenceError});let s=t.$ref.substring(i.length),a=o.messages[s];if(a==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return{...a,name:s}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}}});function dwl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){NVr();let o={},s={},a={},c=[],l={};e.logger.debug("Parsing V3 AsyncAPI...");let u=Vte();for(let[D,R]of Object.entries(i.components?.schemas??{})){let O=u.getUniqueSchemaId(D,e.logger,e.options.resolveSchemaCollisions);o[O]=Fa(R,!1,!1,e,[O],r,e.namespace)}for(let[D,R]of Object.entries(i.channels??{}))if(s[D]||(s[D]={}),R.messages)for(let[O,j]of Object.entries(R.messages))if(a[O]||(a[O]=[]),e.isReferenceObject(j)){let Y=e.resolveMessageReference(j);a[O].push({channelId:D,payload:Y.payload})}else e.isMessageWithPayload(j)&&a[O].push({channelId:D,payload:j.payload});for(let[D,R]of Object.entries(a))if(R.length===1){let O=R[0],j=O.channelId;s[j]=s[j]||{},s[j][D]=Fa(O.payload,!1,!1,e,[D],r,e.namespace)}else{c.push(D);for(let{channelId:O,payload:j}of R){let Y=`${O}_${D}`;s[O]||(s[O]={}),s[O][Y]=Fa(j,!1,!1,e,[Y],r,e.namespace)}}let p={},d=Vte();for(let[D,R]of Object.entries(s))for(let[O,j]of Object.entries(R)){let Y=d.getUniqueSchemaId(O,e.logger,e.options.resolveSchemaCollisions);p[Y]=j}let f=new $ot({...o,...p},e),m={};for(let[D,R]of Object.entries(i.servers??{})){let O=Fr(R,Ny.FERN_SERVER_NAME);m[D]={name:O??D,url:GVr(R.protocol,R.host)}}let g={},A=Object.keys(i.channels??{});for(let[D,R]of Object.entries(i.operations??{})){if(Fr(R,Ny.IGNORE))continue;let O;if(R.channel==null||!("$ref"in R.channel)||R.channel.$ref==null)if(A.length===1&&A[0]!=null)O=A[0];else continue;else O=jcm(R);g[O]||(g[O]={subscribe:[],publish:[],__parsedMessages:[]});let j=Fr(R,Ny.FERN_SDK_METHOD_NAME),Y=Fr(R,Ny.FERN_DISPLAY_NAME);if(!R.messages||!Array.isArray(R.messages))continue;let ee=R.messages.filter(ce=>ce!=null&&ce.$ref!=null).map(ce=>({ref:ce,methodName:j,displayName:Y})),te=g[O];if(te==null)throw new T({message:`Internal error: channelEvents["${O}"] is unexpectedly undefined for operation ${D}`,code:T.Code.InternalError});if(R.action==="receive")te.subscribe.push(...ee);else if(R.action==="send")te.publish.push(...ee);else throw new T({message:`Operation ${D} has an invalid action: ${R.action}`,code:T.Code.ValidationError})}for(let[D,R]of Object.entries(g)){let O=[];O.push(...fwl({messages:R.subscribe,channelPath:D,origin:"server",messageSchemas:s[D]??{},duplicatedMessageIds:c,context:e})),O.push(...fwl({messages:R.publish,channelPath:D,origin:"client",messageSchemas:s[D]??{},duplicatedMessageIds:c,context:e})),g[D]!=null&&(g[D].__parsedMessages=O)}for(let[D,R]of Object.entries(i.channels??{})){if(Fr(R,Ny.IGNORE))continue;let O=[],j=[],Y=[];if(R.parameters!=null)for(let[ee,te]of Object.entries(R.parameters)){let ce=e.isReferenceObject(te)?e.resolveParameterReference(te):te,{type:le,parameterKey:ae}=ce.location!=null?zcm(ce.location):{type:R.address?.includes(`={${ee}}`)?"query":"path",parameterKey:ee},he=Fr(ce,Ny.FERN_PARAMETER_OPTIONAL),xe=dx(ao(D))+dx(ao(ee)),Te=ce.schema!=null?Mn(ce.schema)?V_(ce.schema,!1,!1,e,[ae],void 0,r,e.namespace):Fa(ce.schema,!1,!1,e,[ae],r,e.namespace):Fa({...ce,type:"string",title:xe,example:ce.examples?.[0],default:ce.default,enum:ce.enum,required:void 0},!1,!1,e,[ae],r,e.namespace),pe=he?Gr.optional({value:Te,description:void 0,availability:void 0,generatedName:"",title:xe,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Te,ue={name:ae,description:ce.description,parameterNameOverride:void 0,schema:pe,variableReference:void 0,availability:AC(te),source:r,explode:void 0,clientDefault:void 0};le==="header"?O.push({...ue,env:void 0}):le==="path"?j.push(ue):(le==="payload"||le==="query")&&Y.push(ue)}if(R.bindings?.ws?.query!=null){let ee=new Set(Y.map(ce=>ce.name)),te=new Set(R.bindings.ws.query.required??[]);for(let[ce,le]of Object.entries(R.bindings.ws.query.properties??{})){if(ee.has(ce))continue;if(Mn(le)){let Te=e.resolveSchemaReference(le),pe=te.has(ce),[ue,Pe]=e.options.coerceOptionalSchemasToNullable?[!1,!pe]:[!pe,!1];Y.push({name:ce,schema:V_(le,ue,Pe,e,[D,ce],void 0,r,e.namespace),description:Te.description,parameterNameOverride:void 0,availability:AC(Te),source:r,explode:void 0,clientDefault:void 0});continue}let ae=te.has(ce),[he,xe]=e.options.coerceOptionalSchemasToNullable?[!1,!ae]:[!ae,!1];Y.push({name:ce,schema:Fa(le,he,xe,e,[D,ce],r,e.namespace),description:le.description,parameterNameOverride:void 0,availability:AC(le),source:r,explode:void 0,clientDefault:void 0})}}if(R.bindings?.ws?.headers!=null){let ee=new Set(O.map(ce=>ce.name)),te=new Set(R.bindings.ws.headers.required??[]);for(let[ce,le]of Object.entries(R.bindings.ws.headers.properties??{})){if(ee.has(ce))continue;if(Mn(le)){let Te=e.resolveSchemaReference(le),pe=te.has(ce),[ue,Pe]=e.options.coerceOptionalSchemasToNullable?[!1,!pe]:[!pe,!1];O.push({name:ce,schema:V_(le,ue,Pe,e,[D,ce],void 0,r,e.namespace),description:Te.description,parameterNameOverride:void 0,env:void 0,availability:AC(Te),source:r,clientDefault:void 0});continue}let ae=te.has(ce),[he,xe]=e.options.coerceOptionalSchemasToNullable?[!1,!ae]:[!ae,!1];O.push({name:ce,schema:Fa(le,he,xe,e,[D,ce],r,e.namespace),description:le.description,parameterNameOverride:void 0,env:void 0,availability:AC(le),source:r,clientDefault:void 0})}}if(O.length>0||Y.length>0||g[D]!=null&&(g[D].publish!=null||g[D].subscribe!=null)){let ee=VVr(R),te=g[D]?.__parsedMessages??[],ce=[];try{if(ee.length>0)ce=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:ee,handshake:{headers:O,queryParameters:Y},source:r,namespace:e.namespace});else{let Te=[],{examplePublishMessage:pe,exampleSubscribeMessage:ue}=Mcm({messages:te,messageSchemas:s[D]??{}});pe!=null&&Te.push(pe),ue!=null&&Te.push(ue);let Pe=f.buildWebsocketSessionExample({handshake:{headers:O,queryParameters:Y},messages:Te});Pe!=null&&ce.push(Pe)}}catch(Te){e.logger.warn(`Failed to build examples for channel ${D}: ${rn(Te)}`)}let le=Fr(R,Ny.FERN_SDK_GROUP_NAME),ae=Fr(R,Ny.FERN_SDK_METHOD_NAME),he=(R.servers?.map(Te=>Qcm(m,Te))??Object.values(m)).map(Te=>({...Te,name:Te.name})),xe=R.address?.split("?")[0]??qVr(D);l[D]={audiences:Fr(R,un.AUDIENCES)??[],handshake:{headers:O.map(Te=>({...Te,schema:$f(Te.schema),env:Te.env})),queryParameters:Y.map(Te=>({...Te,schema:$f(Te.schema)})),pathParameters:j.map(Te=>({...Te,parameterNameOverride:void 0,schema:$f(Te.schema)}))},groupName:e.resolveGroupName(typeof le=="string"?[le]:le??[D]),messages:te,summary:Fr(R,Ny.FERN_DISPLAY_NAME),connectMethodName:ae,servers:he,path:xe,description:R.description,examples:ce,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${D} as it does not qualify for inclusion (no headers, query params, or operations)`)}let b={...o,...p},I={},C=Vte();for(let[D,R]of Object.entries(b)){let O=C.getUniqueSchemaId(D,e.logger,e.options.resolveSchemaCollisions);I[O]=$f(R)}let x=Xot(e.namespace,o),S=Object.values(m).map(D=>({...D,name:D.name})),P=Fr(i,Ny.BASE_PATH);return{groupedSchemas:x,channels:l,servers:S,basePath:P}}function jcm(e){if(!e.channel)throw new T({message:"Operation is missing required 'channel' field",code:T.Code.ValidationError});if(!e.channel.$ref)throw new T({message:"Operation channel is missing required '$ref' field",code:T.Code.ValidationError});if(!e.channel.$ref.startsWith(uwl))throw new T({message:`Failed to resolve channel path from operation ${e.channel.$ref}`,code:T.Code.ReferenceError});return D0(e.channel.$ref.substring(uwl.length))}function zcm(e){let t="https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression",[r,n]=e.split("#/");if(r==null||n==null)throw new T({message:`Invalid location format: ${e}; unable to parse message type and parameter key. See ${t} for the expected format.`,code:T.Code.ValidationError});if(!r.startsWith(sjo))throw new T({message:`Invalid location format: ${e}; expected ${sjo} prefix`,code:T.Code.ValidationError});let i=r.substring(sjo.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new T({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,code:T.Code.ValidationError});return{type:i,parameterKey:n}}function Qcm(e,t){if(!t.$ref.startsWith(pwl))throw new T({message:`Failed to resolve server name from server ref ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(pwl.length),n=e[r];if(n==null)throw new T({message:`Failed to find server with name ${r}`,code:T.Code.ReferenceError});return n}function fwl({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,c)=>{try{let l=o.resolveMessageReference(a.ref,!0),u=o.resolveMessageReference(a.ref),p=l.name;i.includes(p)&&(p=`${t}_${p}`);let d=n[p];d!=null&&s.push({origin:r,name:p??`${r}Message${c+1}`,displayName:a.displayName,description:u.description??u.summary,body:$f(d),methodName:a.methodName})}catch(l){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${rn(l)}`)}}),s}function Mcm({messages:e,messageSchemas:t}){let r=e.find(s=>s.origin==="client")?.name,n=e.find(s=>s.origin==="server")?.name,i=r!=null?t[r]:void 0,o=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:o!=null&&n!=null?{type:n,payload:o}:void 0}}var uwl,pwl,sjo,mwl=h(()=>{"use strict";mt();Ic();Bt();xo();yl();W5();Hot();sR();Kot();Gb();zVr();LUt();njo();UVr();ijo();ojo();uwl="#/channels/",pwl="#/servers/",sjo="$message."});function hwl({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let s=[];if(o!=null&&s.push(o),parseFloat(e.asyncapi)<3){let a=e;a.tags?.[0]!=null?s.push(a.tags[0].name):i.naming!=="v2"&&s.push("websocket");let c=new jVr({document:a,taskContext:t,options:r,namespace:o});return awl({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,c=new WVr({document:a,taskContext:t,options:r,namespace:o});return dwl({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}var gwl=h(()=>{"use strict";ZSl();cwl();lwl();mwl()});function KVr({schema:e,name:t}){return t??e.title??HVr}function K3e(e){let t=e.errorResponses;if(!e.sharedErrorResponses||t==null)return;let r=t.schema;if(!(typeof r=="string"||"$ref"in r||ajo(r)))return KVr({schema:r,name:t.name})}function ajo(e){return Array.isArray(e)?e.some(ajo):e!=null&&typeof e=="object"?Object.entries(e).some(([t,r])=>t==="$ref"||ajo(r)):!1}var HVr,HUt=h(()=>{"use strict";HVr="ProblemDetails"});function JVr(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var cjo=h(()=>{"use strict"});function Awl(e){return Fr(e,un.ASYNC_CONFIG)}var ywl=h(()=>{"use strict";yl();Lu()});function Ewl(e,t){let r=Fr(t,un.STREAMING);if(r==null)return;if(typeof r=="boolean")return r?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=Lcm(e,r);if(r["stream-condition"]==null&&r.format!=null)return{type:"stream",format:r.format,terminator:r.terminator,resumable:n};if(r["stream-condition"]!=null)return{type:"streamCondition",format:r.format??"json",terminator:r.terminator,streamDescription:r["stream-description"],streamConditionProperty:_cm(r["stream-condition"]),streamRequestName:r["stream-request-name"],responseStream:r["response-stream"],response:r.response,resumable:n}}function Lcm(e,t){return typeof t.resumable=="boolean"?t.resumable:ljo(e)??!1}function ljo(e){let t=Fr(e,un.STREAMING);if(!(t==null||typeof t=="boolean"))return typeof t.resumable=="boolean"?t.resumable:void 0}function Iwl(e){let t=Fr(e,un.STREAMING);if(!(t==null||typeof t=="boolean"))return typeof t.resumable=="boolean"?t.resumable:void 0}function _cm(e){return e.startsWith(bwl)?e.slice(bwl.length):e}var bwl,vwl=h(()=>{"use strict";yl();Lu();bwl="$request."});function Cwl(e){let t=e;if(t.cursor!=null)return Iw.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return Iw.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return Iw.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return Iw.offset({offset:i.offset,results:i.results,step:i.step,hasNextPage:i["has-next-page"]})}if("type"in e&&e.type==="custom"){let i=e;return Iw.custom({results:i.results})}throw new T({message:"Invalid pagination extension",code:T.Code.ValidationError})}function xwl(e,t){let r=Fr(t,un.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=Fr(e,un.PAGINATION);if(typeof n=="boolean")throw new T({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",code:T.Code.ValidationError});return n==null?void 0:Cwl(n)}return Cwl(r)}}var Swl=h(()=>{"use strict";Ic();Bt();yl();Lu()});function wwl(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n,o=n.schema??i.itemSchema;return{contentType:r,schema:o??{},examples:est(n,t)}}}function Twl(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function Ucm(e){return e.includes("json")||e==="*/*"}function KUt({content:e,context:t}){for(let[r,n]of Object.entries(e))if(YVr({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function YVr({mediaType:e,mediaTypeObject:t,context:r}){if(!Ucm(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:est(t,r)}}function JUt({content:e,context:t}){let r=KUt({content:e,context:t});if(!r)return;let[n,i]=r;return YVr({mediaType:n,mediaTypeObject:i,context:t})}function Owl(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:est(n,t)}}}function est(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=Fr(e,sB.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let s=Mn(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}var tst=h(()=>{"use strict";yl();Gb();M3e()});var Vcm,ujo,Pwl=h(()=>{"use strict";nn();Vcm=Xt.object({lang:Xt.string(),label:Xt.optional(Xt.string()),source:Xt.string()}),ujo=Xt.array(Vcm)});var Bwl,Dwl=h(()=>{"use strict";Bwl={README_EXT:"x-readme"}});function Gcm(e){if(!Array.isArray(e))return!1;for(let t of e)if(!oi(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function Rwl(e){let t=Fr(e,Bwl.README_EXT);if(!oi(t))return[];let r=t["code-samples"];if(!Gcm(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}var kwl=h(()=>{"use strict";mt();yl();Dwl()});function qcm(e){return oi(e)&&typeof e.$ref=="string"}function Wcm(e,t){if(e!=null){if(typeof e=="string")return e;if(qcm(e)){let r=(0,ZVr.resolve)(t??process.cwd(),e.$ref);if((0,XVr.existsSync)(r))try{return(0,XVr.readFileSync)(r,"utf-8")}catch{return}}}}function Hcm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=Wcm(n.code,t);o!=null&&r.push({...n,code:o})}return r}function Fwl(e,t,r){let n=Fr(t,un.EXAMPLES),i=r.source.type==="openapi"?(0,ZVr.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!oi(p))return p;let f=p["code-samples"];if(f!=null){let m=Hcm(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=Qd.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=NUt(t,sB.REDOCLY_CODE_SAMPLES_KEBAB,ujo,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...NUt(t,sB.REDOCLY_CODE_SAMPLES_CAMEL,ujo,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&s.push({"code-samples":l.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let u=Rwl(t);return u.length>0&&s.push({"code-samples":u}),s.map(M5.unknown)}var XVr,ZVr,Nwl=h(()=>{"use strict";mt();lo();Ic();XVr=require("fs"),ZVr=require("path");yl();Pwl();M3e();Lu();kwl()});function jwl(e){let t=Fr(e,un.AVAILABILITY);if(t==="ga"||t==="generally-available")return ng.GenerallyAvailable;if(t==="beta"||t==="pre-release")return ng.Beta;if(t==="deprecated")return ng.Deprecated;if(t==="alpha")return ng.Alpha;if(t==="preview")return ng.Preview;if(t==="legacy")return ng.Legacy;if(e.deprecated)return ng.Deprecated}var zwl=h(()=>{"use strict";Ic();yl();Lu()});function Qwl(e){let t=Fr(e,un.RETRIES);if(t!=null&&t.disabled===!0)return Cm.RetriesConfiguration.disabled(t.disabled)}var Mwl=h(()=>{"use strict";Ic();yl();Lu()});function Kcm(e){return e["x-fern-default"]??e.default}function Lwl(e){let t=Fr(e,un.FERN_GLOBAL_PARAMETERS),r=[];for(let n of t??[])typeof n.name=="string"&&r.push({name:n.name,parameterName:n["parameter-name"],in:n.in,target:n.target,type:n.type,env:n.env,default:Kcm(n),optional:n.optional,apply:n.apply,docs:n.docs});return r}function _wl(e){let t=Fr(e,un.FERN_GLOBAL_PARAMETER);if(t!=null){if(typeof t=="string")return[t];if(Array.isArray(t))return t.filter(r=>typeof r=="string")}}var pjo=h(()=>{"use strict";yl();Lu()});function $Vr(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=Ycm(e);return{url:Zcm({url:e.url,variables:e.variables??{}}),description:e.description,name:$cm(e,t),audiences:Fr(e,un.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?Xcm(e.variables):void 0,defaultUrl:r?n:void 0}}function Ycm(e){let t=e[Jcm];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function Xcm(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function Zcm({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function $cm(e,t){let r=Fr(e,[un.SERVER_NAME_V1,un.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}var Jcm,fjo=h(()=>{"use strict";yl();Lu();Jcm="x-fern-default-url"});function Uwl(e){return Fr(e,un.PARAMETER_NAME)}var Vwl=h(()=>{"use strict";yl();Lu()});function Gwl(e){return Fr(e,un.SDK_VARIABLE)}var qwl=h(()=>{"use strict";yl();Lu()});function e5r({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let c=Mn(a)?n.resolveParameterReference(a):a,l=Fr(a,un.IGNORE)??Fr(c,un.IGNORE);if(l!=null&&l){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let u=c.required??!1,p=AC(c),d=[...i,c.name],f=JA(d,n.options.preserveSchemaIds),m=c.in==="header",[g,A]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!u]:[!u,!1],b=elm(c,n),I=b!=null?Fa(b,g,A,n,d,o,n.namespace,!1,new Set,ilm(c,n)):u?Gr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Li.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:V5({schema:c,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Gr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Gr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Li.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:V5({schema:c,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(c.in==="header"&&c.schema!=null&&!Mn(c.schema)&&c.schema.default!=null){let S=c.schema.default;typeof S=="string"&&S.length>0&&(I=Gr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:ky.string(S),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let C=Fr(a,un.FERN_DEFAULT)??Fr(c,un.FERN_DEFAULT),x={name:c.name,schema:I,description:rlm(c),parameterNameOverride:Uwl(c),availability:p,source:o,clientDefault:C};c.in==="query"?s.queryParameters.push({...x,explode:nlm(c)}):c.in==="path"?s.pathParameters.push({...x,variableReference:Gwl(c),explode:olm(c)}):c.in==="header"?!tlm.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?s.headers.push({...x,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return s}function elm(e,t){return e.schema!=null?e.schema:!t.options.respectParameterContent||e.in!=="header"||e.content==null?void 0:KUt({content:e.content,context:t})?.[1].schema}function rlm(e){if(e.description!=null)return e.description;if(!(e.schema==null||Mn(e.schema)))return e.schema.description}function nlm(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}function ilm(e,t){let r=DVr({schema:e,logger:t.logger});return r??V5({schema:e,logger:t.logger})}function olm(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}var tlm,djo=h(()=>{"use strict";Ic();yl();Hot();sR();XNo();Gte();Gb();Lu();Vwl();qwl();tst();tlm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"])});function slm({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Hwl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function Hwl({mediaType:e,mediaTypeObject:t,context:r}){if(gp.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:est(t,r)}}function alm({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Kwl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function Kwl({mediaType:e,mediaTypeObject:t,context:r}){if(gp.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:est(t,r)}}function Jwl({mediaType:e}){return gp.parse(e)?.isBinary()??!1}function clm({content:e}){for(let[t,r]of Object.entries(e))if(Jwl({mediaType:t}))return[t,r]}function llm(e,t){let r=Mn(e)?mjo(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!Mn(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function r5r({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}){let c=clm({content:e});if(c){let[f,m]=c;return qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a})}let l=alm({content:e,context:n}),u=KUt({content:e,context:n}),p=ulm({json:u,multipart:l,document:r,visitor:{json:([f,m])=>qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}),multipart:([f,m])=>qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a}),neither:()=>{}}});if(p)return p;let d=slm({content:e,context:n});if(d){let[f,m]=d;return qte({mediaType:f,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s,bodyRequired:a})}}function ulm({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,o]=t??[void 0,void 0];return!i?.schema&&!o?.schema?e&&(i?.example!=null||i?.examples!=null&&Object.keys(i.examples).length>0)?n.json(e):n.neither():i?.schema&&o?.schema?i.schema&&llm(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function qte({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a,bodyRequired:c}){let l=plm({mediaTypeObject:t});if(Jwl({mediaType:e}))return y2.octetStream({description:r,source:s,sdkMethodName:l,contentType:e});let u=Kwl({mediaType:e,mediaTypeObject:t,context:i}),p=u?.schema,d=u?.encoding,f=u?.examples;if(p){let A=Mn(p)?mjo(p,n):{id:void 0,schema:p},b=Fa(A.schema,!1,!1,i,o,s,a,!1),I=[];if(b.type==="object"){let C=new Set(A.schema.required??[]);for(let x of b.properties){let S=C.has(x.key),{isFile:P,isOptional:D,isArray:R,description:O}=t5r({schema:x.schema,isOptional:!S});if(P){let j=Wwl(x.key,d);I.push({key:x.key,schema:Nte.file({isOptional:D,isArray:R,description:O}),description:O,contentType:j,exploded:!1,encoding:j==null?i.options.defaultFormParameterEncoding:void 0})}else{let j=Wwl(x.key,d);I.push({key:x.key,schema:Nte.json(x.schema),description:void 0,contentType:j,exploded:d?.[x.key]?.explode,encoding:j==null?i.options.defaultFormParameterEncoding:dlm(j)})}}}return y2.multipart({name:Mn(p)&&i.getNumberOfOccurrencesForRef(p)===1?A.id:void 0,description:A.schema.description,properties:I,source:s,sdkMethodName:l,fullExamples:f})}let m=YVr({mediaType:e,mediaTypeObject:t,context:i});if(m){let A=Fa(m.schema,!1,!1,i,o,s,a,!0);return y2.json({description:void 0,schema:A,contentType:m.contentType,required:c,fullExamples:m.examples,additionalProperties:!Mn(m.schema)&&_Ut(m.schema.additionalProperties,i.options),source:s,sdkMethodName:l})}let g=Hwl({mediaType:e,mediaTypeObject:t,context:i});if(g!=null&&g.schema!=null){let A=Fa(g.schema,!1,!1,i,o,s,a,!1);return y2.formUrlEncoded({schema:A,description:r,contentType:g.contentType,source:s,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:l})}}function plm({mediaTypeObject:e}){return Fr(e,un.SDK_METHOD_NAME)}function dlm(e){return e?flm[e]:void 0}function mjo(e,t){if(!e.$ref.startsWith(W3e))throw new T({message:`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`,code:T.Code.ReferenceError});let r=bxe(e);if(r==null)throw new T({message:`Failed to resolve schema reference because missing schema id: ${e.$ref}`,code:T.Code.ReferenceError});let n=t.components?.schemas?.[r];if(n==null)throw new T({message:`Failed to resolve schema reference because missing: ${e.$ref}`,code:T.Code.ReferenceError});return Mn(n)?mjo(n,t):{id:r,schema:n}}function t5r({schema:e,isOptional:t,isArray:r,description:n}){return hlm(e)?t5r({schema:e.value,isOptional:!0,isArray:r,description:e.description}):glm(e)?t5r({schema:e.value,isOptional:t,isArray:r,description:e.description}):Alm(e)?t5r({schema:e.value,isOptional:t,isArray:!0,description:e.description}):mlm(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function mlm(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function hlm(e){return e.type==="optional"}function glm(e){return e.type==="nullable"}function Alm(e){return e.type==="array"}function Wwl(e,t){return t?.[e]?.contentType}var flm,hjo=h(()=>{"use strict";mt();Ic();Bt();yl();SVr();sR();Gb();Lu();tst();flm={"application/json":"json"}});function Xwl(e){switch(e.toUpperCase()){case ylm:return 400;case blm:return 500;default:return}}var gjo,ylm,blm,Ajo,Ywl,yjo=h(()=>{"use strict";gjo={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"},ylm="4XX",blm="5XX",Ajo={400:"ClientRequestError",500:"ServerError"},Ywl=new Set([...Object.values(gjo),...Object.values(Ajo)])});function n5r({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,streamTerminator:s,streamResumable:a,source:c}){if(t==null)return{value:void 0,errors:{}};let l=Ilm({responses:t,context:r,source:c,namespace:r.namespace}),u=!1,p=!1,d;for(let f of i!=null?[i]:Elm){let m=t[f];if(m==null)continue;u=!0;let g=typeof f=="string"?parseInt(f):f;if(d==null){let A=Zwl({operationContext:e,response:m,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,streamResumable:a,source:c,namespace:r.namespace,statusCode:g});A!=null?d=A:g===204&&(p=!0)}else if(g===204){let A=Mn(m)?r.resolveResponseReference(m):m;JUt({context:r,content:A.content??{}})!=null&&r.logger.warn(`${e.method.toUpperCase()} ${e.path}: the 204 response declares a body, but a 204 (No Content) response cannot include one. Ignoring the declared 204 body and treating the success response as optional.`),p=!0}}if(p&&d!=null&&d.type==="json"){let f=d.schema;f.type!=="optional"&&(d=Jg.json({...d,schema:Gr.optional({value:f,description:f.type==="reference"?f.description:void 0,nameOverride:void 0,generatedName:"",groupName:void 0,namespace:void 0,availability:void 0,title:void 0,inline:void 0})}))}if(d==null&&!u&&t.default!=null&&(d=Zwl({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,streamResumable:a,source:c,namespace:r.namespace})),d!=null)switch(d.type){case"json":return{value:d,errors:l};case"streamingJson":case"streamingSse":return{value:d,errors:l};case"bytes":case"file":case"text":case"streamingText":return{value:d,errors:l};default:Ye(d)}return{value:void 0,errors:l}}function Zwl({operationContext:e,streamFormat:t,streamTerminator:r,streamResumable:n,response:i,context:o,responseBreadcrumbs:s,source:a,namespace:c,statusCode:l}){let u=Mn(i)?o.resolveResponseReference(i):i;if(u.content!=null&&Object.entries(u.content).find(([m,g])=>{if(g.schema==null)return!1;let A=Mn(g.schema)?o.resolveSchemaReference(g.schema):g.schema;return A.type==="string"&&(A.format==="binary"||A.format==null&&A.contentMediaType==="application/octet-stream")}))return o.options.useBytesForBinaryResponse&&t==null?Jg.bytes({description:u.description,source:a,statusCode:l}):Jg.file({description:u.description,source:a,statusCode:l});let p=wwl(u.content??{},o);if(p!=null&&t!=null)switch(t){case"json":return Jg.streamingJson({statusCode:l,description:u.description,responseProperty:Fr(e.operation,un.RESPONSE_PROPERTY),terminator:r,resumable:void 0,fullExamples:p.examples,schema:Fa(p.schema,!1,!1,o,s,a,c),source:a});case"sse":return Jg.streamingSse({description:u.description,responseProperty:void 0,terminator:r,resumable:n,fullExamples:p.examples,schema:Fa(p.schema,!1,!1,o,s,a,c),source:a,statusCode:l})}let d=JUt({context:o,content:u.content??{}});if(d){if(t!=null)switch(t){case"json":return Jg.streamingJson({description:u.description,responseProperty:void 0,terminator:r,resumable:void 0,fullExamples:d.examples,schema:Fa(d.schema,!1,!1,o,s,a,c),source:a,statusCode:l});case"sse":return Jg.streamingSse({description:u.description,responseProperty:void 0,terminator:r,resumable:n,fullExamples:d.examples,schema:Fa(d.schema,!1,!1,o,s,a,c),source:a,statusCode:l})}return Jg.json({description:u.description,schema:Fa(d.schema,!1,!1,o,s,a,c),responseProperty:Fr(e.operation,un.RESPONSE_PROPERTY),terminator:void 0,resumable:void 0,fullExamples:d.examples,source:a,statusCode:l})}for(let[f,m]of Object.entries(u.content??{})){let g=gp.parse(f);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo()||g.isMultiPartMixed())return Jg.file({description:u.description,source:a,statusCode:l});if(g.isText()&&!f.includes("event-stream")){let A=m.schema,b=g.isPlainText()?void 0:f;if(A==null)return Jg.text({description:u.description,source:a,statusCode:l,contentType:b});let I=Mn(A)?o.resolveSchemaReference(A):A;return I.type==="string"&&I.format==="byte"?Jg.file({description:u.description,source:a,statusCode:l}):Jg.text({description:u.description,source:a,statusCode:l,contentType:b})}}}}function Ilm({responses:e,context:t,source:r,namespace:n}){let i={},o=n!=null?K3e(t.options):void 0;for(let[s,a]of Object.entries(e)){if(s==="default")continue;let c=Xwl(s),l=c!=null,u=c??parseInt(s);if(u<400||u>600)continue;let p=Mn(a)?t.resolveResponseReference(a):a,d=Owl(p.content??{},t),f=l?Ajo[u]:gjo[u];if(f==null){t.logger.warn(`No error name found for status code ${s}`);continue}let m=t.options.namespacedErrors?Fr(p,un.SDK_NAMESPACE):void 0,g=l?s.toUpperCase():u.toString(),A=o!=null&&m==null&&d?.schema!=null&&Mn(d.schema)&&bxe(d.schema)===o;i[g]={statusCode:u,isWildcardStatusCode:l?!0:void 0,nameOverride:void 0,generatedName:f,description:p.description,schema:Fa(d?.schema??{},!1,!1,t,[f,"Body"],r,A?void 0:m??n),fullExamples:d?.examples,namespace:m,isShared:A?!0:void 0,source:r}}return i}var Elm,bjo=h(()=>{"use strict";mt();Ic();yl();sR();Gb();HUt();Lu();yjo();tst();Elm=["200","201","202","204"]});function Jde({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,streamResumable:s,source:a,streamRequestNameOverride:c}){let{document:l,operation:u,path:p,method:d,baseBreadcrumbs:f,pathItem:m}=e,g=Fr(u,un.IDEMPOTENT),A=Fr(u,[un.REQUEST_NAME_V1,un.REQUEST_NAME_V2]),b=[...f,"Request"],I=e5r({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:b,path:p,httpMethod:d,source:a}),C=/{([^}]+)}/g,x=[...p.matchAll(C)].map(le=>le[1]).filter(le=>le!==void 0),S=[...p.matchAll(C)].map(le=>le[1]);switch(t.options.pathParameterOrder){case Qr.PathParameterOrder.SpecOrder:{let le=S.filter(ae=>!I.pathParameters.some(he=>he.name===ae));if(le.length>0)for(let ae of le)I.pathParameters.push({name:ae??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Gr.primitive({schema:Li.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}break;case Qr.PathParameterOrder.UrlOrder:if(x.length>0){let le=new Map(I.pathParameters.map(xe=>[xe.name,xe])),ae=[],he=new Set;for(let xe of x){let Te=le.get(xe);he.add(xe),Te?ae.push(Te):ae.push({name:xe,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Gr.primitive({schema:Li.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}for(let xe of I.pathParameters)he.has(xe.name)||ae.push(xe);I.pathParameters=ae}break;default:Ye(t.options.pathParameterOrder)}let P=(()=>{if(e.method==="GET")return[void 0];if(!u.requestBody)return[void 0];let le=Mn(u.requestBody)?t.resolveRequestBodyReference(u.requestBody):u.requestBody,ae=Object.values(le.content).every(xe=>vlm({mediaTypeObject:xe})!=null),he=[];if(ae)return he.push(...Object.entries(le.content).map(([xe,Te])=>{let pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t.DUMMY,requestBreadcrumbs:b,source:a,namespace:t.namespace,bodyRequired:le.required});return e1l({context:t,convertedParameters:I})&&pe!=null&&(pe.type==="json"||pe.type==="formUrlEncoded")&&pe.schema.type!=="object"&&u.requestBody!=null?pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t,requestBreadcrumbs:[...b,"Body"],source:a,namespace:t.namespace,bodyRequired:le.required}):u.requestBody!=null&&(pe=qte({mediaType:xe,mediaTypeObject:Te,description:le.description,document:l,context:t,requestBreadcrumbs:[...b],source:a,namespace:t.namespace,bodyRequired:le.required})),pe}).filter(xe=>xe!=null)),he.length===0?[void 0]:he;{let xe=r5r({content:le.content,description:le.description,document:l,context:t.DUMMY,requestBreadcrumbs:b,source:a,namespace:t.namespace,bodyRequired:le.required});return e1l({context:t,convertedParameters:I})&&xe!=null&&(xe.type==="json"||xe.type==="formUrlEncoded")&&xe.schema.type!=="object"&&u.requestBody!=null?xe=r5r({content:le.content,description:le.description,document:l,context:t,requestBreadcrumbs:[...b,"Body"],source:a,namespace:t.namespace,bodyRequired:le.required}):u.requestBody!=null&&(xe=r5r({content:le.content,description:le.description,document:l,context:t,requestBreadcrumbs:[...b],source:a,namespace:t.namespace,bodyRequired:le.required})),[xe]}})(),D=P.length>1,R=[...f,"Response"],O=n5r({operationContext:e,streamFormat:i,streamTerminator:o,streamResumable:s,responses:u.responses,context:t,responseBreadcrumbs:R,responseStatusCode:r,source:a}),j=Qwl(u),Y=jwl(u),ee=Fwl(e,u,t),te=Fr(u,un.SERVER_NAME_V2),ce=Fr(u,un.SUBTITLE);return P.map(le=>({summary:u.summary,subtitle:ce??void 0,internal:Fr(u,sB.INTERNAL),idempotent:g,audiences:Fr(u,un.AUDIENCES)??[],operationId:u.operationId!=null&&n!=null?u.operationId+"_"+n:u.operationId,tags:t.options.ignoreTags?[]:t.resolveTagsToTagIds(u.tags),namespace:t.namespace,sdkName:Clm({operationContext:e,request:le}),pathParameters:I.pathParameters,queryParameters:I.queryParameters,headers:I.headers,requestNameOverride:c??A??void 0,generatedRequestName:wlm({baseBreadcrumbs:f,requestBreadcrumbs:b,isMultipleRequests:D,request:le,context:t}),request:le,response:O.value,errors:O.errors,servers:te!=null?[{name:te,url:void 0,audiences:void 0}]:(u.servers??m.servers??[]).map(ae=>$Vr(ae,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:u.description,authed:Slm(u,l),security:xlm(u),availability:Y,method:d,path:p,examples:ee,pagination:e.pagination,source:a,retries:j,globalParameterIds:_wl(u)}))}function $wl({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function vlm({mediaTypeObject:e}){return Fr(e,un.SDK_METHOD_NAME)}function Clm({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function xlm(e){return JVr(e.security)}function Slm(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function e1l({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function wlm({baseBreadcrumbs:e,requestBreadcrumbs:t,isMultipleRequests:r,request:n,context:i}){let o=r?$wl({breadcrumbs:t,request:n}):t,s=JA(o,i.options.preserveSchemaIds);if(!i.options.disambiguateRequestNames)return s;let a=i.document.components?.schemas;if(a==null||!Object.keys(a).some(p=>JA([p],i.options.preserveSchemaIds)===s))return s;let l=[...e,"Body"],u=r?$wl({breadcrumbs:l,request:n}):l;return JA(u,i.options.preserveSchemaIds)}var i5r=h(()=>{"use strict";yo();mt();Ic();yl();Gte();Gb();cjo();M3e();Lu();Nwl();zwl();Mwl();pjo();fjo();djo();hjo();bjo()});function r1l({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,c=r.discriminant.value,l=r["response-status-code"],u=t1l({context:t,headerToIgnore:a,parameters:o}),p=t1l({context:t,headerToIgnore:a,parameters:s}),d=Jde({operationContext:{...e,pathItemParameters:u,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==l))}},context:t,streamFormat:void 0,source:n}),f=Jde({operationContext:{...e,pathItemParameters:u,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:l,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Gr.literal({nameOverride:void 0,generatedName:JA([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:ky.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n,clientDefault:void 0})}),{sync:d,async:f}}function t1l({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=Mn(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var n1l=h(()=>{"use strict";Ic();Gte();Gb();i5r()});function a1l({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:Jde({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,streamResumable:r.resumable,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=i1l({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0}),i=o1l({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let u=t.resolveSchemaReference(n.schemaReference),p=Fr(u,un.TYPE_NAME);if(p!=null)return`${p}Streaming`}})(),s=Jde({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Ejo}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Ejo]},context:t,streamFormat:r.format,streamTerminator:r.terminator,streamResumable:r.resumable,suffix:Ejo,source:t.source,streamRequestNameOverride:o});s.forEach(u=>{u.examples=u.examples.filter(p=>s1l(p,t)!==!1)});let a=i1l({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=o1l({operation:e.operation,response:r.response}),l=Jde({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:c}},context:t,source:t.source});return l.forEach(u=>{u.examples=u.examples.filter(p=>s1l(p,t)!==!0)}),{streaming:s,nonStreaming:l}}default:Ye(r)}}function i1l({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=Mn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=JUt({content:i.content,context:e});if(o==null)return;let s=Mn(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null&&s.oneOf==null&&s.anyOf==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&Mn(a)&&(a=void 0);let c={...s,properties:{...s.properties,[r.streamConditionProperty]:{...a??{},type:"boolean","x-fern-boolean-literal":n}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{required:i.required,content:{[gp.APPLICATION_JSON]:{schema:c}}},schemaReference:Mn(o.schema)?o.schema:void 0}}function o1l({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[gp.APPLICATION_JSON]:{schema:t}}}}}function s1l(e,t){return e._visit({unknown:r=>{let n=Qd.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var Ejo,c1l=h(()=>{"use strict";mt();lo();yl();Gb();Lu();tst();i5r();Ejo="stream"});function Tlm(e){return f1l.includes(e)}function Olm(e){switch(e){case"unix-seconds":return Cm.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Cm.WebhookTimestampFormat.UnixMillis;case"iso8601":return Cm.WebhookTimestampFormat.Iso8601}}function l1l(e){if(e!=null)return{header:e.header,format:e.format!=null?Olm(e.format):void 0,tolerance:e.tolerance}}function u1l(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Cm.WebhookPayloadComponent.Body;case"timestamp":return Cm.WebhookPayloadComponent.Timestamp;case"notification-url":return Cm.WebhookPayloadComponent.NotificationUrl;case"message-id":return Cm.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter,bodySort:Plm(e["body-sort"])}}function Plm(e){if(e!=null&&e==="alphabetical")return Cm.WebhookPayloadBodySort.Alphabetical}function Blm(e,t){if(e!=null){if(!Tlm(e.algorithm)){t.warn(`Ignoring webhook body-hash-binding: unsupported algorithm "${e.algorithm}". Supported algorithms are: ${f1l.join(", ")}.`);return}if(e.location?.type!=="query-parameter"){t.warn(`Ignoring webhook body-hash-binding: unsupported location type "${e.location?.type}". The only supported location is "query-parameter".`);return}return{algorithm:Rlm(e.algorithm),encoding:Ijo(e.encoding),location:klm(e.location)}}}function Dlm(e,t){if(e==null)return;let r=e["port-variants"],n=e["legacy-query-encoding"];if(r!=null&&typeof r!="boolean"){t.warn(`Ignoring webhook url-normalization: "port-variants" must be a boolean, got "${typeof r}".`);return}if(n!=null&&typeof n!="boolean"){t.warn(`Ignoring webhook url-normalization: "legacy-query-encoding" must be a boolean, got "${typeof n}".`);return}if(!r&&!n){t.warn('Ignoring webhook url-normalization: enable at least one of "port-variants" or "legacy-query-encoding".');return}return{portVariants:r??!1,legacyQueryEncoding:n??!1}}function Rlm(e){switch(e){case"sha256":return Cm.WebhookBodyHashAlgorithm.Sha256;case"sha1":return Cm.WebhookBodyHashAlgorithm.Sha1;case"sha384":return Cm.WebhookBodyHashAlgorithm.Sha384;case"sha512":return Cm.WebhookBodyHashAlgorithm.Sha512;default:Ye(e)}}function klm(e){if(e.type==="query-parameter")return Cm.WebhookBodyHashLocation.queryParameter({name:e.name});Ye(e.type)}function Flm(e){if(e!=null)switch(e){case"sha256":return Cm.WebhookSignatureAlgorithm.Sha256;case"sha1":return Cm.WebhookSignatureAlgorithm.Sha1;case"sha384":return Cm.WebhookSignatureAlgorithm.Sha384;case"sha512":return Cm.WebhookSignatureAlgorithm.Sha512}}function Ijo(e){if(e!=null)switch(e){case"base64":return Cm.WebhookSignatureEncoding.Base64;case"hex":return Cm.WebhookSignatureEncoding.Hex}}function Nlm(e){if(e!=null)switch(e){case"rsa-sha256":return Cm.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Cm.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Cm.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Cm.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Cm.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Cm.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Cm.AsymmetricAlgorithm.Ed25519}}function d1l(e,t){if(e.type==="hmac")return Cm.WebhookSignatureVerification.hmac({header:e.header,algorithm:Flm(e.algorithm),encoding:Ijo(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:u1l(e["payload-format"]),timestamp:l1l(e.timestamp),bodyHashBinding:Blm(e["body-hash-binding"],t),notificationUrlNormalization:Dlm(e["url-normalization"],t)});if(e.type==="asymmetric"){let r=Nlm(e["asymmetric-algorithm"]);return r==null?void 0:Cm.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:r,encoding:Ijo(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],payloadFormat:u1l(e["payload-format"]),timestamp:l1l(e.timestamp)})}}function p1l(e,t){let r=Fr(e,un.WEBHOOK_SIGNATURE);if(!(r==null||typeof r=="boolean"))return d1l(r,t)}function m1l(e,t,r){let n=Fr(t,un.WEBHOOK_SIGNATURE);return n!=null?typeof n=="boolean"?p1l(e,r):d1l(n,r):p1l(e,r)}var f1l,h1l=h(()=>{"use strict";mt();Ic();yl();Lu();f1l=["sha256","sha1","sha384","sha512"]});function A1l({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:c}=t,l=[...a,"Payload"],u=[...a,"Response"],p=e5r({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:l,path:o,httpMethod:s,source:r});if(s!=="POST"&&s!=="GET")return e.logger.warn(`Skipping webhook ${s.toUpperCase()} ${o}: Only POST and GET methods are currently supported`),[];let d=i.operationId??zlm({path:o,method:s,sdkMethodName:c}),f=i.responses?n5r({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:u,source:r}):void 0,m=m1l(n,i,e.logger);if(i.requestBody==null){if(p.queryParameters.length===0)return e.logger.error(`Skipping webhook ${s.toUpperCase()} ${o}: Missing a request body and no query parameters`),[];let A=p.queryParameters.map(C=>({key:C.name,schema:C.schema,readonly:void 0,writeonly:void 0,audiences:[],conflict:{},nameOverride:C.parameterNameOverride,generatedName:JA([...l,C.name],e.options.preserveSchemaIds),availability:C.availability,xml:void 0})),b=Gr.object({description:i.description,properties:A,nameOverride:void 0,generatedName:JA(l,e.options.preserveSchemaIds),title:void 0,allOf:[],allOfPropertyConflicts:[],namespace:e.namespace,groupName:void 0,fullExamples:void 0,additionalProperties:!1,availability:void 0,encoding:void 0,source:r,inline:void 0,minProperties:void 0,maxProperties:void 0,examples:void 0});return[{summary:i.summary,audiences:Fr(i,un.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:JA(l,e.options.preserveSchemaIds),payload:b,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let g=Mn(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(g.content).map(([A,b])=>qte({mediaType:A,mediaTypeObject:b,description:g.description,document:n,context:e,requestBreadcrumbs:[...a,"Payload"],source:r,namespace:e.namespace,bodyRequired:g.required})).filter(A=>A!=null).map(A=>{if(A==null||A.type!=="json"&&A.type!=="formUrlEncoded"&&A.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let b,I;return A.type==="multipart"?(b={name:A.name,properties:A.properties,description:A.description,source:A.source},I=Gr.unknown({nameOverride:void 0,generatedName:JA(l,e.options.preserveSchemaIds),title:void 0,description:A.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):I=A.schema,{summary:i.summary,audiences:Fr(i,un.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:JA(l,e.options.preserveSchemaIds),payload:I,signatureVerification:m,multipartFormData:b,response:f?.value,description:i.description,examples:jlm(A.fullExamples),source:r}}).filter(A=>A!=null)}function jlm(e){if(e==null)return[];let t=[];for(let r of e){let n=vxe(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function zlm({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=Qlm(e);if(n===e.toLowerCase())return e;let i=(0,g1l.createHash)("sha256").update(e).digest("hex").slice(0,8);return Mlm(`${n}_${t.toLowerCase()}_${i}`)}function Qlm(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function Mlm(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}var g1l,y1l=h(()=>{"use strict";Ic();g1l=require("crypto");yl();QVr();Gte();Gb();Lu();h1l();djo();hjo();bjo()});function vjo({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=Fr(r,un.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=Llm(r,e),s=xwl(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:_lm({operation:r,sdkMethodName:o,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:s};if(n)return{type:"webhook",value:A1l({context:e,operationContext:a,source:e.source})};let c=Ewl(e.document,r);if(c==null&&Ulm({operation:r,context:e})&&(c={type:"stream",format:"sse",terminator:void 0,resumable:Iwl(r)??ljo(e.document)??!1}),c!=null){let p=a1l({context:e,operationContext:a,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let l=Awl(r);if(l!=null){let p=r1l({context:e,operationContext:a,asyncExtension:l,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:Jde({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function Llm(e,t){let r=Fr(e,un.SDK_METHOD_NAME),n=Fr(e,un.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function _lm({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let o=[];if(e!=null){if(i&&o.push(e.methodName),e.groupName.length>0){let s=e.groupName[e.groupName.length-1];s!=null&&o.push(typeof s=="string"?s:s.name)}i||o.push(e.methodName)}else t.operationId!=null?o.push(t.operationId):o.push(ao(`${r}_${n.split("/").join("_")}`));return o}function Ulm({operation:e,context:t}){if(e.responses==null)return!1;for(let[r,n]of Object.entries(e.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=Mn(n)?t.resolveResponseReference(n):n;if(o.content!=null&&Twl(o.content))return!0}return!1}var b1l=h(()=>{"use strict";xo();yl();Gb();Lu();ywl();vwl();Swl();tst();n1l();i5r();c1l();y1l()});function E1l(e,t,r,n){let i=[],o=v1l(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=Vlm({operation:a.operation}),l=vjo({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:c});l&&i.push(l)}return i}function I1l(e,t,r,n){let i=[],o=v1l(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=vjo({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});c&&i.push(c)}return i}function v1l(e){let t=[];return e.get!=null&&t.push({method:mT.Get,operation:e.get}),e.post!=null&&t.push({method:mT.Post,operation:e.post}),e.put!=null&&t.push({method:mT.Put,operation:e.put}),e.delete!=null&&t.push({method:mT.Delete,operation:e.delete}),e.patch!=null&&t.push({method:mT.Patch,operation:e.patch}),e.head!=null&&t.push({method:mT.Head,operation:e.head}),t}function Vlm({operation:e}){return Fr(e,[un.WEBHOOK])??!1}var C1l=h(()=>{"use strict";Ic();yl();Lu();b1l()});function x1l(e){let t=Fr(e,un.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Fr(e,un.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}var S1l=h(()=>{"use strict";yl();Lu()});function w1l(e){return Fr(e,un.FERN_BASIC_AUTH)}var T1l=h(()=>{"use strict";yl();Lu()});function P1l(e,t,r,n){if(Mn(e)){if(n==null)throw new T({message:`Converting referenced security schemes requires context: ${JSON.stringify(e)}`,code:T.Code.InternalError});let i=n.resolveSecuritySchemeReference(e);return O1l(i,t,r)}return O1l(e,t,r)}function O1l(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=Fr(e,sB.BEARER_FORMAT),i=Fr(e,un.FERN_HEADER_AUTH);return dT.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??Fr(e,un.HEADER_VARIABLE_NAME),headerEnvVar:i?.env,headerPlaceholder:i?.placeholder})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=Fr(e,un.FERN_BEARER_TOKEN);return dT.bearer({tokenVariableName:n?.name??Fr(e,un.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env,tokenPlaceholder:n?.placeholder})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=w1l(e),i=x1l(e);return dT.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,usernamePlaceholder:n?.username?.placeholder,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env,passwordPlaceholder:n?.password?.placeholder})}else{if(e.type==="openIdConnect")return dT.bearer({tokenVariableName:void 0,tokenEnvVar:void 0,tokenPlaceholder:void 0});if(e.type==="oauth2")return dT.oauth({scopesEnum:Glm(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function Glm(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Exe({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([o,s])=>[o,{description:s}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=$f(n);if(i.type==="enum")return i}}var B1l=h(()=>{"use strict";Ic();Bt();yl();PVr();Kot();Gb();M3e();Lu();S1l();T1l()});function D1l({document:e,context:t}){return NUt(e,un.GROUPS,qlm,t.logger)}var qlm,R1l=h(()=>{"use strict";nn();yl();Lu();qlm=Xt.record(Xt.string(),Xt.object({summary:Xt.string().optional(),description:Xt.string().optional()}))});function k1l({context:e,document:t}){return Fr(t,un.FERN_VERSION)??void 0}var F1l=h(()=>{"use strict";yl();Lu()});function N1l(e){let t=Fr(e,un.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({header:n.header,name:n.name,optional:n.optional,env:n.env,clientDefault:n["x-fern-default"],schema:n.type!=null?MUt({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}var j1l=h(()=>{"use strict";yl();Lu();xVr()});function z1l(e){let t=Fr(e,un.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?MUt({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}var Q1l=h(()=>{"use strict";yl();Lu();xVr()});function M1l(e,t){let r=Fr(e,un.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{schema:{nameOverride:void 0,generatedName:JA([n],t),title:i.title,schema:ru.string({default:Jot(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0},envVar:Wlm(n,i)}];throw new T({message:`Variable ${n} has unsupported schema ${JSON.stringify(i)}`,code:T.Code.ValidationError})}))}function Wlm(e,t){let r=Fr(t,un.SDK_VARIABLE_ENV);if(r==null)return;let n=typeof r=="string"?r.trim():void 0;if(n==null||n.length===0)throw new T({message:`Variable ${e} has invalid ${un.SDK_VARIABLE_ENV}: expected a non-empty string but got ${JSON.stringify(r)}`,code:T.Code.ValidationError});return n}var L1l=h(()=>{"use strict";Ic();Bt();yl();YNo();Gte();Lu()});function _1l(e){return Fr(e,Hlm)??{}}var Hlm,U1l=h(()=>{"use strict";yl();Hlm="webhooks"});function V1l(e){let t=Klm(e),r={};return Cjo({obj:t,occurrences:r,breadcrumbs:[]}),r}function Cjo({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)Cjo({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)Cjo({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function Klm(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?YUt(r.get):void 0,put:r?.put!=null?YUt(r.put):void 0,post:r?.post!=null?YUt(r.post):void 0,patch:r?.patch!=null?YUt(r.patch):void 0,delete:r?.delete!=null?YUt(r.delete):void 0}]))}}function YUt(e){return{...e,requestBody:e.requestBody!=null?Mn(e.requestBody)?e.requestBody:Jlm(e.requestBody):void 0}}function Jlm(e){let t,r;for(let n in e.content){let i=gp.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[gp.MULTIPART_FORM_DATA]:r}}:e}var G1l=h(()=>{"use strict";mt();Gb()});var o5r,q1l=h(()=>{"use strict";lo();o5r=class{endpoints;parser=new hde;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let n=[];for(let i of r){let o=this.parser.tryParse(i);if(o==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${o.method} ${o.path}`)}return n}}});var W1l,H1l,K1l,J1l,Y1l,rst,xjo=h(()=>{"use strict";Bt();yl();G1l();Gb();HUt();Lu();q1l();W1l="#/components/parameters/",H1l="#/components/responses/",K1l="#/components/examples/",J1l="#/components/requestBodies/",Y1l="#/components/securitySchemes/",rst=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;schemaNamespaceMapping;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s,refOccurrences:a}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=a??V1l(t),this.options=i,this.source=o,this.filter=new o5r({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=s,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Mn(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(W1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(W1l.length),n=this.document.components.parameters[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(J1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(J1l.length),n=this.document.components.requestBodies[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(H1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(H1l.length),n=this.document.components.responses[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(K1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(K1l.length),n=this.document.components.examples[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(Y1l))throw new T({message:`Failed to resolve ${t.$ref}`,code:T.Code.ReferenceError});let r=t.$ref.substring(Y1l.length),n=this.document.components.securitySchemes[r];if(n==null)throw new T({message:`${t.$ref} is undefined`,code:T.Code.ReferenceError});return Mn(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;let r=this.namespace!=null?K3e(this.options):void 0;for(let[n,i]of Object.entries(this.document.components.schemas))if(!(!i||Mn(i))){if(n===r){t.set(n,void 0);continue}t.set(n,Fr(i,un.SDK_NAMESPACE)||this.namespace)}return t}}});var s5r,X1l=h(()=>{"use strict";xjo();s5r=class extends rst{constructor({document:t,taskContext:r,options:n,source:i,namespace:o,refOccurrences:s}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o,refOccurrences:s})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}}});var nst,Z1l=h(()=>{"use strict";xjo();X1l();nst=class extends rst{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s}){super({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:s})}getDummy(){return new s5r({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace,refOccurrences:this.refOccurrences})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}}});function $1l(e){return Fr(e,un.RESOLUTIONS)}var eTl=h(()=>{"use strict";yl();Lu()});function tTl({openapi:e}){let t=$1l(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let o of n.resolutions)e=Ylm({openapi:e,schemaReference:o,schemaName:n.name}),e=rTl({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function Ylm({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(o=>o.replaceAll("~1","/")),i=e;for(let o of n){let s=i[o];if(s==null)return e;i=s}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function rTl({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,l)=>l.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let l=r.replace(i,c);return rTl({openapi:e,replaceReference:t,schemaReference:l,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),s=e;for(let c of o.slice(0,-1)){let l=s[c];if(l==null)return e;s=l}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}var nTl=h(()=>{"use strict";eTl()});function oTl({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=QUt({document:e,options:r,logger:t.logger}),e=tTl({openapi:e}),NVr();let o=new nst({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([xe,Te])=>{let pe=P1l(Te,n,t,o);return pe==null?null:[xe,pe]}).filter(xe=>xe!==null)),a=JVr(e.security?.filter(xe=>xe!=null)),c=new Set(Object.entries(s).map(([xe,Te])=>Te.type==="basic"||Te.type==="bearer"||Te.type==="oauth"?"Authorization":Te.type==="header"?Te.headerName:null).filter(xe=>xe!=null)),l=M1l(e,r.preserveSchemaIds),u=N1l(e),p=Lwl(e),d=z1l(e),f=r.audiences??[],m=[],g=[],A=new nst({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i}),b=i!=null?K3e(r):void 0,I=b!=null&&e.components?.schemas?.[b]!=null?new nst({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:void 0}):A;A.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied...");let C=$xl(e);if(C?.pathsIncludeBasePath){let xe=jUt({openApi:e,basePath:C.basePath,rootPathParameterNames:new Set(C.pathParameters.map(Te=>Te.name))});for(let Te of xe)t.logger.warn(Te)}let x=r.respectPerSpecBasePath&&C!=null&&C.pathParameters.length===0?C.basePath:void 0;Object.entries(e.paths??{}).forEach(([xe,Te])=>{if(Te==null)return;let pe=E1l(xe,Te,e,A);for(let ue of pe){let Pe=iTl({operation:ue});if(!(f.length>0&&!f.some(Ie=>Pe.includes(Ie))))switch(ue.type){case"async":m.push(...XUt(ue.sync,x)),m.push(...XUt(ue.async,x));break;case"http":m.push(...XUt(ue.value,x));break;case"streaming":m.push(...XUt(ue.streaming,x)),ue.nonStreaming&&m.push(...XUt(ue.nonStreaming,x));break;case"webhook":g.push(...ue.value);break;default:Ye(ue)}}}),Object.entries(_1l(e)).forEach(([xe,Te])=>{if(Te==null)return;t.logger.debug(`Converting path ${xe}`);let pe=I1l(xe,Te,e,A);for(let ue of pe){let Pe=iTl({operation:ue});f.length>0&&!f.some(Ie=>Pe.includes(Ie))||g.push(...ue.value)}});let S=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([xe,Te])=>{if(xe===b)return[xe,Fa(Te,!1,!1,I,[xe],n,void 0)];let pe=Fr(Te,un.SDK_NAMESPACE);if(!Mn(Te)){let ue=Fr(Te,un.IGNORE);if(ue!=null&&ue)return[];if(Ywl.has(xe))return[xe,Fa({...Te,"x-fern-type-name":`${xe}Body`},!1,!1,A,[xe],n,pe??i)]}return[xe,Fa(Te,!1,!1,A,[xe],n,pe??i)]}).filter(xe=>xe.length>0)),P=Xlm(S,A,n),D=eum(P,A),R=new Cxe(D,A.nonRequestReferencedSchemas,A),O=Vte(),j={};for(let[xe,Te]of Object.entries(D)){let pe=r.objectSchemaExamples?sTl($f(Te),Te,R):$f(Te);if(A.isSchemaExcluded(xe))continue;let ue=O.getUniqueSchemaId(xe,A.logger,r.resolveSchemaCollisions);j[ue]=pe}let Y=g.map(xe=>{let pe=xe.examples;if(!r.disableExamples&&pe.length===0){let ue=R.buildExample({schema:xe.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ue!=null&&(pe=[{name:void 0,description:void 0,payload:ue}])}return{...xe,payload:$f(xe.payload),examples:pe}}),ee=new _Vr(D,A,u),te=m.map(xe=>{let Te=xe.examples,pe=Te;if(!r.disableExamples&&(Te.length===0||Te.every(WUt))){let Ie=ee.buildEndpointExample(xe);Ie.length>0&&(pe=[...Ie,...Te.filter(je=>!WUt(je))])}let ue=xe.request,Pe=xe.response;return{...xe,request:ue?.type==="json"||ue?.type==="formUrlEncoded"?{...ue,schema:$f(ue.schema)}:ue,response:Pe?.type==="json"?{...Pe,schema:$f(Pe.schema)}:Pe,queryParameters:xe.queryParameters.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,explode:Ie.explode,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),pathParameters:xe.pathParameters.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,variableReference:Ie.variableReference,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),headers:xe.headers.map(Ie=>({description:Ie.description,name:Ie.name,schema:$f(Ie.schema),parameterNameOverride:Ie.parameterNameOverride,env:Ie.env,availability:Ie.availability,source:Ie.source,clientDefault:Ie.clientDefault})),examples:pe,errors:hp(xe.errors,Ie=>{let je=Ie.fullExamples?.map(_e=>{let at=vxe(_e.value);if(at!=null)return{name:_e.name,description:_e.description,example:at}}).filter(gs);if(je?.length===0){let _e=R.buildExample({schema:Ie.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});_e!=null&&je.push({name:void 0,description:void 0,example:_e})}return{generatedName:Ie.generatedName,nameOverride:Ie.nameOverride,isWildcardStatusCode:Ie.isWildcardStatusCode,schema:$f(Ie.schema),description:Ie.description,source:Ie.source,examples:je,namespace:Ie.namespace,isShared:Ie.isShared}}),retries:xe.retries,globalParameterIds:xe.globalParameterIds}});ee.finalize();let ce=D1l({document:e,context:A}),le=Fr(e,un.BASE_URL_ENV),ae;return le!=null&&(typeof le=="string"&&le.length>0?ae=le:t.logger.warn(`Expected a non-empty string value for ${un.BASE_URL_ENV}; ignoring.`)),{apiVersion:k1l({context:A,document:e}),specVersion:e.info.version!=null&&e.info.version.length>0?e.info.version:void 0,baseUrlEnv:ae,basePath:C!=null&&(!r.respectPerSpecBasePath||C.pathParameters.length>0)?C.basePath:void 0,basePathParameters:C!=null&&C.pathParameters.length>0?C.pathParameters:void 0,title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(ce??{}).map(([xe,Te])=>[xe,{summary:Te.summary??void 0,description:Te.description??void 0}])),servers:(e.servers??[]).map(xe=>$Vr(xe,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(xe=>[xe.name,{id:xe.name,description:xe.description}])),orderedTagIds:e.tags?.map(xe=>xe.name)},endpoints:te,webhooks:Y,channels:{},groupedSchemas:Xot(i,j,b),securitySchemes:s,security:a,hasEndpointsMarkedInternal:te.some(xe=>xe.internal),nonRequestReferencedSchemas:A.getReferencedSchemas(),variables:l,globalHeaders:u,globalParameters:p.length>0?p:void 0,idempotencyHeaders:d}}function Xlm(e,t,r){if(t.options.removeDiscriminantsFromSchemas===Qr.RemoveDiscriminantsFromSchemas.Never)return e;let n=$lm(e,t),i={};for(let[o,s]of Object.entries(e)){if(s.type!=="object"){i[o]=s;continue}let a={$ref:`#/components/schemas/${o}`},c=t.getReferencesFromDiscriminatedUnion(a);if(c==null){i[o]=s;continue}if(t.getReferencedSchemas().has(o)){i[o]=s;continue}let u={...s,type:"object",properties:s.properties.filter(d=>!c.discriminants.has(d.key)),allOfPropertyConflicts:s.allOfPropertyConflicts.filter(d=>!c.discriminants.has(d.propertyKey)),source:r};i[o]=u;let p=Sjo({schema:s,schemas:e});for(let d of[...new Set(p)]){if(n.has(d))continue;let f=i[d]??e[d];f==null||f.type!=="object"||(i[d]={...f,type:"object",properties:f.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:f.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return i}function Zlm(e,t){if(t==null||t==="/")return e;let r=Xh(t);if(e===r||e.startsWith(`${r}/`))return e;let n=e.replace(/^\/+/,"");return n.length>0?`${r}/${n}`:r}function XUt(e,t){return t==null||t==="/"?e:e.map(r=>({...r,path:Zlm(r.path,t)}))}function $lm(e,t){let r=new Set;for(let[n,i]of Object.entries(e)){if(i.type!=="object")continue;let o={$ref:`#/components/schemas/${n}`};if(t.getReferencesFromDiscriminatedUnion(o)==null)for(let s of Sjo({schema:i,schemas:e}))r.add(s)}return r}function eum(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let o={$ref:`#/components/schemas/${n}`},s=t.getDiscriminatedUnionMetadata(o);if(s==null){r[n]=i;continue}let a=[];for(let l of i.properties)if(s.discriminants.has(l.key)){let u=s.discriminants.get(l.key);u!=null&&a.push({...l,schema:Gr.literal({nameOverride:void 0,generatedName:JA([i.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:ky.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(l);let c={...i,type:"object",properties:a};r[n]=c}return r}function Sjo({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...Sjo({schema:i,schemas:t}))}return r}function a5r(e){return[...new Set(e)]}function iTl({operation:e}){let t=[];switch(e.type){case"async":t=a5r(e.async.flatMap(r=>r.audiences));break;case"http":t=a5r(e.value.flatMap(r=>r.audiences));break;case"streaming":t=a5r(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=a5r(e.value.flatMap(r=>r.audiences));break;default:Ye(e)}return t}function sTl(e,t,r){if(e.type==="nullable"&&t.type==="nullable")return{...e,value:sTl(e.value,t.value,r)};if(e.type!=="object"||t.type!=="object")return e;let n={ignoreOptionals:!1,isParameter:!1,maxDepth:3,maxCheckerDepth:5},i=t.fullExamples??[],o=i.length>0?i.map(s=>r.buildExample({schema:t,example:s.value,exampleId:s.name,skipReadonly:!1,options:n})).filter(gs):tum(t,r,n);return o.length>0?{...e,examples:o}:e}function tum(e,t,r){let n=new Set(e.properties.filter(a=>t.hasExample(a.schema,0,new Set,r)).map(a=>a.key));if(n.size===0)return[];let i=a=>a.schema.type!=="optional"&&a.schema.type!=="nullable";if(e.properties.some(a=>i(a)&&!n.has(a.key)))return[];let o=t.buildExample({schema:e,example:void 0,exampleId:void 0,skipReadonly:!1,options:r});if(o==null||o.type!=="object")return o==null?[]:[o];let s=Object.fromEntries(Object.entries(o.properties).filter(([a])=>n.has(a)));return[oc.object({properties:s})]}var aTl=h(()=>{"use strict";yo();mt();Ic();xo();yl();sR();QVr();MVr();Kot();Gte();Gb();HUt();zVr();cjo();LUt();C1l();B1l();fjo();yjo();rjo();Lu();ONo();R1l();F1l();j1l();pjo();Q1l();L1l();DNo();U1l();tjo();Z1l();nTl()});function J3e({context:e,documents:t,options:r}){let n={apiVersion:void 0,specVersion:void 0,baseUrlEnv:void 0,title:void 0,description:void 0,basePath:void 0,basePathParameters:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],globalParameters:void 0,idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let s=o.source!=null?o.source:oR.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=oTl({taskContext:e,openApi:o.value,options:U5({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=lum(n,a,U5({options:o.settings,overrides:r}),e),i++;break}case"asyncapi":{let a=hwl({document:o.value,taskContext:e,options:U5({options:o.settings,overrides:r}),source:s,asyncApiOptions:rum({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(l=>({...l,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),a.channels!=null&&(n.channels={...n.channels,...a.channels}),a.groupedSchemas!=null&&(n.groupedSchemas=c5r(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath);let c=o.value.info?.version?.trim();n.specVersion==null&&c&&(n.specVersion=c),i++;break}default:Ye(o)}}catch(s){e.logger.error(`Failed to parse ${o.type} document ${o.type==="openapi"?o.value.info?.title:o.source?.file}`),s instanceof Error&&e.logger.error(s.message,s.stack?`
|
|
297
297
|
`+s.stack:"")}return n}function rum({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??aSl.naming}}function Ojo(e){return String(e.description||e.name||e["x-fern-server-name"]||"default").trim()}function ZUt(e){return lTl(Ojo(e))}function lTl(e){let t=e.toUpperCase();return t==="PRODUCTION"||t==="PRD"||t==="PROD"?"PRD":t==="SANDBOX"||t==="SBX"?"SBX":t==="STAGING"||t==="STG"?"STG":t==="PERFORMANCE"||t==="PRF"||t==="PERF"?"PRF":t==="E2E"||t==="E_2_E"?"E2E":t==="QAL"||t==="QUALITY"?"QAL":e}function num(e){try{let n=new URL(e).hostname.split("."),i=new Set(["api","www","service","services","example","com","org","net","io"]);for(let s of n){let a=s.split("-")[0],c=a&&a.length>2?a:s;if(c&&!i.has(c.toLowerCase())&&c.length>2)return c.toLowerCase()}let o=n[0];return o&&o.length>0?o.toLowerCase():"api"}catch{let t=e.match(/https?:\/\/([^./-]+)/);return t&&t[1]?t[1].toLowerCase():"api"}}function wjo(e,t){if(!(e==null&&t==null))return[...e??[],...t??[]]}function Tjo(e,t){let r=e??[],n=t??[];if(r.length===0&&n.length===0)return;let i=new Map;for(let o of[...r,...n]){let s=Object.keys(o).sort(),a={};for(let l of s)a[l]=o[l]??[];let c=JSON.stringify(a);i.has(c)||i.set(c,o)}return Array.from(i.values())}function ium(e,t){if(aum(e))return!0;if(e.length===0||t.length===0||e.length!==t.length)return!1;let r=new Map;for(let o of e){if(o.type==="grouped")continue;let s=ZUt(o);r.set(s,o.url)}let n=!0,i=!0;for(let o of t){if(o.type==="grouped")continue;let s=ZUt(o),a=r.get(s);a?a===o.url&&(i=!1):n=!1}return n&&i}function oum(e){let t=new Set;return e.filter(r=>{if(r.type==="grouped")return!0;let n=`${ZUt(r)}\0${r.url}`;return t.has(n)?!1:(t.add(n),!0)})}function sum(e){return e.defaultUrl??e.url}function cTl(e){if(e.length===0||!e[0])return"api";let t=e[0];return t.type==="grouped"?Object.keys(t.urls)[0]??"api":num(sum(t))}function aum(e){return e.some(t=>t.type==="grouped")}function cum(e,t,r,n){return r?.respectPerSpecBasePath===!0&&e.basePath!=null&&t.basePath!=null&&e.basePath!==t.basePath&&n.failWithoutThrowing(`Conflicting parameterized x-fern-base-path values: '${e.basePath}' and '${t.basePath}'.`),{basePath:e.basePath??t.basePath,basePathParameters:e.basePathParameters??t.basePathParameters}}function lum(e,t,r,n){let i=cum(e,t,r,n);if(!(r?.groupMultiApiEnvironments===!0))return{apiVersion:e.apiVersion??t.apiVersion,specVersion:e.specVersion??t.specVersion,baseUrlEnv:e.baseUrlEnv??t.baseUrlEnv,title:e.title??t.title,description:e.description??t.description,basePath:i.basePath,basePathParameters:i.basePathParameters,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:c5r(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Tjo(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,globalParameters:wjo(e.globalParameters,t.globalParameters),idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}};if(ium(e.servers,t.servers)){let a=[],c=[],l=cTl(t.servers),u=new Map,p=new Map,d=cTl(e.servers);for(let g of e.servers)if(g.type==="grouped"){let A=g.name??"default",b=lTl(A);p.has(b)||p.set(b,A),u.has(b)||u.set(b,{});let I=u.get(b);if(I)for(let[C,x]of Object.entries(g.urls))I[C]=x}else{let A=ZUt(g);p.has(A)||p.set(A,Ojo(g)),u.has(A)||u.set(A,{});let b=u.get(A);b&&(b[d]={url:g.url,audiences:g.audiences,defaultUrl:g.defaultUrl,urlTemplate:g.urlTemplate,variables:g.variables})}for(let g of t.servers){let A=ZUt(g);p.has(A)||p.set(A,Ojo(g)),u.has(A)||u.set(A,{});let b=u.get(A);b&&(b[l]={url:g.url,audiences:g.audiences,defaultUrl:g.defaultUrl,urlTemplate:g.urlTemplate,variables:g.variables})}for(let[g,A]of u.entries()){let b=p.get(g)??g,I={type:"grouped",name:b,description:`${b} environment`,urls:A};a.push(I)}let f=e.endpoints.map(g=>{let A=g.__apiName;return A?{...g,type:"multi-api",apiName:A,servers:[{name:A,url:void 0,audiences:void 0}]}:{...g,type:"multi-api",apiName:d,servers:[{name:d,url:void 0,audiences:void 0}]}}),m=t.endpoints.map(g=>({...g,type:"multi-api",apiName:l,servers:[{name:l,url:void 0,audiences:void 0}]}));return c=[...f,...m],{apiVersion:e.apiVersion??t.apiVersion,specVersion:e.specVersion??t.specVersion,baseUrlEnv:e.baseUrlEnv??t.baseUrlEnv,title:e.title??t.title,description:e.description??t.description,basePath:i.basePath,basePathParameters:i.basePathParameters,servers:a,websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:c.map(g=>{if(g.type==="multi-api"){let{type:I,apiName:C,servers:x,...S}=g;return{...S,__apiName:C,servers:x}}let{type:A,...b}=g;return b}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:c5r(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Tjo(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,globalParameters:wjo(e.globalParameters,t.globalParameters),idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}return{apiVersion:e.apiVersion??t.apiVersion,specVersion:e.specVersion??t.specVersion,baseUrlEnv:e.baseUrlEnv??t.baseUrlEnv,title:e.title??t.title,description:e.description??t.description,basePath:i.basePath,basePathParameters:i.basePathParameters,servers:oum([...e.servers,...t.servers]),websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:c5r(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Tjo(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,globalParameters:wjo(e.globalParameters,t.globalParameters),idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function c5r(e,t,r){let n=Vte(),i=r?.resolveSchemaCollisions??!1,o={...e.rootSchemas};for(let[s,a]of Object.entries(t.rootSchemas)){let c=n.getUniqueSchemaId(s,void 0,i);o[c]=a}e.rootSchemas=o;for(let[s,a]of Object.entries(t.namespacedSchemas))if(e.namespacedSchemas[s]!=null){let c=e.namespacedSchemas[s];for(let[l,u]of Object.entries(a)){let p=n.getUniqueSchemaId(l,void 0,i);c[p]=u}}else e.namespacedSchemas[s]=a;return e}var uTl=h(()=>{"use strict";mt();Ic();cSl();gwl();aTl();RNo();LUt()});var W5=h(()=>{"use strict";tEl();nEl();M3e();Lu();ONo();DNo();RNo();uTl();HUt()});function Bjo({document:e,errorResponses:t,schema:r}){if(!bum(r))throw new Error("error-responses.schema must be an OpenAPI schema object or a $ref");let n=Pjo(r);if(n.length>0)throw new Error(`error-responses.schema may only contain local "#/..." references into the OpenAPI document. Found: ${n.join(", ")}`);let i=t["apply-to"]??"all",o=t.ensure??[];for(let c of o)if(!dTl(c["status-code"].toString()))throw new Error(`error-responses.ensure.status-code must be between 400 and 599, got ${c["status-code"]}`);let s=pum({schema:r,name:t.name}),a=new Set;for(let[c,l]of Object.entries(e.paths))if(l!=null)for(let u of pTl){let p=l[u];if(p==null)continue;let d=p.responses??{};p.responses=d;for(let[f,m]of Object.entries(d)){if(!dTl(f))continue;let g=gum({document:e,response:m});if(g!=null&&(i==="all"||!yum(g))){let A=$Ut(m)?EMi(g):g;Aum({response:A,errorSchemaRef:s,responsePath:["paths",c,u,"responses",f],insertedRefPointers:a}),d[f]=A}}for(let f of o){let m=f["status-code"].toString();d[m]!=null||!(f.methods??pTl).includes(u)||(d[m]={description:uum[f["status-code"]]??`Error ${m}`,content:{[l5r]:{schema:s}}},a.add(p5r(["paths",c,u,"responses",m,"content",l5r,"schema"])))}}return $Ut(r)||fum({document:e,schema:r,name:t.name,errorSchemaRef:s,insertedRefPointers:a}),e}function mTl({schema:e,name:t}){return KVr({schema:e,name:t})}function pum({schema:e,name:t}){return $Ut(e)?e:{$ref:`#/components/schemas/${hTl(mTl({schema:e,name:t}))}`}}function fum({document:e,schema:t,name:r,errorSchemaRef:n,insertedRefPointers:i}){let o=mTl({schema:t,name:r}),s=e.components??{};e.components=s;let a=s.schemas??{};s.schemas=a;let c=a[o];if(c!=null&&!qv(c,t)){let l=dum({document:e,schemaName:o,errorSchemaRef:n,insertedRefPointers:i});if(l.length>0)throw new Error(`error-responses: components.schemas already contains a different schema named "${o}" that is still referenced from ${l.join(", ")}. Set error-responses.name to an unused name, or reference the existing schema with \`schema: { $ref: "#/components/schemas/${o}" }\`.`)}a[o]=t}function dum({document:e,schemaName:t,errorSchemaRef:r,insertedRefPointers:n}){let{responses:i,...o}=e.components??{},s=new Set,a=[],c=[],l=({ref:u,path:p})=>{let d=mum(u);if(d!=null&&!s.has(d)&&(s.add(d),a.push(d)),u!==r.$ref)return;let f=p5r(p),[m,g,A]=p;!(m==="components"&&g==="schemas"&&A===t)&&!n.has(f)&&c.push(f)};u5r({...e,components:o},l);for(let u=a.pop();u!=null;u=a.pop())u5r(i?.[u],l,["components","responses",u]);return c}function mum(e){if(!e.startsWith(fTl))return;let[t]=e.slice(fTl.length).split("/");return t==null||t===""?void 0:hum(t)}function u5r(e,t,r=[]){if(Array.isArray(e)){e.forEach((i,o)=>{u5r(i,t,[...r,o.toString()])});return}if(!gr(e))return;typeof e.$ref=="string"&&t({ref:e.$ref,path:r});let n=gr(e.discriminator)?e.discriminator.mapping:void 0;if(gr(n))for(let[i,o]of Object.entries(n))typeof o=="string"&&t({ref:o,path:[...r,"discriminator","mapping",i]});for(let[i,o]of Object.entries(e))i!=="$ref"&&i!=="discriminator"&&u5r(o,t,[...r,i])}function p5r(e){return`#/${e.map(hTl).join("/")}`}function hTl(e){return e.replaceAll("~","~0").replaceAll("/","~1")}function hum(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Pjo(e,t=[]){if(Array.isArray(e))for(let r of e)Pjo(r,t);else if(gr(e))for(let[r,n]of Object.entries(e))r==="$ref"&&typeof n=="string"&&!n.startsWith("#/")?t.push(n):Pjo(n,t);return t}function gum({document:e,response:t}){if(!$Ut(t))return t;let r="#/components/responses/";if(!t.$ref.startsWith(r))return;let n=e.components?.responses?.[t.$ref.slice(r.length)];if(!(n==null||$Ut(n)))return n}function Aum({response:e,errorSchemaRef:t,responsePath:r,insertedRefPointers:n}){let i=e.content??{};e.content=i;let o=Object.keys(i);if(o.length===0){i[l5r]={schema:t},n.add(p5r([...r,"content",l5r,"schema"]));return}for(let s of o){let a=i[s]??{};if(a.schema==null)i[s]={...a,schema:t};else{let{example:c,examples:l,...u}=a;i[s]={...u,schema:t}}n.add(p5r([...r,"content",s,"schema"]))}}function yum(e){return Object.values(e.content??{}).some(t=>t.schema!=null)}function dTl(e){if(/^[45]XX$/i.test(e))return!0;let t=Number(e);return Number.isInteger(t)&&t>=400&&t<=599}function $Ut(e){return"$ref"in e}function bum(e){return e.$ref===void 0||typeof e.$ref=="string"}var l5r,pTl,uum,fTl,gTl=h(()=>{"use strict";mt();W5();xo();l5r="application/json",pTl=["get","post","put","patch","delete","head","options","trace"],uum={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",412:"Precondition Failed",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};fTl="#/components/responses/"});function Ium(e){let{defaults:t,options:r,overrides:n,overrideOnly:i=new Set,undefinedIfAbsent:o=new Set}=e,s={};for(let a of Object.keys(t))i.has(a)?s[a]=n?.[a]!==void 0?n[a]:t[a]:o.has(a)?s[a]=n?.[a]!==void 0?n[a]:r?.[a]!==void 0?r[a]:void 0:s[a]=n?.[a]??r?.[a]??t[a];return s}function Y3e({options:e,overrides:t}){return Ium({defaults:Eum,options:e,overrides:t})}var Eum,Djo=h(()=>{"use strict";yo();Eum={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!0,respectReadonlySchemas:!1,useReadVariantForResponses:!1,respectNullableSchemas:!0,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!0,respectOptionalRequestBody:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!1,coerceOptionalSchemasToNullable:!1,groupEnvironmentsByHost:!1,multiServerStrategy:Qr.MultiServerStrategy.EnvironmentPerServer,removeDiscriminantsFromSchemas:Qr.RemoveDiscriminantsFromSchemas.Always,inferDefaultEnvironment:!0}});function LE(e){switch(e){case ng.Deprecated:return"deprecated";case ng.Beta:return"beta";case ng.GenerallyAvailable:return"generally-available";case ng.Alpha:return"alpha";case ng.Preview:return"preview";case ng.Legacy:return"legacy";default:return}}var X3e=h(()=>{"use strict";Ic()});function eVt(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};case"xml":return{xml:{name:e.name,namespace:e.namespace,prefix:e.prefix}};default:Ye(e)}}function f5r(e){return{xml:{name:e.name,attribute:e.attribute,text:e.text,wrapped:e.wrapped,separator:e.separator}}}var d5r=h(()=>{"use strict";mt()});function ATl(e){let t=e.match(/^(_+)/),r=e.match(/(_+)$/),n=t?.[1]??"",i=r?.[1]??"";if(n===""&&i==="")return ao(e);if(n.length+i.length>=e.length)return e;let o=e.slice(n.length,e.length-i.length||void 0);return`${n}${ao(o)}${i}`}function vum(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function yTl(e){let t=e?vum(e):void 0;if(t==null||t.length===0)return K_e;let r=[];for(let[n,i]of t.entries())typeof i=="string"?r.push(ATl(i)):typeof i=="object"?i.type==="namespace"?n<t.length-1?r.push(ATl(i.name)):r.push(i.name,K_e):Ye(i.type):Ye(i);return r.join("/")}function Yde(e){return _s.of(`${yTl(e)}.yml`)}function Rjo({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?K_e:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,yTl(r))}function bTl({sdkName:e,namespaceOverride:t}){return _s.of(`${Rjo({sdkName:e,namespaceOverride:t})}.yml`)}function ETl({location:e,namespaceOverride:t}){return t!=null?MI(_s.of(t),e):e}var ist=h(()=>{"use strict";yo();mt();vE();xo()});function ITl(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"unknown":return m5r({namespace:e.namespace,groupName:e.groupName});case"oneOf":return m5r({namespace:e.value.namespace,groupName:e.value.groupName});default:Ye(e)}}function m5r({namespace:e,groupName:t}){return e!=null&&t!=null?Yde([{type:"namespace",name:e},...t]):e!=null?Yde([{type:"namespace",name:e}]):Yde(t)}var kjo=h(()=>{"use strict";mt();ist()});function Xde(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":case"unknown":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;default:Ye(e)}}var tVt=h(()=>{"use strict";mt()});function af(e){return typeof e=="string"?e:e.type}function ost(e){if(typeof e!="string")return e.docs}function xxe(e){if(typeof e!="string")return e.default}function Fjo(e){if(typeof e!="string")return e.validation}function sst(e){let t=e.match(/^optional<\s*nullable<\s*(.+)\s*>\s*>$/);if(t!=null&&t[1]!=null)return t[1].trim();let r=e.match(/^nullable<\s*(.+)\s*>$/);return r!=null&&r[1]!=null?r[1].trim():e}var G_=h(()=>{"use strict"});function CTl(e){let t=af(e);return t.startsWith("nullable<")||t.startsWith("optional<nullable<")?e:typeof e=="string"?vTl(e):{...e,type:vTl(e.type)}}function vTl(e){return e.startsWith("nullable<")||e.startsWith("optional<nullable<")?e:e.startsWith("optional<")?e.replace("optional<","optional<nullable<")+">":`nullable<${e}>`}var xTl=h(()=>{"use strict";G_()});function Z3e(e){return af(e).startsWith("optional<")?e:typeof e=="string"?STl(e):{...e,type:STl(e.type)}}function STl(e){return e.startsWith("optional<")?e:`optional<${e}>`}var h5r=h(()=>{"use strict";G_()});function Rc({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i,declarationDepth:o,variant:s}){switch(n.shouldMarkSchemaAsReferenced()&&n.markSchemaAsReferenced(e,i),e.type){case"primitive":return rVt(e);case"array":return zjo({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"map":return Qjo({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"reference":return jjo({schema:e,fileContainingReference:t,context:n,namespace:i,variant:s});case"unknown":return Ljo();case"optional":return g5r({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"nullable":return Mjo({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"enum":return zum({schema:e,fileContainingReference:t,context:n,declarationFile:r,declarationDepth:o});case"literal":return e.value,_jo(e);case"object":return Qum({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"oneOf":return Mum({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});default:Ye(e)}}function rVt(e){switch(e.schema.type){case"string":return Pum({description:e.description,schema:e.schema});case"int":return Bum({description:e.description,schema:e.schema});case"float":return Dum({description:e.description,schema:e.schema});case"double":return Rum({description:e.description,schema:e.schema});case"boolean":return Tum({description:e.description,schema:e.schema});case"int64":return Oum({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",datetimeRfc2822:()=>"datetime-rfc-2822",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{}}}function Tum({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function Oum({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function Pum({description:e,schema:t}){let r="string",n=kum(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function Bum({description:e,schema:t}){let r="integer",n=wTl(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function Dum({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function Rum({description:e,schema:t}){let r="double",n=wTl(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function kum(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,o=Fum(t);if(!(o==null&&r==null&&n==null&&i==null))return{format:o,pattern:r,minLength:n,maxLength:i}}function Fum(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function wTl(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:o,exclusiveMaximum:s}=e;if(r=Njo(r,t),n=Njo(n,t),i=Njo(i,t),!(r==null&&n==null&&o==null&&s==null&&i==null))return{min:r,max:n,exclusiveMin:o,exclusiveMax:s,multipleOf:i}}function Njo(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[Cum,xum]:[Sum,wum];return e<r||e>n?void 0:e}function jjo({schema:e,fileContainingReference:t,context:r,variant:n}){let i=r.getSchema(e.schema,e.namespace);if(i==null)return"unknown";let o=Lum(i)??e.schema,s=r.options.respectReadonlySchemas&&n!=null?r.getSchemaFinalName(o,n):o,a=Xde(i),c=_um(i),u=A5r({context:r,fileContainingReference:t,declarationFile:m5r({namespace:e.namespace,groupName:a}),type:s});i.type==="nullable"&&(u=r.options.wrapReferencesToNullableInOptional?`optional<${u}>`:`nullable<${u}>`),i.type==="optional"&&!u.startsWith("optional<")&&(u=`optional<${u}>`);let p=Num(i,r);return e.description==null&&c==null&&p==null?u:{type:u,...p!=null?{default:p}:{},...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{}}}function Num(e,t){let r=new Set,n=e;for(;n!=null&&!r.has(n);)switch(r.add(n),n.type){case"primitive":{let i=xxe(rVt(n));return jum(n,i)?i:void 0}case"optional":case"nullable":n=n.value;break;case"reference":n=t.getSchema(n.schema,n.namespace);break;case"object":case"array":case"map":case"enum":case"literal":case"oneOf":case"unknown":return;default:Ye(n)}}function jum(e,t){return t==null?!1:e.schema._visit({int:()=>Number.isInteger(t),int64:()=>Number.isInteger(t),uint:()=>Number.isInteger(t),uint64:()=>Number.isInteger(t),float:()=>typeof t=="number",double:()=>typeof t=="number",string:()=>typeof t=="string",datetime:()=>typeof t=="string",datetimeRfc2822:()=>typeof t=="string",date:()=>typeof t=="string",base64:()=>typeof t=="string",boolean:()=>typeof t=="boolean",_other:()=>!1})}function zjo({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=Rc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=`list<${af(a)}>`;return e.description==null&&e.title==null&&e.default==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{},...e.default!=null?{default:e.default}:{},type:c}}function Qjo({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=rVt(e.key),c=Rc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),l=e.encoding!=null?eVt(e.encoding):void 0,u=`map<${af(a)}, ${af(c)}>`;if(e.description==null&&l==null&&e.title==null)return u;let p={type:u};return e.description!=null&&(p.docs=e.description),e.encoding!=null&&(p.encoding=l),e.availability!=null&&(p.availability=LE(e.availability)),p}function Mjo({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){if(!n.options.respectNullableSchemas)return g5r({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});let a=Rc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=af(a),l=ost(a),u=xxe(a),p=Fjo(a),d=CTl(c);if(n.options.wrapReferencesToNullableInOptional&&(d=Z3e(d)),e.availability==null&&e.description==null&&l==null&&u==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||l!=null)&&(f.docs=e.description??l),u!=null&&(f.default=u),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=LE(e.availability)),f}function g5r({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=Rc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=af(a),l=ost(a),u=xxe(a),p=Fjo(a),d=Z3e(c);if(e.availability==null&&e.description==null&&l==null&&u==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||l!=null)&&(f.docs=e.description??l),u!=null&&(f.default=u),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=LE(e.availability)),f}function Ljo(){return"unknown"}function _jo(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ye(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{}}}function zum({schema:e,fileContainingReference:t,declarationFile:r,context:n,declarationDepth:i}){let o=nVt(e,i),s=e.nameOverride??e.generatedName;n.builder.addType(r,{name:s,schema:o.schema});let a=A5r({type:s,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return a;let c={type:a};return e.description!=null&&(c.docs=e.description),e.default!=null&&(c.default=e.default.value),e.availability!=null&&(c.availability=LE(e.availability)),c}function Qum({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=$3e({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let l=A5r({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?l:{type:l,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{}}}function Mum({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=Ujo({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let l=A5r({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?l:{...e.title!=null?{"display-name":e.title}:{},type:l,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:LE(e.availability)}:{}}}function A5r({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function Lum(e){return ba._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function _um(e){return ba._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}var Cum,xum,Sum,wum,Wte=h(()=>{"use strict";mt();Ic();iVt();X3e();d5r();kjo();tVt();G_();xTl();h5r();Cum=-2147483648,xum=2147483647,Sum=-17976931348623157e292,wum=17976931348623157e292});function IT(e){switch(e.type){case"primitive":return OTl(e.value);case"object":return PTl(e.properties);case"array":return BTl(e.value);case"map":return Vum(e.value);case"oneOf":return Gum(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return qum(e.value);case"unknown":return IT(e.value);case"null":return null;default:Ye(e)}}function TTl(e){switch(e.type){case"withStreaming":return e.sse?{stream:Uum(e.events)}:{stream:BTl(e.events)};case"withoutStreaming":return{body:IT(e.value)};default:Ye(e)}}function OTl(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Ye(e)}}function PTl(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,IT(r)]))}function Uum(e){return e.map(t=>({event:"",data:IT(t)}))}function BTl(e){return e.map(t=>IT(t))}function Vum(e){return Object.fromEntries(e.map(t=>[OTl(t.key),IT(t.value)]))}function Gum(e){return e.type==="discriminated"?PTl(e.value):IT(e.value)}function qum(e){switch(e.type){case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"boolean":return e.value;default:Ye(e)}}var oVt=h(()=>{"use strict";mt()});function Zde(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ye(e)}}var y5r=h(()=>{"use strict";mt()});function kTl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s;switch(e.type){case"primitive":s=Kum(e);break;case"array":s=Wum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"map":s=Hum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"reference":s=Jum({schema:e,context:t,declarationFile:r,namespace:n,variant:o});break;case"unknown":s=Xum(e.nameOverride,e.generatedName,e.description);break;case"optional":s=FTl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"nullable":s=Yum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"enum":s=nVt(e,i);break;case"literal":s=Zum(e,e.nameOverride,e.generatedName);break;case"object":s=$3e({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;case"oneOf":s=Ujo({schema:e.value,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;default:Ye(e)}return s}function $3e({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,skipReadonlyProperties:o,variant:s}){let a=o===!0||s==="write",c=e.properties.some(g=>g.readonly),l=new Set;for(let g of e.properties){if(a&&g.readonly)continue;let A=Object.entries(g.conflict);if(!A.every(([b,I])=>!I.differentSchema))for(let[b]of A)for(let I of sVt({property:g.key,schemaId:b,context:t,namespace:n}))l.add(I)}let u={};for(let g of e.properties)a&&g.readonly||Object.keys(g.conflict).length>0&&Object.values(g.conflict).every(b=>!b.differentSchema)||(u[g.key]=RTl({property:g,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:s}));for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(A=>l.add(A));let p=[];for(let g of e.allOf){let A=b5r({schema:g.schema,context:t,namespace:n});if(A==null||l.has(g.schema)||l.has(A))continue;let b=Rc({schema:ba.reference(g),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});p.push(sst(af(b)))}for(let g of l){let A=ast(t,g,n);for(let b of A.properties)u[b.key]==null&&(a&&b.readonly||(u[b.key]=RTl({property:b,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:s})));for(let b of A.allOf){if(l.has(b.schema))continue;let I=Rc({schema:ba.reference(b),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});p.push(sst(af(I)))}}let d={docs:e.description??void 0,...e.examples!=null&&e.examples.length>0&&!a?{examples:e.examples.map(g=>({value:IT(g)}))}:{},properties:Object.fromEntries(Object.entries(u).map(([g,A])=>epm(g)?[g,typeof A=="string"?{type:A,name:`_${g}`}:{...A,name:`_${g}`}]:[g,A]))};p.length>0&&(d.extends=p),e.additionalProperties&&(d["extra-properties"]=!0),e.availability!=null&&(d.availability=LE(e.availability)),e.source!=null&&(d.source=Zde(e.source)),e.encoding!=null&&(d.encoding=eVt(e.encoding)),d.inline=Gjo(e,i);let f=e.nameOverride??e.generatedName;return{name:s==="read"&&c&&t.options.respectReadonlySchemas&&t.hasReadVariant(f)?`${f}Read`:f,schema:d}}function sVt({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];let o=i.type==="nullable"?i.value:i;if(o.type==="reference")return sVt({property:e,schemaId:o.schema,context:r,namespace:n});if(o.type==="object"){let{properties:s,allOf:a}=Vjo(r,o,n),c=s.some(u=>u.key===e),l=[...a.flatMap(u=>sVt({property:e,context:r,schemaId:u.schema,namespace:n}))];if(c||l.length>0)return[t,...l]}return[]}function Vjo(e,t,r){return t.type==="object"?{properties:t.properties,allOf:t.allOf}:t.type==="reference"?ast(e,t.schema,r):t.type==="nullable"?Vjo(e,t.value,r):{properties:[],allOf:[]}}function ast(e,t,r){let n=e.getSchema(t,r);return n==null?{properties:[],allOf:[]}:Vjo(e,n,r)}function Wum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:zjo({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function Hum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Qjo({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function Kum(e){let t=rVt(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function DTl(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function nVt(e,t){let r={enum:e.values.map(o=>{let s=o.nameOverride??o.generatedName,a=o.value;if(s===a&&o.description==null&&(o.casing==null||DTl(o.casing)))return s;let c={value:o.value};if(s!==a&&(c.name=s),o.description!=null&&(c.docs=o.description),o.casing!=null&&!DTl(o.casing)){let l={},u=!1;o.casing.camel!=null&&(l.camel=o.casing.camel,u=!0),o.casing.screamingSnake!=null&&(l["screaming-snake"]=o.casing.screamingSnake,u=!0),o.casing.snake!=null&&(l.snake=o.casing.snake,u=!0),o.casing.pascal!=null&&(l.pascal=o.casing.pascal,u=!0),u&&(c.casing=l)}return c})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=Gjo(e,t);let n=new Set,i={...r,enum:[],source:e.source!=null?Zde(e.source):void 0};for(let o of r.enum){let s=typeof o=="string"?o:o.name??o.value;n.has(s.toLowerCase())||(i.enum.push(o),n.add(s.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:i}}function Jum({schema:e,context:t,declarationFile:r,namespace:n,variant:i}){return{name:e.nameOverride??e.generatedName,schema:jjo({schema:e,context:t,fileContainingReference:r,namespace:n,variant:i})}}function Yum({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return t.options.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:Mjo({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}:FTl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i})}function FTl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:g5r({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}}function Xum(e,t,r){return r!=null?{name:e??t,schema:{type:"unknown",docs:r}}:{name:e??t,schema:Ljo()}}function Zum(e,t,r){return{name:t??r,schema:_jo(e)}}function Ujo({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s=e.encoding!=null?eVt(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let p of e.commonProperties)l[p.key]=Rc({schema:p.schema,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o});let u={};for(let[p,d]of Object.entries(e.schemas))u[p]=Rc({schema:d,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:o});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantPropertyNameOverride!=null||e.discriminatorContext!=null?{...e.discriminantPropertyNameOverride!=null&&{name:e.discriminantPropertyNameOverride},value:e.discriminantProperty,...e.discriminatorContext!=null&&{context:e.discriminatorContext}}:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?LE(e.availability):void 0,union:u,"default-variant":e.defaultDiscriminantValue??void 0,encoding:s,source:e.source!=null?Zde(e.source):void 0}}}let a=[];for(let l of e.schemas)a.push(Rc({schema:l,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o}));let c=e.commonProperties!=null&&e.commonProperties.length>0?Object.fromEntries(e.commonProperties.map(l=>[l.key,Rc({schema:l.schema,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o})])):void 0;return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,"base-properties":c,docs:e.description??void 0,union:a,encoding:s,source:e.source!=null?Zde(e.source):void 0,inline:Gjo(e,i)}}}function epm(e){return $um.test(e)}function b5r({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?b5r({context:t,schema:n.schema,namespace:r}):e}function RTl({property:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s=Rc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:o});return tpm({typeReference:s,audiences:e.audiences,name:e.nameOverride,availability:LE(e.availability),propertyAccess:rpm(e),encoding:e.xml!=null?f5r(e.xml):void 0})}function tpm({typeReference:e,audiences:t,name:r,availability:n,propertyAccess:i,encoding:o}){return t.length===0&&r==null&&n==null&&i==null&&o==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{},...i!=null?{access:i}:{},...o!=null?{encoding:o}:{}}}function Gjo(e,t){return e.inline===!0||t>0?!0:void 0}function rpm(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return Qd.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return Qd.ObjectPropertyAccess.WriteOnly}}var $um,iVt=h(()=>{"use strict";mt();lo();Ic();Wte();X3e();oVt();d5r();y5r();G_();$um=/^[0-9]/});function NTl(e){let t=e.replace(/^x-|^X-/,"");return ao(t)}var jTl=h(()=>{"use strict";xo()});function zTl(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.usernamePlaceholder!=null&&(i.username===void 0?i.username={placeholder:n.usernamePlaceholder}:i.username.placeholder=n.usernamePlaceholder),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),n.passwordPlaceholder!=null&&(i.password===void 0?i.password={placeholder:n.passwordPlaceholder}:i.password.placeholder=n.passwordPlaceholder),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),n.tokenPlaceholder!=null&&(i.token===void 0?i.token={placeholder:n.tokenPlaceholder}:i.token.placeholder=n.tokenPlaceholder),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??NTl(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),n.headerPlaceholder!=null&&(i.placeholder=n.headerPlaceholder),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(_s.of("__package__.yml"),{name:"OauthScope",schema:nVt(n.scopesEnum,0).schema})}}var QTl=h(()=>{"use strict";vE();iVt();jTl()});function Hte({header:e,context:t,fileContainingReference:r,namespace:n}){let i=Rc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),o=af(i),s=xxe(i),a=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:ao(a);if(e.description==null&&e.name===c&&e.env==null&&e.availability==null&&e.clientDefault==null&&s==null)return o;let l={type:o};return c!==e.name&&(l.name=c),e.description!=null&&(l.docs=e.description),e.env!=null&&(l.env=e.env),e.availability!=null&&(l.availability=LE(e.availability)),e.clientDefault!=null&&(l["client-default"]=e.clientDefault),s!=null&&(l.default=s),l}var cst=h(()=>{"use strict";xo();Wte();X3e();G_()});function E5r({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Rc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null&&e.clientDefault==null)return af(i);let o=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:af(i)};return e.description!=null&&(o.docs=e.description),e.availability!=null&&(o.availability=LE(e.availability)),e.clientDefault!=null&&"type"in o&&(o["client-default"]=e.clientDefault),o}var qjo=h(()=>{"use strict";Wte();X3e();G_()});function v5r({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Wjo({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let o=af(i.value),s=Hjo(e.schema,t,n)??xxe(i.value);o==="unknown"?o="string":o==="optional<unknown>"&&(o="optional<string>");let a={type:o};return e.clientDefault!=null&&(a["client-default"]=e.clientDefault),s!=null&&(a.default=s),i.allowMultiple&&(a["allow-multiple"]=!0),e.explode!=null&&(a.explode=e.explode),e.description!=null&&(a.docs=e.description),e.parameterNameOverride!=null&&(a.name=e.parameterNameOverride),e.availability!=null&&(a.availability=LE(e.availability)),npm(i.value)&&i.value.validation!==void 0&&(a.validation=i.value.validation),a.default==null&&a["client-default"]==null&&a["allow-multiple"]==null&&a.docs==null&&a.name==null&&a.availability==null&&a.validation==null&&a.explode==null?o:a}function Wjo({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:Rc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:_s.of(Yf),fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(i.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Got.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:qot(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(i.value.schemas.length===2){let[a,c]=i.value.schemas;if(a!=null&&c!=null&&I5r({array:a,primitive:c}))return{value:Rc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&I5r({array:c,primitive:a}))return{value:Rc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}for(let[a,c]of Object.entries(i.value.schemas))return Wjo({schema:c,context:t,fileContainingReference:r,namespace:n})}else if(t.options.objectQueryParameters)return{value:Rc({schema:e,context:t,fileContainingReference:r,declarationFile:_s.of(Yf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){let i=e.type==="optional"?ba.optional:ba.nullable;if(e.value.type==="reference"){let o=t.getSchema(e.value.schema,n);if(o==null)return;if(o.type==="array")return{value:Rc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:o.value,description:e.description??o.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:_s.of(Yf),namespace:n,declarationDepth:0}),allowMultiple:!0};if(t.options.objectQueryParameters)return{value:Rc({schema:e,context:t,fileContainingReference:r,declarationFile:_s.of(Yf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Rc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Got.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:qot(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,c]=e.value.value.schemas;if(a!=null&&c!=null&&I5r({array:a,primitive:c}))return{value:Rc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&I5r({array:c,primitive:a}))return{value:Rc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}if(t.options.objectQueryParameters)return{value:Rc({schema:e,context:t,fileContainingReference:r,declarationFile:_s.of(Yf),namespace:n,declarationDepth:0}),allowMultiple:!1};for(let[a,c]of Object.entries(e.value.value.schemas))return Wjo({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return t.options.objectQueryParameters?{value:Rc({schema:e,context:t,fileContainingReference:r,declarationFile:_s.of(Yf),namespace:n,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Rc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Rc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}:{value:Rc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}function Hjo(e,t,r){if(e.type==="array")return e.default??void 0;if(e.type==="optional"||e.type==="nullable")return Hjo(e.value,t,r);if(e.type==="reference"){let n=t.getSchema(e.schema,r);if(n!=null)return Hjo(n,t,r)}}function I5r({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function npm(e){return typeof e=="object"&&e!==null&&"type"in e}var Kjo=h(()=>{"use strict";yo();Ic();vE();Wte();X3e();G_()});function MTl({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=ipm(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=opm({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=Sxe(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function ipm(e){let t={};return e.forEach(r=>{let n=Sxe(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function opm({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let o=Sxe(i.value);r.has(i.name)||o!=null&&(n[i.name]=o)}),n}function Sxe(e){switch(e.type){case"primitive":return LTl(e.value);case"object":return _Tl(e.properties);case"array":return spm(e.value);case"map":return apm(e.value);case"oneOf":return cpm(e.value);case"enum":return e.value;case"literal":return lpm(e.value);case"unknown":return Sxe(e.value);case"null":return null;default:Ye(e)}}function LTl(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Ye(e)}}function _Tl(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Sxe(r)]))}function spm(e){return e.map(t=>Sxe(t))}function apm(e){return Object.fromEntries(e.map(t=>[LTl(t.key),Sxe(t.value)]))}function cpm(e){return e.type==="discriminated"?_Tl(e.value):Sxe(e.value)}function lpm(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ye(e)}}var UTl=h(()=>{"use strict";mt()});function aVt(e){try{let r=new URL(e).pathname.split("/").filter(n=>n.length>0);if(r.length>0)return r[r.length-1]}catch{}}function cVt(e){try{return new URL(e).protocol.replace(":","")}catch{return}}function C5r(e,t,r=!1){let n=aVt(t);return r&&n!=null?n:e!=null&&n!=null?`${e}_${n}`:n??e??"websocket"}var Jjo=h(()=>{"use strict"});function $de(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function x5r(e,t){return t??(e?.groupName!=null?$de(e.groupName):void 0)}function VTl({endpointNamespace:e,error:t}){if(!t.isShared)return t.namespace??e}var e4e=h(()=>{"use strict"});function GTl({channel:e,context:t,declarationFile:r}){let n=e.servers[0],i=t.ir.servers.length===0&&t.ir.websocketServers.length<=1,o=n!=null?t.getUrlId(n.url):void 0,s=n!=null&&!i?o??(t.options.groupEnvironmentsByHost?C5r(n.name,n.url,!0):n.name):void 0;t.logger.debug(`[buildChannel] Channel path="${e.path}", server name="${n?.name}", server url="${n?.url}", resolved urlId="${s}" (from collision map: ${t.getUrlId(n?.url??"")!=null})`);let a=e.path;for(let m of e.handshake.pathParameters)m.parameterNameOverride!=null&&(a=a.replace(`{${m.name}}`,`{${m.parameterNameOverride}}`));let c=t.authOverrides?.auth!=null,l={path:a,url:s,auth:c};e.audiences!=null&&e.audiences.length>0&&(l.audiences=e.audiences),e.summary!=null&&(l["display-name"]=e.summary),e.connectMethodName!=null&&(l["connect-method-name"]=e.connectMethodName),e.description!=null&&(l.docs=e.description);let u=$de(e.groupName),p={};if(e.handshake.pathParameters.length>0)for(let m of e.handshake.pathParameters){let g=m.parameterNameOverride??m.name;p[g]=E5r({pathParameter:m,context:t,fileContainingReference:r,namespace:u})}Object.keys(p).length>0&&(l["path-parameters"]=p);let d={};if(e.handshake.queryParameters.length>0)for(let m of e.handshake.queryParameters){let g=v5r({queryParameter:m,context:t,fileContainingReference:r,namespace:u});g!=null&&(d[m.name]=g)}Object.keys(d).length>0&&(l["query-parameters"]=d);let f={};if(e.handshake.headers.length>0)for(let m of e.handshake.headers){let g=Hte({header:m,context:t,fileContainingReference:r,namespace:u});f[m.name]=g}Object.keys(f).length>0&&(l.headers=f),t.builder.addChannel(r,{channel:l});for(let m of e.messages){let g={origin:m.origin,body:Rc({schema:m.body,context:t,fileContainingReference:r,namespace:u,declarationDepth:0})};m.displayName!=null&&(g["display-name"]=m.displayName),m.description!=null&&(g.docs=m.description),m.methodName!=null&&(g["method-name"]=m.methodName),t.builder.addChannelMessage(r,{messageId:m.name,message:g})}for(let m of e.examples){let g=MTl({context:t,websocketExample:m});t.builder.addChannelExample(r,{example:g})}}var qTl=h(()=>{"use strict";cst();qjo();Kjo();Wte();UTl();Jjo();e4e()});function Yjo(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}function WTl(e){try{return new URL(e).hostname}catch{return}}function HTl(e){return e??KTl}function upm(e,t){let r=new Map;for(let n of e){if(Yjo(n)||!("url"in n)||!n.url)continue;let i=WTl(n.url)??n.url;r.has(i)||r.set(i,{environmentName:HTl(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.httpServers.push({name:n.name,url:n.url,audiences:n.audiences})}for(let n of t){let i=WTl(n.url)??n.url;r.has(i)||r.set(i,{environmentName:HTl(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.websocketServers.push(n)}return r}function wxe(e){return Object.entries(e).reduce((t,[r,n])=>(ZD(n)?Object.entries(n.urls).forEach(([i,o])=>{t[i]=o}):t[r]=typeof n=="string"?n:n.url,t),{})}function ppm(e,t,r){for(let[n,i]of Object.entries(t))if(i!=null)if(e[n]!=null&&e[n]!==i){let o=cVt(i),s=o!=null?`${n}_${o}`:`${n}_ws`;e[s]=i,r.setUrlId(i,s)}else e[n]=i,r.setUrlId(i,n)}function JTl(e){let t=e.environmentOverrides?.["base-url-env"]??e.ir.baseUrlEnv;if(t!=null&&e.builder.setBaseUrlEnv(t),e.environmentOverrides!=null){for(let[S,P]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:S,schema:P});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let r={},n=[],i=e.ir.servers.some(S=>Yjo(S)),o=e.ir.servers;for(let S of o)if(Yjo(S)){let P={urls:{}},D={},R={},O={};for(let[Y,ee]of Object.entries(S.urls))P.urls[Y]=ee.defaultUrl??ee.url,ee.urlTemplate&&(D[Y]=ee.urlTemplate),ee.defaultUrl&&(R[Y]=ee.defaultUrl),ee.variables&&ee.variables.length>0&&(O[Y]=ee.variables);(Object.keys(D).length>0||Object.keys(O).length>0)&&(P["url-templates"]=D,P["default-urls"]=R,P.variables=O),S.name&&(r[S.name]=P)}else if("url"in S&&S.url){let D=S.urlTemplate!=null&&S.variables!=null&&S.variables.length>0?{url:S.url,audiences:S.audiences,"default-url":S.defaultUrl,"url-template":S.urlTemplate,variables:S.variables?.map(R=>({id:R.id,default:R.default,values:R.values}))}:S.audiences?{url:S.url,audiences:S.audiences}:S.url;if(S.name==null){n.push(D);continue}r[S.name]=D}let s={},a={},c=[],l={},u={},p={};for(let S of e.ir.endpoints)for(let P of S.servers){if(P.url==null&&P.name!=null){s[P.name]||(s[P.name]=[]);continue}if(P.url==null)continue;let D=P,R="defaultUrl"in P&&typeof D.defaultUrl=="string"?D.defaultUrl:void 0,O="urlTemplate"in P&&typeof D.urlTemplate=="string"?D.urlTemplate:void 0,j="variables"in P&&Array.isArray(D.variables)?D.variables:void 0,Y=R??P.url,ee=P.audiences?{url:Y,audiences:P.audiences}:Y;if(P.name==null){c.push(ee);continue}s[P.name]||(s[P.name]=[]),s[P.name]?.push({url:Y,audiences:P.audiences}),a[P.name]=ee,O&&P.name&&(l[P.name]=O),R&&P.name&&(u[P.name]=R),j&&j.length>0&&P.name&&(p[P.name]=j)}let d={},f=[];for(let S of e.ir.websocketServers){e.logger.debug(`[buildEnvironments] Processing WebSocket server: name="${S.name}", url="${S.url}"`);let P=S.audiences?{url:S.url,audiences:S.audiences}:S.url;if(S.name==null){f.push(P);continue}d[S.name]=P}let m=Object.keys(r).length,g=m>0,A=Object.keys(a).length>0,b=Object.keys(s).some(S=>s[S]?.length===0),I=Object.keys(d).length>0;if(e.options.groupEnvironmentsByHost&&I&&(g||e.ir.servers.length>0)){let S=Object.entries(d).map(([D,R])=>({name:D,url:typeof R=="string"?R:R.url,audiences:typeof R=="string"?void 0:R.audiences})),P=upm(o,S);if(P.size>0){let D=!0;for(let[R,O]of P.entries()){let j={},Y=[...O.httpServers.map(te=>({...te,isHttp:!0})),...O.websocketServers.map(te=>({...te,isHttp:!1}))],ee=new Map;for(let te of Y){let ce=aVt(te.url),le=cVt(te.url);ce&&le&&(ee.has(ce)||ee.set(ce,new Set),ee.get(ce)?.add(le))}if(O.httpServers.length>0){let te=O.httpServers[0];te!=null&&(j[X0]=te.url,e.setUrlId(te.url,X0));for(let ce=1;ce<O.httpServers.length;ce++){let le=O.httpServers[ce];if(le!=null){let ae=aVt(le.url),he=cVt(le.url),xe=ae?ee.get(ae):void 0,Te=xe&&xe.size>1,ue=Te&&he!=="https"?`${ae}_${he}`:ae||`Http${ce+1}`;e.logger.debug(`[buildEnvironments] HTTP server: url="${le.url}", pathSegment="${ae}", protocol="${he}", hasCollision=${Te}, urlId="${ue}"`),j[ue]=le.url,e.setUrlId(le.url,ue)}}}for(let te of O.websocketServers){let ce=aVt(te.url),le=cVt(te.url),ae=ce?ee.get(ce):void 0,he=ae&&ae.size>1,xe=he?`${ce}_${le}`:C5r(te.name,te.url,!0);e.logger.debug(`[buildEnvironments] WebSocket server: name="${te.name}", url="${te.url}", pathSegment="${ce}", protocol="${le}", hasCollision=${he}, urlId="${xe}"`),j[xe]=te.url,e.setUrlId(te.url,xe)}if(Object.keys(j).length>1)e.builder.addEnvironment({name:O.environmentName,schema:{urls:j}});else if(Object.keys(j).length===1){let te=Object.values(j)[0];te!=null&&e.builder.addEnvironment({name:O.environmentName,schema:te})}D&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(O.environmentName),Object.keys(j).length>1&&e.builder.setDefaultUrl(X0),D=!1)}return}}if(!g&&!A&&I&&e.ir.servers.length===0){for(let[S,P]of Object.entries(d))e.builder.addEnvironment({name:S,schema:P});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(Object.keys(d)[0]),e.builder.setDefaultUrl(X0);return}if(c.length>0&&e.logger.debug(`Skipping endpoint level servers ${c.map(S=>typeof S=="string"?S:S.url).join(", ")} because x-fern-server-name was not provided.`),!g){let S=e.ir.servers[0],P=S?.url,D=S?.audiences,R=S?.defaultUrl,O=S?.urlTemplate,j=S?.variables;if(P!=null){let ee=O!=null&&j!=null&&j.length>0?{url:P,audiences:D,"default-url":R,"url-template":O,variables:j?.map(te=>({id:te.id,default:te.default,values:te.values}))}:D?{url:P,audiences:D}:P;r[KTl]=ee}}let C=Object.values(r).map(S=>typeof S=="string"?S:ZD(S)?Object.values(S.urls)[0]:S.url),x=n.filter(S=>{let P=typeof S=="string"?S:S.url;return!C.includes(P)});if(x.length>0&&e.logger.debug(`Skipping top level servers ${x.map(S=>typeof S=="string"?S:S.url).join(", ")} because x-fern-server-name was not provided.`),i){let S=!0;for(let[P,D]of Object.entries(r))if(e.builder.addEnvironment({name:P,schema:D}),S){if(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(P),ZD(D)){let R=Object.keys(D.urls)[0];R&&e.builder.setDefaultUrl(R)}S=!1}return}if(!A&&!b){let S=!0;for(let[P,D]of Object.entries(r))if(S){if(I){let R=typeof D=="string"?D:ZD(D)?Object.values(D.urls)[0]:D["default-url"]??D.url;R!=null&&e.setUrlId(R,X0),e.builder.addEnvironment({name:P,schema:{urls:{[X0]:R??"",...wxe(d)}}})}else e.builder.addEnvironment({name:P,schema:D});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(P),S=!1}else if(I){let R=typeof D=="string"?D:ZD(D)?Object.values(D.urls)[0]:D["default-url"]??D.url;R!=null&&e.setUrlId(R,X0),e.builder.addEnvironment({name:P,schema:{urls:{[X0]:R??"",...wxe(d)}}})}else e.builder.addEnvironment({name:P,schema:D});I&&e.builder.setDefaultUrl(X0)}else if(m===1){let S=Object.keys(r)[0],P=Object.values(r)[0],D=typeof P=="string"?P:ZD(P)?Object.values(P.urls)[0]:P["default-url"]??P.url,R={},O={},j={};typeof P!="string"&&!ZD(P)&&(P["url-template"]&&(R[X0]=P["url-template"]),P["default-url"]&&(O[X0]=P["default-url"]),P.variables&&P.variables.length>0&&(j[X0]=P.variables)),Object.assign(R,l),Object.assign(O,u),Object.assign(j,p);let Y=Object.keys(R).length>0||Object.keys(j).length>0;D!=null&&e.setUrlId(D,X0);let ee={urls:{[X0]:D??"",...wxe(a),...wxe(d)},...Y?{"url-templates":R,"default-urls":O,variables:j}:{}};e.builder.addEnvironment({name:S,schema:ee}),e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(S),e.builder.setDefaultUrl(X0)}else{let S=new Map;for(let O of e.ir.endpoints)for(let j of O.servers)if(j.url!=null&&j.name!=null){S.has(j.name)||S.set(j.name,new Map);let Y=j.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",ee=S.get(j.name);ee&&ee.set(Y,j.url)}let P=new Set(S.keys()),D=new Set(Object.keys(r)),R=P.size>0&&[...P].every(O=>D.has(O));if(e.options.multiServerStrategy==="urls-per-environment"&&S.size>0&&R){let O=Object.entries(r),j=O[0];if(j){let[Y,ee]=j,te=typeof ee=="string"?ee:ZD(ee)?Object.values(ee.urls)[0]:ee["default-url"]??ee.url,ce={};te!=null&&(ce[X0]=te,e.setUrlId(te,X0));for(let le=1;le<O.length;le++){let ae=O[le];if(ae==null)continue;let[he,xe]=ae,Te=typeof xe=="string"?xe:ZD(xe)?Object.values(xe.urls)[0]:xe["default-url"]??xe.url;Te!=null&&(ce[he]=Te,e.setUrlId(Te,he))}I&&ppm(ce,wxe(d),e),e.builder.addEnvironment({name:Y,schema:{urls:ce}}),e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(Y),e.builder.setDefaultUrl(X0)}}else if(S.size>0){let O=!0;for(let[j,Y]of Object.entries(r)){let ee=typeof Y=="string"?Y:ZD(Y)?Object.values(Y.urls)[0]:Y["default-url"]??Y.url;if(!ee)continue;e.setUrlId(ee,X0);let te=ee.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",ce={[X0]:ee};for(let[le,ae]of S.entries()){let he=ae.get(te)||ae.get("production")||ae.values().next().value;he&&(ce[le]=he)}I&&Object.assign(ce,wxe(d)),Object.keys(ce).length>1?e.builder.addEnvironment({name:j,schema:{urls:ce}}):e.builder.addEnvironment({name:j,schema:ee}),O&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(j),O=!1)}S.size>0&&e.builder.setDefaultUrl(X0)}else{let O=!0;for(let[j,Y]of Object.entries(r)){if(I||Object.keys(a).length>0){let ee=typeof Y=="string"?Y:ZD(Y)?Object.values(Y.urls)[0]:Y["default-url"]??Y.url;ee!=null&&e.setUrlId(ee,X0),e.builder.addEnvironment({name:j,schema:{urls:{[X0]:ee??"",...wxe(a),...wxe(d)}}})}else e.builder.addEnvironment({name:j,schema:Y});O&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(j),O=!1)}}}}var X0,KTl,YTl=h(()=>{"use strict";lo();Jjo();X0="Base",KTl="Default"});function XTl(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let o=n.optional===!0?"optional<string>":"string",s=o;if(n.name==null&&n.env==null&&n.clientDefault==null&&typeof n.schema=="string")s=n.schema;else if(n!=null){let a=n.schema?Xde(n.schema):void 0,c=a!=null?$de(a):void 0,l=_s.of("api.yml");s={name:n.name,env:n.env,type:n.schema!=null?af(Rc({schema:n.schema,context:e,fileContainingReference:c?MI(_s.of(ao(c)),l):l,namespace:c,declarationDepth:0}))??o:o},(typeof n.clientDefault=="string"||typeof n.clientDefault=="boolean")&&(s["client-default"]=n.clientDefault)}e.builder.addGlobalHeader({name:r,schema:s})}if(e.options.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let o of i.headers){if(dpm.has(o.name.toLowerCase()))continue;let s=r[o.name];if(s==null){let a=t[o.name],c=Hte({header:{...o,schema:a?.schema??o.schema,name:a?.name??o.name},fileContainingReference:_s.of(nv),context:e,namespace:void 0});s=new Xjo(c),r[o.name]=s}s.increment()}let n=e.ir.endpoints.length*fpm;for(let[i,o]of Object.entries(r)){let s=t[i],a=o.count===e.ir.endpoints.length,c=o.count>=n;s==null&&(a?e.builder.addGlobalHeader({name:i,schema:o.schema}):c&&e.builder.addGlobalHeader({name:i,schema:Z3e(o.schema)}))}}}var Xjo,fpm,dpm,ZTl=h(()=>{"use strict";yo();vE();xo();cst();Wte();tVt();e4e();G_();h5r();Xjo=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},fpm=.75,dpm=new Set(["authorization"])});function $Tl(e){let t=e.ir.globalParameters;if(!(t==null||t.length===0))for(let r of t){let n=mpm(r);e.builder.addGlobalParameter({name:r.name,schema:n})}}function mpm(e){let t={};return e.in!=null&&(t.in=e.in),e.target!=null&&(t.target=e.target),e.type!=null&&(t.type=e.type),e.env!=null&&(t.env=e.env),e.default!=null&&(t.default=e.default),e.optional!=null&&(t.optional=e.optional),e.apply!=null&&(t.apply=e.apply),e.parameterName!=null&&(t["parameter-name"]=e.parameterName),e.docs!=null&&(t.docs=e.docs),t}var eOl=h(()=>{"use strict"});function tOl(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?Xde(t.schema):void 0,n=r!=null?$de(r):void 0,i=Hte({header:{...t,schema:t.schema??ba.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:ru.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0,clientDefault:void 0},fileContainingReference:_s.of(nv),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:Z3e(i)})}}var rOl=h(()=>{"use strict";yo();Ic();vE();cst();tVt();e4e();h5r()});function nOl({endpointExample:e,context:t,pathParameterRenames:r}){let n={};if(e.type!=="full")return e.value;e.name!=null&&(n.name=e.name),e.description!=null&&(n.docs=e.description);let i={};if(t.ir.basePathParameters!=null)for(let l of t.ir.basePathParameters){let u=l.clientDefault??l.name;(typeof u=="string"||typeof u=="number"||typeof u=="boolean")&&(i[l.name]=u)}e.pathParameters!=null&&e.pathParameters.length>0&&Object.assign(i,hpm(e.pathParameters,r)),Object.keys(i).length>0&&(n["path-parameters"]=i),e.queryParameters!=null&&e.queryParameters.length>0&&(n["query-parameters"]=gpm(e.queryParameters));let o=e.headers!=null&&e.headers.length>0,s=t.builder.getGlobalHeaders(),a=Object.keys(s).length>0,c=new Set(e.headers?.map(l=>l.name)??[]);if(o||a){let l=[];if(e.headers!=null)for(let u of e.headers)u.name!==t.builder.getAuthHeaderName()&&l.push(u);for(let[u,p]of Object.entries(s)){if(p!=null&&typeof p=="object"&&p.type!=null){let f=fC({type:p.type,_default:void 0,validation:void 0,visitor:{primitive:xt,map:xt,list:xt,optional:m=>m,nullable:m=>m,set:xt,named:xt,literal:m=>{if(m.type==="string")return m.string;if(m.type==="boolean")return m.boolean.toString()},unknown:xt}});if(f!=null){let m=l.findIndex(A=>A.name===u),g={name:u,value:oc.literal(nxe.string(f))};m>=0?l[m]=g:l.push(g);continue}}if(c.has(u))continue;let d=p!=null&&typeof p=="object"?p.type:typeof p=="string"?p:void 0;l.push({name:u,value:oc.primitive(Apm(iOl(d),u))})}n.headers=ypm({context:t,namedFullExamples:l})}return e.request!=null&&(n.request=IT(e.request)),e.response!=null&&(n.response=TTl(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(n["code-samples"]=e.codeSamples.map(l=>l.type==="language"?{name:l.name??void 0,docs:l.description??void 0,language:l.language,code:l.code,install:l.install??void 0}:{name:l.name??void 0,docs:l.description??void 0,sdk:l.sdk,code:l.code}).filter(gs)),n}function hpm(e,t){let r={};return e.forEach(n=>{let i=IT(n.value);if(i!=null){let o=n.parameterNameOverride??t?.[n.name]??n.name;r[o]=i}}),r}function gpm(e){let t={};return e.forEach(r=>{let n=IT(r.value);n!=null&&(t[r.name]=n)}),t}function iOl(e){if(e==null)return;let t=e.match(/^(?:optional|nullable)<(.+)>$/);return t!=null?iOl(t[1]):e}function Apm(e,t){switch(e){case"integer":case"int":return Po.int(0);case"int64":case"long":return Po.int64(0);case"uint":return Po.uint(0);case"uint64":return Po.uint64(0);case"float":return Po.float(0);case"double":return Po.double(0);case"boolean":return Po.boolean(!0);case"date":return Po.date("2024-01-01");case"date-time":case"datetime":return Po.datetime("2024-01-01T00:00:00Z");case"base64":return Po.base64("SGVsbG8=");default:return Po.string(t)}}function ypm({context:e,namedFullExamples:t}){let r={};return t.forEach(n=>{let i=IT(n.value);i!=null&&(r[n.name]=i)}),r}var oOl=h(()=>{"use strict";mt();lo();Ic();oVt()});var cB,lVt=h(()=>{"use strict";(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(cB||(cB={}))});function sOl(e){return mT._visit(e,{get:()=>Qd.HttpMethodSchema.Get,post:()=>Qd.HttpMethodSchema.Post,put:()=>Qd.HttpMethodSchema.Put,patch:()=>Qd.HttpMethodSchema.Patch,delete:()=>Qd.HttpMethodSchema.Delete,head:()=>Qd.HttpMethodSchema.Head,options:()=>{throw new T({message:"OPTIONS is unsupported",code:T.Code.ConfigError})},trace:()=>{throw new T({message:"TRACE is unsupported",code:T.Code.ConfigError})},_other:()=>{throw new T({message:"Unknown http method is unsupported",code:T.Code.ConfigError})}})}var aOl=h(()=>{"use strict";lo();Ic();Bt()});function Zjo(e){return e==="POST"||e==="PUT"||e==="PATCH"}var cOl=h(()=>{"use strict"});function bpm({endpoint:e,context:t,namespace:r}){let n=new Set;for(let o of e.queryParameters)n.add(o.name);for(let o of e.headers)n.add(o.parameterNameOverride??o.name);let i=e.request;if(i==null)return n;switch(i.type){case"multipart":for(let o of i.properties)n.add(o.key);break;case"json":case"formUrlEncoded":{let o=i.schema.type==="reference"?i.schema.schema:void 0,s=i.schema.type==="reference"?t.getSchema(i.schema.schema,r):i.schema;if(s?.type!=="object"||o!=null&&t.isResponseReachable(o)){n.add("body");break}for(let a of s.properties)n.add(a.nameOverride??a.key);for(let a of s.allOf){let{properties:c}=ast(t,a.schema,r);for(let l of c)n.add(l.nameOverride??l.key)}break}case"octetStream":break;default:Ye(i)}return n}function Epm({pathParameterName:e,reservedNames:t,pathParameters:r}){let n=new Set;for(let s of r){let a=s.parameterNameOverride??s.name;a!==e&&n.add(a)}let i=`${e}${lOl}`,o=2;for(;t.has(i)||n.has(i);)i=`${e}${lOl}${o}`,o++;return i}function pOl({endpoint:e,declarationFile:t,context:r}){let n=[],i=new Set,o=e.path,s=x5r(e.sdkName,e.namespace),a=bpm({endpoint:e,context:r,namespace:s}),c={},l={};for(let b of e.pathParameters){let I=b.parameterNameOverride;I==null&&a.has(b.name)&&(I=Epm({pathParameterName:b.name,reservedNames:a,pathParameters:e.pathParameters}),c[b.name]=I),I&&(o=o.replace(`{${b.name}}`,`{${I}}`)),l[I??b.name]=E5r({pathParameter:b,context:r,fileContainingReference:t,namespace:s})}let u={};for(let b of e.queryParameters){let I=v5r({queryParameter:b,context:r,fileContainingReference:t,namespace:s});I!=null&&(u[b.name]=I,i.add(b.name))}let p;if(e.pagination!=null)switch(e.pagination.type){case"cursor":p={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":p={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":p={type:"custom",results:e.pagination.results};break;case"uri":p={next_uri:e.pagination.nextUri,results:e.pagination.results};break;case"path":p={next_path:e.pagination.nextPath,results:e.pagination.results};break;default:Ye(e.pagination)}let d={path:o,method:sOl(e.method),auth:Ipm({endpoint:e,context:r}),docs:e.description??void 0,pagination:p,source:e.source!=null?Zde(e.source):void 0};!Spm({context:r,request:e.request})&&Object.keys(l).length>0&&(d["path-parameters"]=l),e.summary!=null&&(d["display-name"]=e.summary),e.subtitle!=null&&(d.subtitle=e.subtitle);let f={},m=r.builder.getGlobalHeaderNames(),g=r.builder.getAuthHeaderName();g!=null&&m.add(g);let A=e.headers.filter(b=>!m.has(b.name));for(let b of A){let I=Hte({header:b,context:r,fileContainingReference:t,namespace:s});f[b.name]=I,i.add(typeof I=="string"?b.name:I.name??b.name)}if(e.request!=null){r.setInState(cB.Request);let b=xpm({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.options.inlinePathParameters&&Object.keys(l).length>0?l:void 0,queryParameters:Object.keys(u).length>0?u:void 0,headers:Object.keys(f).length>0?f:void 0,usedNames:i,namespace:s});d.request=b.value,n=[...n,...b.schemaIdsToExclude??[]],r.unsetInState(cB.Request)}else{let b=r.options.inlinePathParameters&&Object.keys(l).length>0,I=Object.keys(u).length>0,C=Object.keys(f).length>0,x={};(b||I||C)&&(x.name=e.requestNameOverride??e.generatedRequestName),b&&(x["path-parameters"]=l),I&&(x["query-parameters"]=u),C&&(x.headers=f),Object.keys(x).length>0&&(d.request=x)}if(e.response!=null&&e.response._visit({json:b=>{let I=Rc({schema:b.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0,variant:r.options.respectReadonlySchemas&&r.options.useReadVariantForResponses?"read":void 0});d.response={docs:b.description??void 0,type:af(I)},b.statusCode!=null&&(d.response["status-code"]=b.statusCode),b.responseProperty!=null&&(d.response.property=b.responseProperty)},streamingJson:b=>{let I=Rc({schema:b.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0,variant:r.options.respectReadonlySchemas&&r.options.useReadVariantForResponses?"read":void 0});d["response-stream"]={docs:b.description??void 0,type:af(I),format:"json",terminator:b.terminator??void 0}},streamingSse:b=>{let I=Rc({schema:b.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0,variant:r.options.respectReadonlySchemas&&r.options.useReadVariantForResponses?"read":void 0});d["response-stream"]={docs:b.description??void 0,type:af(I),format:"sse",terminator:b.terminator??void 0,resumable:b.resumable??void 0}},file:b=>{d.response={docs:b.description??void 0,type:"file","status-code":b.statusCode}},bytes:b=>{d.response={docs:b.description??void 0,type:"bytes","status-code":b.statusCode}},streamingText:b=>{d["response-stream"]={docs:b.description??void 0,type:"text"}},text:b=>{d.response={docs:b.description??void 0,type:"text","status-code":b.statusCode,"content-type":b.contentType??void 0}},_other:()=>{throw new T({message:"Unrecognized Response type: "+e.response?.type,code:T.Code.InternalError})}}),r.builder.getEnvironmentType()==="multi"){let b=r.getDefaultServerName(),I=e.servers[0];if(I==null)b!=null&&(d.url=b);else{let C=I.url!=null?r.getUrlId(I.url):void 0;d.url=C??I.name??void 0}}return e.idempotent&&(d.idempotent=!0),e.availability!=null&&(d.availability=LE(e.availability)),Object.entries(e.errors).forEach(([b,I])=>{let C=I.generatedName,x=_s.of(Yf);r.builder.enableUniqueErrorsPerEndpoint&&(C=`${e.generatedRequestName}${I.generatedName}`,I.schema!=null&&(I.schema.type!=="reference"&&I.schema.type!=="oneOf"?I.schema.generatedName=`${e.generatedRequestName}${I.schema.generatedName}`:I.schema.type==="oneOf"&&(I.schema.value.generatedName=`${e.generatedRequestName}${I.schema.value.generatedName}`)));let S={"status-code":I.isWildcardStatusCode===!0?b:parseInt(b)},P=VTl({endpointNamespace:s,error:I}),D=ETl({location:dOl,namespaceOverride:P});if(I.schema!=null){let j=Rc({schema:I.schema,context:r,fileContainingReference:D,declarationFile:D,namespace:P,declarationDepth:0});S.type=af(j),S.docs=I.description}r.builder.addError(D,{name:C,schema:r.isErrorUnknownSchema({statusCode:b,namespace:I.namespace})?{...S,type:"unknown"}:S}),d.errors==null&&(d.errors=[]);let R=r.builder.addImport({file:t,fileToImport:D});d.errors.push(R!=null?`${R}.${C}`:C),S.type!=null&&I.examples?.forEach(j=>{let Y={value:IT(j.example),name:j.name,docs:j.description};r.builder.addErrorExample(D,{name:C,example:Y})})}),e.examples.length>0&&(d.examples=vpm({endpointExamples:e.examples,context:r,pathParameterRenames:c})),e.retries!=null&&(d.retries=Cpm({retries:e.retries})),e.globalParameterIds!=null&&e.globalParameterIds.length>0&&(d["global-parameters"]=e.globalParameterIds),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?d.audiences=[$jo,...e.audiences]:e.audiences.length>0&&(d.audiences=e.audiences),{value:d,schemaIdsToExclude:n}}function Ipm({endpoint:e,context:t}){return e.security==null?t.authOverrides?.auth!=null?!0:t.ir.security==null?void 0:t.ir.security.length>0?!0:void 0:e.security.length===0?!1:JSON.stringify(e.security)===JSON.stringify(t.ir.security)?!0:e.security}function vpm({endpointExamples:e,context:t,pathParameterRenames:r}){return e.map(n=>{try{return nOl({endpointExample:n,context:t,pathParameterRenames:r})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function Cpm({retries:e}){if(e!=null){if(e.type==="disabled")return{disabled:e.value??void 0};Ye(e)}}function xpm({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:o,pathParameters:s,queryParameters:a,headers:c,usedNames:l,namespace:u}){if(n.type==="json"||n.type==="formUrlEncoded"){let p=n.schema.type==="reference"?n.schema.schema:void 0,d=n.schema.type==="reference"?r.getSchema(n.schema.schema,u):n.schema;if(d?.type!=="object"||p!=null&&r.isResponseReachable(p)){let R=r.options.respectReadonlySchemas&&Zjo(e.method)?"write":void 0,O=Rc({schema:n.schema,fileContainingReference:t,context:r,namespace:u,declarationDepth:0,variant:R}),j={body:O},Y=Object.keys(s??{}).length>0,ee=Object.keys(a??{}).length>0,te=Object.keys(c??{}).length>0;Y&&(j["path-parameters"]=s),ee&&(j["query-parameters"]=a),te&&(j.headers=c),(Y||ee||te)&&(j.name=i??o),n.contentType!=null&&(j["content-type"]=n.contentType),n.description!=null&&(j.docs=n.description);let ce=typeof j.body=="string"&&j["path-parameters"]==null&&j["query-parameters"]==null&&j.headers==null&&j.name==null&&j.docs==null&&(j["content-type"]==null||j["content-type"]==="application/json"),le=uOl(n);return le&&(ce&&delete j["content-type"],j.body=typeof O=="string"?{type:O,optional:!0}:{...O,optional:!0}),{schemaIdsToExclude:[],value:ce&&!le?j.body:j}}let f=new Map;for(let D of d.allOf){let R=r.getSchema(D.schema,u);if(R==null)continue;let O=Xde(R),j=Yde(O),{properties:Y}=ast(r,D.schema,u);for(let ee of Y)f.set(ee.key,j)}let m=new Set,g=new Set;for(let D of d.allOfPropertyConflicts)D.allOfSchemaIds.forEach(R=>m.add(R)),D.conflictingTypeSignatures&&g.add(D.propertyKey);let A=Zjo(e.method)===!0,b=D=>A&&D.readonly===!0;for(let D of d.properties){if(b(D))continue;let R=Object.entries(D.conflict);if(!R.every(([O,j])=>!j.differentSchema))for(let[O]of R)for(let j of sVt({property:D.key,schemaId:O,context:r,namespace:u}))m.add(j)}let I=(D,R)=>{let O=Rc({schema:D.schema,fileContainingReference:t,declarationFile:R,context:r,namespace:u,declarationDepth:1}),j=D.xml!=null?f5r(D.xml):void 0,Y=le=>j==null?le:{...typeof le=="string"?{type:le}:le,encoding:j},ee=D.nameOverride??D.key,te=LE(D.availability);if(!l.has(ee)&&D.audiences.length<=0)return l.add(ee),D.nameOverride!=null?Y({type:af(O),docs:ost(O),name:D.nameOverride,availability:te}):Y(te?{...typeof O=="string"?{type:O}:O,availability:te}:O);let ce={type:af(O),docs:ost(O)};return l.has(ee)&&(ce.name=D.generatedName),D.audiences.length>0&&(ce.audiences=D.audiences),te!=null&&(ce.availability=te),l.add(ee),Y(ce)},C={};for(let D of d.properties)b(D)||(C[D.key]=I(D,f.get(D.key)??t));let x=[];for(let D of d.allOf){let R=b5r({schema:D.schema,context:r,namespace:u});if(R==null||m.has(D.schema)||m.has(R))continue;let O=Rc({schema:ba.reference(D),fileContainingReference:t,context:r,namespace:u,declarationDepth:0}),j=sst(af(O));j!=="unknown"&&x.push(j)}for(let D of m){let R=ast(r,D,u),O=r.getSchema(D,u),j=O!=null?Yde(Xde(O)):t;for(let Y of R.properties)if(C[Y.key]==null&&!b(Y)){if(g.has(Y.key)){C[Y.key]="unknown";continue}C[Y.key]=I(Y,j)}for(let Y of R.allOf){if(m.has(Y.schema))continue;let ee=Rc({schema:ba.reference(Y),fileContainingReference:t,context:r,namespace:u,declarationDepth:0}),te=sst(af(ee));te!=="unknown"&&!x.includes(te)&&x.push(te)}}let S={properties:C};x.length>0&&(S.extends=x),n.additionalProperties&&(S["extra-properties"]=!0),uOl(n)&&(S.optional=!0);let P={name:i??d.nameOverride??d.generatedName,"path-parameters":s,"query-parameters":a,headers:c,body:S};return n.contentType!=null&&(P["content-type"]=n.contentType),n.description!=null&&(P.docs=n.description),{schemaIdsToExclude:p!=null?[p]:[],value:P}}else if(n.type==="octetStream"){let p={body:"bytes","content-type":n.contentType??gp.APPLICATION_OCTET_STREAM,"query-parameters":a};return a!=null&&(p.name=i??o),n.description!=null&&(p.docs=n.description),{schemaIdsToExclude:[],value:p}}else if(n.type==="multipart"){let p=Object.fromEntries(n.properties.map(d=>{if(d.schema.type==="file"){let f=d.schema.isArray?"list<file>":"file";if(f=d.schema.isOptional?`optional<${f}>`:f,d.description!=null||d.contentType!=null){let m={type:f};if(d.description!=null&&(m.docs=d.description),d.contentType!=null){let g=d.contentType.split(",")[0];m["content-type"]=g}return[d.key,m]}return[d.key,f]}else{let f=Rc({schema:d.schema.value,fileContainingReference:t,context:r,namespace:u,declarationDepth:1});if(d.contentType||d.exploded||d.encoding){let m=typeof f=="string"?{type:f}:f;d.contentType!=null&&(m["content-type"]=d.contentType),d.encoding==="form"?m.style="form":d.encoding==="json"?m.style="json":d.exploded&&(m.style="exploded"),f=m}return[d.key,f]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??o,"path-parameters":s,"query-parameters":a,headers:c,body:{properties:p},"content-type":gp.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else Ye(n)}function uOl(e){return e.type==="json"&&e.required!==!0}function Spm({context:e,request:t}){if(!e.options.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Ye(t)}}var lOl,fOl=h(()=>{"use strict";yo();mt();Ic();vE();Bt();oOl();ezo();cst();qjo();Kjo();iVt();Wte();lVt();X3e();oVt();ist();d5r();aOl();y5r();tVt();e4e();G_();cOl();lOl="PathParam"});function wpm({location:e,namespaceOverride:t}){return t!=null?{...e,file:MI(_s.of(t),e.file)}:e}function mOl(e){return e.includes(".")?ao(e):e}function Tpm(e){let t=e.namespace,r=e.tags.filter(c=>c!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:_s.of(`${ao(r)}.yml`),endpointId:e.summary!=null?ao(e.summary):ao(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:_s.of(Yf),endpointId:ao(e.summary)}:{file:_s.of(Yf),endpointId:ao(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:_s.of(Yf),endpointId:mOl(n)};let i=D7(r),o=D7(n);if(qv(i,o))return{file:_s.of("__package__.yml"),endpointId:r};let s=Bpm({operationId:n,tag:r,path:e.path,method:e.method});if(s!=null)return s;let a=[];for(let c=0;c<i.length;++c){let l=i[c];if(l!=null&&l===o[c])a.push(l);else{let u=ao(r);return{file:_s.of(`${u}.yml`),endpointId:mOl(n),tag:r}}}if(a.length>=o.length)throw new T({message:`Cannot get file for endpoint ${JSON.stringify(e)}`,code:T.Code.InternalError});return{file:_s.of(ao(a.join("_"))+".yml"),endpointId:ao(o.slice(a.length).join("_")),tag:r}}function uVt(e){let t=e.tags[0];if(e.sdkName!=null){let r=Rjo({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:_s.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return wpm({namespaceOverride:e.namespace,location:Tpm(e)})}function Bpm({operationId:e,tag:t,path:r,method:n}){let o=`${r.split(Opm).join("_").replaceAll(Ppm,"_")}_${n.toLowerCase()}`;if(e.endsWith(o))return{file:_s.of(ao(t)+".yml"),endpointId:ao(e.slice(0,-1*o.length)),tag:t}}var Opm,Ppm,tzo=h(()=>{"use strict";yo();mt();vE();Bt();xo();ist();Opm=new RegExp("[^a-zA-Z0-9{}]+"),Ppm=new RegExp("[{}]","g")});function hOl(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let o of r){let{endpointId:s,file:a,tag:c}=uVt(o),l=a.split(".")[0];l!=null&&t.add(l);let u;if(o.sdkName!=null){let f=e.ir.groups;for(let m of o.sdkName.groupName){let g=typeof m=="string"?m:m.name,A=f[g];if(A==null)break;if(A.summary!=null||A.description!=null){u=f[g];break}}}let p=c==null?void 0:n.tagsById[c];e.setInState(cB.Endpoint),e.setEndpointMethod(o.method);let d=pOl({context:e,endpoint:o,declarationFile:a});e.unsetEndpointMethod(),e.unsetInState(cB.Endpoint),i=[...i,...d.schemaIdsToExclude],e.builder.addEndpoint(a,{name:s,schema:d.value,source:o.source!=null?Zde(o.source):void 0}),(p?.id!=null||p?.description!=null)&&e.builder.setServiceInfo(a,{"display-name":u?.summary??p?.id,docs:u?.description??p?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}var gOl=h(()=>{"use strict";fOl();lVt();y5r();tzo()});function AOl(e){for(let[t,{schema:r,envVar:n}]of Object.entries(e.ir.variables)){let i=r.groupName!=null?$de(r.groupName):void 0,o=Rc({schema:ba.primitive(r),context:e,fileContainingReference:_s.of(Yf),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:af(o),docs:r.description??void 0,env:n}})}}var yOl=h(()=>{"use strict";yo();Ic();vE();Wte();e4e();G_()});function IOl(e){for(let t of e.ir.webhooks){let r=kpm({webhook:t,context:e});if(r==null)continue;let n=x5r(t.sdkName,t.namespace),i={};for(let s of t.headers)i[s.name]=Hte({header:s,context:e,fileContainingReference:r.file,namespace:n});let o={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:i,payload:Rc({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0}),signature:Fpm(t.signatureVerification),examples:t.examples!=null?t.examples.map(s=>({docs:s.description,name:s.name,payload:IT(s.payload)})):void 0};t.response!=null&&t.response._visit({json:s=>{let a=Rc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o.response={docs:s.description??void 0,type:af(a)},s.statusCode!=null&&(o.response["status-code"]=s.statusCode)},file:s=>{o.response={docs:s.description??void 0,type:"file","status-code":s.statusCode}},bytes:s=>{o.response={docs:s.description??void 0,type:"bytes","status-code":s.statusCode}},text:s=>{o.response={docs:s.description??void 0,type:"text","status-code":s.statusCode,"content-type":s.contentType??void 0}},streamingJson:s=>{let a=Rc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:af(a),format:"json"}},streamingSse:s=>{let a=Rc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:af(a),format:"sse"}},streamingText:s=>{o["response-stream"]={docs:s.description??void 0,type:"text"}},_other:()=>{throw new T({message:"Unrecognized Response type: "+t.response?.type,code:T.Code.InternalError})}}),e.builder.addWebhook(r.file,{name:r.endpointId,schema:o}),t.description!=null&&(o.docs=t.description)}}function Dpm({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:MI(_s.of(t),e.file)}:e}function Rpm({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:_s.of(Yf),endpointId:n};let i=D7(r),o=D7(n);if(qv(i,o))return{file:_s.of("__package__.yml"),endpointId:r};let s=[];for(let a=0;a<i.length;++a){let c=i[a];if(c!=null&&c===o[a])s.push(c);else{let l=ao(r);return{file:_s.of(`${l}.yml`),endpointId:n,tag:r}}}if(s.length>=o.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:_s.of(ao(s.join("_"))+".yml"),endpointId:ao(o.slice(s.length).join("_")),tag:r}}function kpm({webhook:e,context:t}){return e.sdkName!=null?{file:bTl({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:Dpm({namespaceOverride:e.namespace,location:Rpm({webhook:e,context:t})})}function Fpm(e){if(e!=null)switch(e.type){case"hmac":return{type:"hmac",header:e.header,algorithm:Npm(e.algorithm),encoding:rzo(e.encoding),"signature-prefix":e.signaturePrefix,"payload-format":bOl(e.payloadFormat),timestamp:EOl(e.timestamp),"body-hash-binding":zpm(e.bodyHashBinding),"url-normalization":Qpm(e.notificationUrlNormalization)};case"asymmetric":return{type:"asymmetric",header:e.header,"asymmetric-algorithm":jpm(e.asymmetricAlgorithm),encoding:rzo(e.encoding),"signature-prefix":e.signaturePrefix,"jwks-url":e.jwksUrl,"key-id-header":e.keyIdHeader,"payload-format":bOl(e.payloadFormat),timestamp:EOl(e.timestamp)};default:return}}function Npm(e){if(e!=null)switch(e){case"sha256":return"sha256";case"sha1":return"sha1";case"sha384":return"sha384";case"sha512":return"sha512";default:return}}function rzo(e){if(e!=null)switch(e){case"base64":return"base64";case"hex":return"hex";default:return}}function jpm(e){switch(e){case"rsa-sha256":return"rsa-sha256";case"rsa-sha384":return"rsa-sha384";case"rsa-sha512":return"rsa-sha512";case"ecdsa-sha256":return"ecdsa-sha256";case"ecdsa-sha384":return"ecdsa-sha384";case"ecdsa-sha512":return"ecdsa-sha512";case"ed25519":return"ed25519";default:return"rsa-sha256"}}function bOl(e){if(e!=null)return{components:e.components.map(Upm),delimiter:e.delimiter,"body-sort":_pm(e.bodySort)}}function zpm(e){if(e!=null)return{algorithm:Mpm(e.algorithm),encoding:e.encoding!=null?rzo(e.encoding):void 0,location:Lpm(e.location)}}function Qpm(e){if(e!=null)return{"port-variants":e.portVariants,"legacy-query-encoding":e.legacyQueryEncoding}}function Mpm(e){switch(e){case"sha256":return"sha256";case"sha1":return"sha1";case"sha384":return"sha384";case"sha512":return"sha512";default:Ye(e)}}function Lpm(e){if(e.type==="queryParameter")return{type:"query-parameter",name:e.name};Ye(e.type)}function _pm(e){if(e!=null&&e==="alphabetical")return"alphabetical"}function Upm(e){switch(e){case"body":return"body";case"timestamp":return"timestamp";case"notification-url":return"notification-url";case"message-id":return"message-id";default:return"body"}}function Vpm(e){switch(e){case"unix-seconds":return"unix-seconds";case"unix-millis":return"unix-millis";case"iso8601":return"iso8601";default:return}}function EOl(e){if(e!=null)return{header:e.header,format:e.format!=null?Vpm(e.format):void 0,tolerance:e.tolerance}}var vOl=h(()=>{"use strict";yo();mt();vE();Bt();xo();cst();Wte();oVt();ist();e4e();G_()});function Txe(e,t,r){switch(e.type){case"primitive":case"enum":case"literal":case"unknown":return;case"reference":{let n=e.schema;if(r.has(n))return;r.add(n);let i=COl(n,e.namespace,t);i!=null&&Txe(i,t,r);return}case"object":for(let n of e.allOf)if(!r.has(n.schema)){r.add(n.schema);let i=COl(n.schema,n.namespace,t);i!=null&&Txe(i,t,r)}for(let n of e.properties)Txe(n.schema,t,r);return;case"array":case"map":case"optional":case"nullable":Txe(e.value,t,r);return;case"oneOf":Gpm(e.value,t,r);return;default:Ye(e)}}function Gpm(e,t,r){switch(e.type){case"discriminated":for(let n of Object.values(e.schemas))Txe(n,t,r);for(let n of e.commonProperties)Txe(n.schema,t,r);return;case"undiscriminated":for(let n of e.schemas)Txe(n,t,r);return;default:Ye(e)}}function COl(e,t,r){return t==null?r.rootSchemas[e]:r.namespacedSchemas[t]?.[e]}function H5(e,t,r){Txe(e,t,r)}function nzo(e){let t=new Set,r=new Set,{groupedSchemas:n}=e;for(let i of e.endpoints){if(i.request!=null)switch(i.request.type){case"json":case"formUrlEncoded":H5(i.request.schema,n,t);break;case"multipart":for(let o of i.request.properties)o.schema.type==="json"&&H5(o.schema.value,n,t);break;case"octetStream":break;default:Ye(i.request)}if(i.response!=null)switch(i.response.type){case"json":case"streamingJson":case"streamingSse":H5(i.response.schema,n,r);break;case"file":case"text":case"bytes":case"streamingText":break;default:Ye(i.response)}for(let o of Object.values(i.errors))o.schema!=null&&H5(o.schema,n,r);for(let o of i.pathParameters)H5(o.schema,n,r);for(let o of i.queryParameters)H5(o.schema,n,r);for(let o of i.headers)H5(o.schema,n,r)}for(let i of e.webhooks)H5(i.payload,n,r);for(let i of Object.values(e.channels)){for(let o of i.messages)H5(o.body,n,r);for(let o of i.handshake.queryParameters)H5(o.schema,n,r);for(let o of i.handshake.headers)H5(o.schema,n,r);for(let o of i.handshake.pathParameters)H5(o.schema,n,r)}return{requestReachable:t,responseReachable:r}}function qpm(e){return e.type!=="object"?!1:e.properties.some(t=>t.readonly===!0)}function izo(e,t){let r=new Set,n=new Set,i=new Set;function o(s){for(let[a,c]of Object.entries(s)){if(!qpm(c))continue;let l=t.requestReachable.has(a),u=t.responseReachable.has(a);l&&u?r.add(a):l&&!u?n.add(a):!l&&u&&i.add(a)}}o(e.groupedSchemas.rootSchemas);for(let s of Object.values(e.groupedSchemas.namespacedSchemas))o(s);return{needsBothVariants:r,requestOnlyWithReadonly:n,responseOnlyWithReadonly:i}}var xOl=h(()=>{"use strict";mt()});function SOl({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,o]of Object.entries(e)){if(t.has(i))continue;let s=ITl(o);if(n.options.respectReadonlySchemas&&n.needsBothVariants(i)&&o.type==="object"){let l=$3e({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:"read"});n.builder.addType(s,{name:l.name??i,schema:l.schema});let u=$3e({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:u.name??i,schema:u.schema});continue}if(n.options.respectReadonlySchemas&&n.isRequestOnlyWithReadonly(i)&&o.type==="object"){let l=$3e({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:l.name??i,schema:l.schema});continue}let a;n.options.respectReadonlySchemas&&(a=n.isRequestOnly(i)?"write":"read");let c=kTl({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:a});if(gCe(c.schema)){let l=af(c.schema);if(l===(c.name??i)||l===`optional<${c.name??i}>`||l===`nullable<${c.name??i}>`||l===`optional<nullable<${c.name??i}>>`)continue}n.builder.addType(s,{name:c.name??i,schema:c.schema})}}function wOl(e){if(e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),JTl(e),XTl(e),$Tl(e),tOl(e),zTl(e),AOl(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.basePathParameters!=null&&e.ir.basePathParameters.length>0){let i={};for(let o of e.ir.basePathParameters){let s={type:"string"};o.description!=null&&(s.docs=o.description),o.clientDefault!=null&&(s["client-default"]=o.clientDefault),i[o.name]=s}e.builder.setRootPathParameters(i)}if(e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience($jo),e.options.respectReadonlySchemas&&e.options.useReadVariantForResponses){let i=nzo(e.ir),o=izo(e.ir,i);e.setVariantPlan(o,i)}let t=hOl(e),r=t.sdkGroups;if(e.options.respectReadonlySchemas&&!e.options.useReadVariantForResponses){let i=nzo(e.ir),o=izo(e.ir,i);e.setVariantPlan(o,i)}e.setInState(cB.Webhook),IOl(e),e.unsetInState(cB.Webhook),e.setInState(cB.Channel);for(let i of Object.values(e.ir.channels)){let o=Yde(i.groupName);GTl({channel:i,context:e,declarationFile:o})}e.unsetInState(cB.Channel);let n=Wpm({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});SOl({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:n,namespace:void 0,context:e});for(let[i,o]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))SOl({schemas:o,schemaIdsToExclude:n,namespace:i,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(o=>r.has(o))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.optimizeServiceAuth(),e.builder.build()}function Wpm({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return new Set(t);let n=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(o=>Object.keys(o))]),i=new Set(t);for(let o of n)r.includes(o)||i.add(o);return i}var $jo,dOl,ezo=h(()=>{"use strict";yo();lo();vE();QTl();qTl();YTl();ZTl();eOl();rOl();gOl();iVt();yOl();vOl();xOl();lVt();ist();kjo();G_();$jo="external",dOl=_s.of(Yf)});var pVt,TOl=h(()=>{"use strict";pVt=class{context;constructor(t){this.context=t}}});var S5r,OOl=h(()=>{"use strict";vE();Bt();S5r=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[s,a]of Object.entries(n.files)){let c=i!=null?_s.of(`${i}${"/"}${s}`):_s.of(s);t[c]=a}let o=Object.keys(n.directories).sort();for(let s of o){let a=i!=null?`${i}${"/"}${s}`:s,c=n.directories[s];r(c,a)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[_s.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new T({message:`Internal error; cannot add file with path: ${t}`,code:T.Code.InternalError});return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}}});function POl(e){return e?.header!=null}var t4e,BOl=h(()=>{"use strict";yo();lo();vE();xo();OOl();t4e=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;rootPathParameters=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new S5r,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:o}){let s=this.getOrCreateFile(t);s.service==null&&(s.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(s.service.auth=r),n!=null&&(s.service["base-path"]=n),i!=null&&(s.service["display-name"]=i),o!=null&&(s.docs=o)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBaseUrlEnv(t){this.rootApiFile["base-url-env"]=t}setBasePath(t){this.basePath=t}setRootPathParameters(t){Object.keys(t).length!==0&&(this.rootPathParameters=t)}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return cte(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let n of Object.values(this.rootApiFile["auth-schemes"]))POl(n)&&t.push(n.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(POl(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addGlobalParameter({name:t,schema:r}){this.rootApiFile["global-parameters"]==null&&(this.rootApiFile["global-parameters"]={}),this.rootApiFile["global-parameters"][t]=r}addImport({file:t,fileToImport:r,alias:n}){if(t===r)return;let i=n??ao((MU(r)+"/"+nz(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===_s.of(nv))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=yJe(MU(AJe.of(`/${t}`)),AJe.of(`/${r}`)),i;let o=this.getOrCreateFile(t);return o.imports==null&&(o.imports={}),o.imports[i]=yJe(MU(AJe.of(`/${t}`)),AJe.of(`/${r}`)),i}addType(t,{name:r,schema:n}){if(t===_s.of(nv))return;let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let o=i.types[r];o!=null&&(typeof o=="string"?i.types[r]={type:o,examples:[n]}:(o.examples==null&&(o.examples=[]),o.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let o=i.errors[r];if(o==null)return;o.examples==null&&(o.examples=[]),(o.examples.some(a=>qv(a,n))??!1)||o.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let o=this.getOrCreateFile(t);o.service==null&&(o.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(o.service.source=i),o.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=MI(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}optimizeServiceAuth(){let t=[this.packageMarkerFile,...Object.values(this.root.getAllFiles())];for(let r of t){if(r.service==null)continue;let n=Object.values(r.service.endpoints);if(n.length===0)continue;if(n.every(o=>o.auth===!0)){r.service.auth=!0;for(let o of Object.values(r.service.endpoints))delete o.auth}}}build(){let t=this.root.getAllFiles(),r=this.basePath,n=this.rootPathParameters,i=r!=null&&n==null&&!r.includes("{");if(r!=null&&i){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([s,a])=>[s,{...a,path:MI(r,a.path)}]))});for(let s of Object.values(t))s.service!=null&&(s.service={...s.service,endpoints:Object.fromEntries(Object.entries(s.service.endpoints).map(([a,c])=>[a,{...c,path:MI(r,c.path)}]))})}else r!=null&&(this.rootApiFile["base-path"]=r,n!=null&&(this.rootApiFile["path-parameters"]=n));return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===Yf?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}}});var ozo=h(()=>{"use strict";TOl();BOl()});function DOl({statusCode:e,namespace:t}){return t!=null?`${t}:${e}`:`${e}`}var w5r,ROl=h(()=>{"use strict";mt();ozo();Ic();Djo();lVt();w5r=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;options;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;urlIdMap=new Map;endpointMethod;state=new Set;schemaNameMapping=new Map;variantPlan;reachability;constructor({taskContext:t,ir:r,options:n,environmentOverrides:i,globalHeaderOverrides:o,authOverrides:s}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=i,this.authOverrides=s,this.globalHeaderOverrides=o,this.options=Y3e({options:n}),this.enableUniqueErrorsPerEndpoint=this.options.enableUniqueErrorsPerEndpoint,this.referencedSchemaIds=this.options.onlyIncludeReferencedSchemas?new Set:void 0,this.builder=new t4e(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let a={};if(!this.enableUniqueErrorsPerEndpoint)for(let c of r.endpoints)for(let[l,u]of Object.entries(c.errors)){let p=DOl({statusCode:l,namespace:u.namespace}),d=a[p];d==null&&u.schema!=null?a[p]=u.schema:d!=null&&u.schema!=null&&v2(d,u.schema)||this.unknownSchema.add(p)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}setUrlId(t,r){this.urlIdMap.set(t,r)}getUrlId(t){return this.urlIdMap.get(t)}isErrorUnknownSchema({statusCode:t,namespace:r}){return this.unknownSchema.has(DOl({statusCode:t,namespace:r}))}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.options.onlyIncludeReferencedSchemas&&this.isInAnyState(cB.Channel,cB.Endpoint,cB.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ye(t)}}markObjectSchemaAsReferenced(t,r){for(let n of t.allOf)this.markSchemaIdAsReferenced(n.schema,r);for(let n of t.properties)this.markSchemaAsReferenced(n.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let n of Object.values(t.schemas))this.markSchemaAsReferenced(n,r);return;case"undiscriminated":for(let n of t.schemas)this.markSchemaAsReferenced(n,r);return;default:Ye(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let n=this.getSchema(t,r);n!=null&&this.markSchemaAsReferenced(n,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}setSchemaFinalName(t,r){this.schemaNameMapping.set(t,r)}hasReadVariant(t){return this.schemaNameMapping.has(t)}setVariantPlan(t,r){this.variantPlan=t,this.reachability=r;let n=[this.ir.groupedSchemas.rootSchemas,...Object.values(this.ir.groupedSchemas.namespacedSchemas)];for(let i of n)for(let[o,s]of Object.entries(i))if(t.needsBothVariants.has(o)&&s.type==="object"){let a=s.nameOverride??s.generatedName;this.schemaNameMapping.set(a,`${a}Read`)}}needsBothVariants(t){return this.variantPlan?.needsBothVariants.has(t)??!1}isRequestOnlyWithReadonly(t){return this.variantPlan?.requestOnlyWithReadonly.has(t)??!1}isResponseReachable(t){return this.reachability==null?this.ir.nonRequestReferencedSchemas.has(t):this.reachability.responseReachable.has(t)}isRequestOnly(t){return this.reachability==null?!this.ir.nonRequestReferencedSchemas.has(t):this.reachability.requestReachable.has(t)&&!this.reachability.responseReachable.has(t)}getSchemaFinalName(t,r){return!this.options.respectReadonlySchemas||r==="write"?t:this.schemaNameMapping.get(t)??t}}});function szo(e){let t=new w5r(e);return t.options.respectOptionalRequestBody&&t.logger.warn("The `respect-optional-request-body` setting is deprecated and no longer has any effect. A request body that OpenAPI does not mark as required is now always described as omittable in the IR, and each SDK generator opts in to that behaviour through its own configuration."),wOl(t)}var kOl=h(()=>{"use strict";ezo();ROl()});var T5r=h(()=>{"use strict";Djo();kOl();tzo()});var Hpm,FOl,Kpm,Jpm,Ypm,Xpm,qb,Zpm,$pm,fVt,dVt,efm,C2,NOl,jOl,zOl,QOl,MOl,LOl,_Ol,UOl,VOl,GOl,qOl,WOl,HOl,KOl,JOl,YOl,XOl,azo,tfm,rfm,ZOl,UZI,VZI,GZI,qZI,WZI,HZI,KZI,JZI,czo,O5r,YZI,XZI,ZZI,$ZI,Er,Ko=h(()=>{"use strict";Hpm=Object.create,FOl=Object.defineProperty,Kpm=Object.getOwnPropertyDescriptor,Jpm=Object.getOwnPropertyNames,Ypm=Object.getPrototypeOf,Xpm=Object.prototype.hasOwnProperty,qb=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Zpm=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Jpm(t),o=0,s=i.length,a;o<s;o++)a=i[o],!Xpm.call(e,a)&&a!==r&&FOl(e,a,{get:(c=>t[c]).bind(null,a),enumerable:!(n=Kpm(t,a))||n.enumerable});return e},$pm=(e,t,r)=>(r=e!=null?Hpm(Ypm(e)):{},Zpm(t||!e||!e.__esModule?FOl(r,"default",{value:e,enumerable:!0}):r,e)),fVt=qb(((e,t)=>{function r(c){return typeof c>"u"||c===null}function n(c){return typeof c=="object"&&c!==null}function i(c){return Array.isArray(c)?c:r(c)?[]:[c]}function o(c,l){if(l){let u=Object.keys(l);for(let p=0,d=u.length;p<d;p+=1){let f=u[p];c[f]=l[f]}}return c}function s(c,l){let u="";for(let p=0;p<l;p+=1)u+=c;return u}function a(c){return c===0&&Number.NEGATIVE_INFINITY===1/c}t.exports.isNothing=r,t.exports.isObject=n,t.exports.toArray=i,t.exports.repeat=s,t.exports.isNegativeZero=a,t.exports.extend=o})),dVt=qb(((e,t)=>{function r(i,o){let s="",a=i.reason||"(unknown reason)";return i.mark?(i.mark.name&&(s+='in "'+i.mark.name+'" '),s+="("+(i.mark.line+1)+":"+(i.mark.column+1)+")",!o&&i.mark.snippet&&(s+=`
|
|
298
298
|
|
|
299
299
|
`+i.mark.snippet),a+" "+s):a}function n(i,o){Error.call(this),this.name="YAMLException",this.reason=i,this.mark=o,this.message=r(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n.prototype.toString=function(o){return this.name+": "+r(this,o)},t.exports=n})),efm=qb(((e,t)=>{var r=fVt();function n(s,a,c,l,u){let p="",d="",f=Math.floor(u/2)-1;return l-a>f&&(p=" ... ",a=l-f+p.length),c-l>f&&(d=" ...",c=l+f-d.length),{str:p+s.slice(a,c).replace(/\t/g,"\u2192")+d,pos:l-a+p.length}}function i(s,a){return r.repeat(" ",a-s.length)+s}function o(s,a){if(a=Object.create(a||null),!s.buffer)return null;a.maxLength||(a.maxLength=79),typeof a.indent!="number"&&(a.indent=1),typeof a.linesBefore!="number"&&(a.linesBefore=3),typeof a.linesAfter!="number"&&(a.linesAfter=2);let c=/\r?\n|\r|\0/g,l=[0],u=[],p,d=-1;for(;p=c.exec(s.buffer);)u.push(p.index),l.push(p.index+p[0].length),s.position<=p.index&&d<0&&(d=l.length-2);d<0&&(d=l.length-1);let f="",m=Math.min(s.line+a.linesAfter,u.length).toString().length,g=a.maxLength-(a.indent+m+3);for(let b=1;b<=a.linesBefore&&!(d-b<0);b++){let I=n(s.buffer,l[d-b],u[d-b],s.position-(l[d]-l[d-b]),g);f=r.repeat(" ",a.indent)+i((s.line-b+1).toString(),m)+" | "+I.str+`
|
|
@@ -547,7 +547,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
|
|
|
547
547
|
`,s+1),c=a===-1?"":o.slice(a+1);String(n.stack).endsWith(c)||(n.stack+=`
|
|
548
548
|
`+o)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=KK(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&K8t.assertOptions(n,{silentJSONParsing:u8.transitional(u8.boolean),forcedJSONParsing:u8.transitional(u8.boolean),clarifyTimeoutError:u8.transitional(u8.boolean),legacyInterceptorReqResOrdering:u8.transitional(u8.boolean)},!1),i!=null&&(lr.isFunction(i)?r.paramsSerializer={serialize:i}:K8t.assertOptions(i,{encode:u8.function,serialize:u8.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),K8t.assertOptions(r,{baseUrl:u8.spelling("baseURL"),withXsrfToken:u8.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&lr.merge(o.common,o[r.method]);o&&lr.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete o[m]}),r.headers=Kb.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(r)===!1)return;c=c&&g.synchronous;let A=r.transitional||ASe;A&&A.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});let l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let u,p=0,d;if(!c){let m=[uHr.bind(this),void 0];for(m.unshift(...a),m.push(...l),d=m.length,u=Promise.resolve(r);p<d;)u=u.then(m[p++],m[p++]);return u}d=a.length;let f=r;for(;p<d;){let m=a[p++],g=a[p++];try{f=m(f)}catch(A){g.call(this,A);break}}try{u=uHr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=l.length;p<d;)u=u.then(l[p++],l[p++]);return u}getUri(t){t=KK(this.defaults,t);let r=nUe(t.baseURL,t.url,t.allowAbsoluteUrls);return tUe(r,t.params,t.paramsSerializer)}};lr.forEach(["delete","get","head","options"],function(t){gct.prototype[t]=function(r,n){return this.request(KK(n||{},{method:t,url:r,data:(n||{}).data}))}});lr.forEach(["post","put","patch","query"],function(t){function r(n){return function(o,s,a){return this.request(KK(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}gct.prototype[t]=r(),t!=="query"&&(gct.prototype[t+"Form"]=r(!0))});J8t=gct});var u8o,J9l,Y9l=h(()=>{"use strict";rUe();u8o=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 s3(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}}},J9l=u8o});function p8o(e){return function(r){return e.apply(null,r)}}var X9l=h(()=>{"use strict"});function f8o(e){return lr.isObject(e)&&e.isAxiosError===!0}var Z9l=h(()=>{"use strict";My()});var d8o,$9l,eql=h(()=>{"use strict";d8o={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(d8o).forEach(([e,t])=>{d8o[t]=e});$9l=d8o});function tql(e){let t=new J8t(e),r=D8t(J8t.prototype.request,t);return lr.extend(r,J8t.prototype,t,{allOwnKeys:!0}),lr.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return tql(KK(e,i))},r}var qx,Vd,rql=h(()=>{"use strict";My();p5o();K9l();sHr();eHr();S5o();rUe();Y9l();T5o();G8t();j8t();o3();X9l();Z9l();WK();c8o();eql();qx=tql(dct);qx.Axios=J8t;qx.CanceledError=s3;qx.CancelToken=J9l;qx.isCancel=M8t;qx.VERSION=Rme;qx.toFormData=gSe;qx.AxiosError=ai;qx.Cancel=qx.CanceledError;qx.all=function(t){return Promise.all(t)};qx.spread=p8o;qx.isAxiosError=f8o;qx.mergeConfig=KK;qx.AxiosHeaders=Kb;qx.formToJSON=e=>$7r(lr.isHTMLForm(e)?new FormData(e):e);qx.getAdapter=lHr.getAdapter;qx.HttpStatusCode=$9l;qx.default=qx;Vd=qx});var $jv,Act,ezv,tzv,rzv,nzv,izv,ozv,szv,azv,czv,lzv,uzv,pzv,fzv,dzv,mzv,_Q=h(()=>{"use strict";rql();({Axios:$jv,AxiosError:Act,CanceledError:ezv,isCancel:tzv,CancelToken:rzv,VERSION:nzv,all:izv,Cancel:ozv,isAxiosError:szv,spread:azv,toFormData:czv,AxiosHeaders:lzv,HttpStatusCode:uzv,formToJSON:pzv,getAdapter:fzv,mergeConfig:dzv,create:mzv}=Vd)});function w8m(e,t,r){let n=t,i=t?t.next:e.head,o=new gGo(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function T8m(e,t){e.tail=new gGo(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function O8m(e,t){e.head=new gGo(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var Nql,M2,UHr,cGo,jql,uGo,gUe,GHr,Mql,QHr,TSe,aql,Lql,hUe,Hql,bGt,ZK,G8o,Xql,Z8o,yGo,nWl,bGo,Ed,Hx,EGo,vGt,Tct,VQ,fWl,EGt,IGo,UQ,CGo,d5m,m5m,nql,h5m,g5m,A5m,Nme,jme,ySe,fHr,Y8t,dHr,iql,mHr,oql,JK,yct,DT,X8t,vct,RT,Q2,kT,m8o,hHr,gR,IC,h8o,g8o,sql,A8o,gre,y8o,gHr,Z8t,aUe,a3,$8t,y5m,b5m,E5m,I5m,zql,v5m,C5m,x5m,EUe,S5m,PSe,eJ,eGt,ig,b8o,Lme,E8o,L8o,_8o,pGt,AHr,wct,Oct,I8o,Cct,BSe,$K,CSe,Are,xct,v8o,Mme,tGt,C8o,THr,cUe,OHr,AUe,lGo,w5m,VHr,Qql,T5m,O5m,P5m,B5m,D5m,R5m,k5m,pGo,IGt,F5m,Ere,N5m,cql,j5m,x8o,yUe,yHr,S8o,fGo,_ql,z5m,Q5m,Uql,M5m,L5m,Vql,_5m,U5m,V5m,G5m,q5m,W5m,H5m,K5m,Gql,qql,J5m,PHr,Y5m,Wql,qHr,dGo,bUe,X5m,lUe,w8o,Z5m,xSe,$5m,e8m,t8m,SSe,r8m,n8m,i8m,T8o,o8m,uUe,MHr,s8m,a8m,c8m,l8m,lf,u8m,WHr,p8m,U8o,V8o,f8m,p8,pUe,zme,O8o,lql,yre,rGt,bSe,uql,Jb,Qme,ESe,P8o,fUe,Wx,bHr,EHr,B8o,pql,fql,nGt,D8o,IHr,bct,ISe,vHr,dUe,CHr,xHr,dql,d8m,yGt,fGt,m8m,Jql,h8m,g8m,HHr,Yql,A8m,mql,mGo,KHr,hGo,y8m,b8m,hql,E8m,Zql,I8m,gql,Aql,yql,q8o,bql,iGt,BHr,W8o,DHr,H8o,K8o,J8o,Y8o,wSe,LHr,X8o,R8o,bre,$ql,v8m,C8m,x8m,S8m,gGo,Eql,Iql,RHr,oGt,YK,sGt,vSe,mUe,aGt,SHr,XK,k8o,kHr,vql,$8o,eGo,FHr,NHr,Cql,F8o,jHr,eWl,N8o,JHr,AGo,P8m,B8m,tWl,rWl,D8m,R8m,YHr,k8m,iWl,oWl,xql,sWl,aWl,cWl,F8m,N8m,j8m,Sql,lWl,tGo,_Hr,z8m,uWl,Q8m,pWl,dWl,XHr,M8m,L8m,rGo,mWl,_8m,U8m,j8o,wql,Ect,V8m,G8m,q8m,W8m,H8m,K8m,Tql,nGo,Oql,iGo,f8,oGo,sGo,zHr,Pql,Bql,uGt,Dql,Rql,z8o,OSe,FT,wHr,kql,Ict,Q8o,M8o,aGo,dGt,mGt,hGt,gGt,J8m,AGt,Y8m,X8m,Z8m,Fql,vGo,cGt,hWl,$8m,eGm,gWl,tGm,rGm,nGm,iGm,oGm,lGt,gzv,sGm,ZHr=h(()=>{"use strict";Nql=Ae(require("events"),1),M2=Ae(require("fs"),1),UHr=require("events"),cGo=Ae(require("stream"),1),jql=require("string_decoder"),uGo=Ae(require("path"),1),gUe=Ae(require("fs"),1),GHr=require("path"),Mql=require("events"),QHr=Ae(require("assert"),1),TSe=require("buffer"),aql=Ae(require("zlib"),1),Lql=Ae(require("zlib"),1),hUe=require("path"),Hql=require("path"),bGt=Ae(require("fs"),1),ZK=Ae(require("fs"),1),G8o=Ae(require("path"),1),Xql=require("path"),Z8o=Ae(require("path"),1),yGo=Ae(require("fs"),1),nWl=Ae(require("assert"),1),bGo=require("crypto"),Ed=Ae(require("fs"),1),Hx=Ae(require("path"),1),EGo=Ae(require("fs"),1),vGt=Ae(require("fs"),1),Tct=Ae(require("path"),1),VQ=Ae(require("fs"),1),fWl=Ae(require("fs/promises"),1),EGt=Ae(require("path"),1),IGo=require("path"),UQ=Ae(require("fs"),1),CGo=Ae(require("path"),1),d5m=Object.defineProperty,m5m=(e,t)=>{for(var r in t)d5m(e,r,{get:t[r],enumerable:!0})},nql=typeof process=="object"&&process?process:{stdout:null,stderr:null},h5m=e=>!!e&&typeof e=="object"&&(e instanceof EUe||e instanceof cGo.default||g5m(e)||A5m(e)),g5m=e=>!!e&&typeof e=="object"&&e instanceof UHr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==cGo.default.Writable.prototype.pipe,A5m=e=>!!e&&typeof e=="object"&&e instanceof UHr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",Nme=Symbol("EOF"),jme=Symbol("maybeEmitEnd"),ySe=Symbol("emittedEnd"),fHr=Symbol("emittingEnd"),Y8t=Symbol("emittedError"),dHr=Symbol("closed"),iql=Symbol("read"),mHr=Symbol("flush"),oql=Symbol("flushChunk"),JK=Symbol("encoding"),yct=Symbol("decoder"),DT=Symbol("flowing"),X8t=Symbol("paused"),vct=Symbol("resume"),RT=Symbol("buffer"),Q2=Symbol("pipes"),kT=Symbol("bufferLength"),m8o=Symbol("bufferPush"),hHr=Symbol("bufferShift"),gR=Symbol("objectMode"),IC=Symbol("destroyed"),h8o=Symbol("error"),g8o=Symbol("emitData"),sql=Symbol("emitEnd"),A8o=Symbol("emitEnd2"),gre=Symbol("async"),y8o=Symbol("abort"),gHr=Symbol("aborted"),Z8t=Symbol("signal"),aUe=Symbol("dataListeners"),a3=Symbol("discarded"),$8t=e=>Promise.resolve().then(e),y5m=e=>e(),b5m=e=>e==="end"||e==="finish"||e==="prefinish",E5m=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,I5m=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),zql=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[vct](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},v5m=class extends zql{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)}},C5m=e=>!!e.objectMode,x5m=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",EUe=class extends UHr.EventEmitter{[DT]=!1;[X8t]=!1;[Q2]=[];[RT]=[];[gR];[JK];[gre];[yct];[Nme]=!1;[ySe]=!1;[fHr]=!1;[dHr]=!1;[Y8t]=null;[kT]=0;[IC]=!1;[Z8t];[gHr]=!1;[aUe]=0;[a3]=!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");C5m(t)?(this[gR]=!0,this[JK]=null):x5m(t)?(this[JK]=t.encoding,this[gR]=!1):(this[gR]=!1,this[JK]=null),this[gre]=!!t.async,this[yct]=this[JK]?new jql.StringDecoder(this[JK]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[RT]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Q2]});let{signal:r}=t;r&&(this[Z8t]=r,r.aborted?this[y8o]():r.addEventListener("abort",()=>this[y8o]()))}get bufferLength(){return this[kT]}get encoding(){return this[JK]}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[gR]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[gre]}set async(e){this[gre]=this[gre]||!!e}[y8o](){this[gHr]=!0,this.emit("abort",this[Z8t]?.reason),this.destroy(this[Z8t]?.reason)}get aborted(){return this[gHr]}set aborted(e){}write(e,t,r){if(this[gHr])return!1;if(this[Nme])throw new Error("write after end");if(this[IC])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[gre]?$8t:y5m;if(!this[gR]&&!Buffer.isBuffer(e)){if(I5m(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(E5m(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[gR]?(this[DT]&&this[kT]!==0&&this[mHr](!0),this[DT]?this.emit("data",e):this[m8o](e),this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT]):e.length?(typeof e=="string"&&!(t===this[JK]&&!this[yct]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[JK]&&(e=this[yct].write(e)),this[DT]&&this[kT]!==0&&this[mHr](!0),this[DT]?this.emit("data",e):this[m8o](e),this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT]):(this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT])}read(e){if(this[IC])return null;if(this[a3]=!1,this[kT]===0||e===0||e&&e>this[kT])return this[jme](),null;this[gR]&&(e=null),this[RT].length>1&&!this[gR]&&(this[RT]=[this[JK]?this[RT].join(""):Buffer.concat(this[RT],this[kT])]);let t=this[iql](e||null,this[RT][0]);return this[jme](),t}[iql](e,t){if(this[gR])this[hHr]();else{let r=t;e===r.length||e===null?this[hHr]():typeof r=="string"?(this[RT][0]=r.slice(e),t=r.slice(0,e),this[kT]-=e):(this[RT][0]=r.subarray(e),t=r.subarray(0,e),this[kT]-=e)}return this.emit("data",t),!this[RT].length&&!this[Nme]&&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[Nme]=!0,this.writable=!1,(this[DT]||!this[X8t])&&this[jme](),this}[vct](){this[IC]||(!this[aUe]&&!this[Q2].length&&(this[a3]=!0),this[X8t]=!1,this[DT]=!0,this.emit("resume"),this[RT].length?this[mHr]():this[Nme]?this[jme]():this.emit("drain"))}resume(){return this[vct]()}pause(){this[DT]=!1,this[X8t]=!0,this[a3]=!1}get destroyed(){return this[IC]}get flowing(){return this[DT]}get paused(){return this[X8t]}[m8o](e){this[gR]?this[kT]+=1:this[kT]+=e.length,this[RT].push(e)}[hHr](){return this[gR]?this[kT]-=1:this[kT]-=this[RT][0].length,this[RT].shift()}[mHr](e=!1){do;while(this[oql](this[hHr]())&&this[RT].length);!e&&!this[RT].length&&!this[Nme]&&this.emit("drain")}[oql](e){return this.emit("data",e),this[DT]}pipe(e,t){if(this[IC])return e;this[a3]=!1;let r=this[ySe];return t=t||{},e===nql.stdout||e===nql.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[Q2].push(t.proxyErrors?new v5m(this,e,t):new zql(this,e,t)),this[gre]?$8t(()=>this[vct]()):this[vct]()),e}unpipe(e){let t=this[Q2].find(r=>r.dest===e);t&&(this[Q2].length===1?(this[DT]&&this[aUe]===0&&(this[DT]=!1),this[Q2]=[]):this[Q2].splice(this[Q2].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[a3]=!1,this[aUe]++,!this[Q2].length&&!this[DT]&&this[vct]();else if(e==="readable"&&this[kT]!==0)super.emit("readable");else if(b5m(e)&&this[ySe])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Y8t]){let n=t;this[gre]?$8t(()=>n.call(this,this[Y8t])):n.call(this,this[Y8t])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[aUe]=this.listeners("data").length,this[aUe]===0&&!this[a3]&&!this[Q2].length&&(this[DT]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[aUe]=0,!this[a3]&&!this[Q2].length&&(this[DT]=!1)),t}get emittedEnd(){return this[ySe]}[jme](){!this[fHr]&&!this[ySe]&&!this[IC]&&this[RT].length===0&&this[Nme]&&(this[fHr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[dHr]&&this.emit("close"),this[fHr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==IC&&this[IC])return!1;if(e==="data")return!this[gR]&&!r?!1:this[gre]?($8t(()=>this[g8o](r)),!0):this[g8o](r);if(e==="end")return this[sql]();if(e==="close"){if(this[dHr]=!0,!this[ySe]&&!this[IC])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Y8t]=r,super.emit(h8o,r);let i=!this[Z8t]||this.listeners("error").length?super.emit("error",r):!1;return this[jme](),i}else if(e==="resume"){let i=super.emit("resume");return this[jme](),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[jme](),n}[g8o](e){for(let r of this[Q2])r.dest.write(e)===!1&&this.pause();let t=this[a3]?!1:super.emit("data",e);return this[jme](),t}[sql](){return this[ySe]?!1:(this[ySe]=!0,this.readable=!1,this[gre]?($8t(()=>this[A8o]()),!0):this[A8o]())}[A8o](){if(this[yct]){let t=this[yct].end();if(t){for(let r of this[Q2])r.dest.write(t);this[a3]||super.emit("data",t)}}for(let t of this[Q2])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[gR]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[gR]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[gR])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[JK]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(IC,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[a3]=!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[Nme])return t();let n,i,o=l=>{this.off("data",s),this.off("end",a),this.off(IC,c),t(),i(l)},s=l=>{this.off("error",o),this.off("end",a),this.off(IC,c),this.pause(),n({value:l,done:!!this[Nme]})},a=()=>{this.off("error",o),this.off("data",s),this.off(IC,c),t(),n({done:!0,value:void 0})},c=()=>o(new Error("stream destroyed"));return new Promise((l,u)=>{i=u,n=l,this.once(IC,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[a3]=!1;let e=!1,t=()=>(this.pause(),this.off(h8o,t),this.off(IC,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(h8o,t),this.once(IC,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[IC])return e?this.emit("error",e):this.emit(IC),this;this[IC]=!0,this[a3]=!0,this[RT].length=0,this[kT]=0;let t=this;return typeof t.close=="function"&&!this[dHr]&&t.close(),e?this.emit("error",e):this.emit(IC),this}static get isStream(){return h5m}},S5m=M2.default.writev,PSe=Symbol("_autoClose"),eJ=Symbol("_close"),eGt=Symbol("_ended"),ig=Symbol("_fd"),b8o=Symbol("_finished"),Lme=Symbol("_flags"),E8o=Symbol("_flush"),L8o=Symbol("_handleChunk"),_8o=Symbol("_makeBuf"),pGt=Symbol("_mode"),AHr=Symbol("_needDrain"),wct=Symbol("_onerror"),Oct=Symbol("_onopen"),I8o=Symbol("_onread"),Cct=Symbol("_onwrite"),BSe=Symbol("_open"),$K=Symbol("_path"),CSe=Symbol("_pos"),Are=Symbol("_queue"),xct=Symbol("_read"),v8o=Symbol("_readSize"),Mme=Symbol("_reading"),tGt=Symbol("_remain"),C8o=Symbol("_size"),THr=Symbol("_write"),cUe=Symbol("_writing"),OHr=Symbol("_defaultFlag"),AUe=Symbol("_errored"),lGo=class extends EUe{[AUe]=!1;[ig];[$K];[v8o];[Mme]=!1;[C8o];[tGt];[PSe];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[AUe]=!1,this[ig]=typeof t.fd=="number"?t.fd:void 0,this[$K]=e,this[v8o]=t.readSize||16*1024*1024,this[Mme]=!1,this[C8o]=typeof t.size=="number"?t.size:1/0,this[tGt]=this[C8o],this[PSe]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[ig]=="number"?this[xct]():this[BSe]()}get fd(){return this[ig]}get path(){return this[$K]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[BSe](){M2.default.open(this[$K],"r",(e,t)=>this[Oct](e,t))}[Oct](e,t){e?this[wct](e):(this[ig]=t,this.emit("open",t),this[xct]())}[_8o](){return Buffer.allocUnsafe(Math.min(this[v8o],this[tGt]))}[xct](){if(!this[Mme]){this[Mme]=!0;let e=this[_8o]();if(e.length===0)return process.nextTick(()=>this[I8o](null,0,e));M2.default.read(this[ig],e,0,e.length,null,(t,r,n)=>this[I8o](t,r,n))}}[I8o](e,t,r){this[Mme]=!1,e?this[wct](e):this[L8o](t,r)&&this[xct]()}[eJ](){if(this[PSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[wct](e){this[Mme]=!0,this[eJ](),this.emit("error",e)}[L8o](e,t){let r=!1;return this[tGt]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[tGt]<=0)&&(r=!1,this[eJ](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[ig]=="number"&&this[xct](),!1;case"error":return this[AUe]?!1:(this[AUe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},w5m=class extends lGo{[BSe](){let e=!0;try{this[Oct](null,M2.default.openSync(this[$K],"r")),e=!1}finally{e&&this[eJ]()}}[xct](){let e=!0;try{if(!this[Mme]){this[Mme]=!0;do{let t=this[_8o](),r=t.length===0?0:M2.default.readSync(this[ig],t,0,t.length,null);if(!this[L8o](r,t))break}while(!0);this[Mme]=!1}e=!1}finally{e&&this[eJ]()}}[eJ](){if(this[PSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.closeSync(e),this.emit("close")}}},VHr=class extends Nql.default{readable=!1;writable=!0;[AUe]=!1;[cUe]=!1;[eGt]=!1;[Are]=[];[AHr]=!1;[$K];[pGt];[PSe];[ig];[OHr];[Lme];[b8o]=!1;[CSe];constructor(e,t){t=t||{},super(t),this[$K]=e,this[ig]=typeof t.fd=="number"?t.fd:void 0,this[pGt]=t.mode===void 0?438:t.mode,this[CSe]=typeof t.start=="number"?t.start:void 0,this[PSe]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[CSe]!==void 0?"r+":"w";this[OHr]=t.flags===void 0,this[Lme]=t.flags===void 0?r:t.flags,this[ig]===void 0&&this[BSe]()}emit(e,...t){if(e==="error"){if(this[AUe])return!1;this[AUe]=!0}return super.emit(e,...t)}get fd(){return this[ig]}get path(){return this[$K]}[wct](e){this[eJ](),this[cUe]=!0,this.emit("error",e)}[BSe](){M2.default.open(this[$K],this[Lme],this[pGt],(e,t)=>this[Oct](e,t))}[Oct](e,t){this[OHr]&&this[Lme]==="r+"&&e&&e.code==="ENOENT"?(this[Lme]="w",this[BSe]()):e?this[wct](e):(this[ig]=t,this.emit("open",t),this[cUe]||this[E8o]())}end(e,t){return e&&this.write(e,t),this[eGt]=!0,!this[cUe]&&!this[Are].length&&typeof this[ig]=="number"&&this[Cct](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[eGt]?(this.emit("error",new Error("write() after end()")),!1):this[ig]===void 0||this[cUe]||this[Are].length?(this[Are].push(e),this[AHr]=!0,!1):(this[cUe]=!0,this[THr](e),!0)}[THr](e){M2.default.write(this[ig],e,0,e.length,this[CSe],(t,r)=>this[Cct](t,r))}[Cct](e,t){e?this[wct](e):(this[CSe]!==void 0&&typeof t=="number"&&(this[CSe]+=t),this[Are].length?this[E8o]():(this[cUe]=!1,this[eGt]&&!this[b8o]?(this[b8o]=!0,this[eJ](),this.emit("finish")):this[AHr]&&(this[AHr]=!1,this.emit("drain"))))}[E8o](){if(this[Are].length===0)this[eGt]&&this[Cct](null,0);else if(this[Are].length===1)this[THr](this[Are].pop());else{let e=this[Are];this[Are]=[],S5m(this[ig],e,this[CSe],(t,r)=>this[Cct](t,r))}}[eJ](){if(this[PSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},Qql=class extends VHr{[BSe](){let e;if(this[OHr]&&this[Lme]==="r+")try{e=M2.default.openSync(this[$K],this[Lme],this[pGt])}catch(t){if(t?.code==="ENOENT")return this[Lme]="w",this[BSe]();throw t}else e=M2.default.openSync(this[$K],this[Lme],this[pGt]);this[Oct](null,e)}[eJ](){if(this[PSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.closeSync(e),this.emit("close")}}[THr](e){let t=!0;try{this[Cct](null,M2.default.writeSync(this[ig],e,0,e.length,this[CSe])),t=!1}finally{if(t)try{this[eJ]()}catch{}}}},T5m=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"]]),O5m=e=>!!e.sync&&!!e.file,P5m=e=>!e.sync&&!!e.file,B5m=e=>!!e.sync&&!e.file,D5m=e=>!e.sync&&!e.file,R5m=e=>!!e.file,k5m=e=>T5m.get(e)||e,pGo=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=k5m(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},IGt=(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=pGo(o);if(i?.(c,s),O5m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(c,s)}else if(P5m(c)){let l=t(c,s);return a?l.then(()=>a(),a):l}else if(B5m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,s)}else if(D5m(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}),F5m=Lql.default.constants||{ZLIB_VERNUM:4736},Ere=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},F5m)),N5m=TSe.Buffer.concat,cql=Object.getOwnPropertyDescriptor(TSe.Buffer,"concat"),j5m=e=>e,x8o=cql?.writable===!0||cql?.set!==void 0?e=>{TSe.Buffer.concat=e?j5m:N5m}:e=>{},yUe=Symbol("_superWrite"),yHr=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"}},S8o=Symbol("flushFlag"),fGo=class extends EUe{#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 aql[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new aql[t](e)}catch(r){throw new yHr(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 yHr(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,QHr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(TSe.Buffer.alloc(0),{[S8o]: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}[yUe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=TSe.Buffer.from(e,t)),this.#e)return;(0,QHr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},x8o(!0);let s;try{let c=typeof e[S8o]=="number"?e[S8o]:this.#r;s=this.#o._processChunk(e,c),x8o(!1)}catch(c){x8o(!1),this.#s(new yHr(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 yHr(c,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let c=s[0];a=this[yUe](TSe.Buffer.from(c));for(let l=1;l<s.length;l++)a=this[yUe](s[l])}else a=this[yUe](TSe.Buffer.from(s));return r&&r(),a}},_ql=class extends fGo{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||Ere.Z_NO_FLUSH,e.finishFlush=e.finishFlush||Ere.Z_FINISH,e.fullFlushFlag=Ere.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(Ere.Z_SYNC_FLUSH),(0,QHr.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)}}}},z5m=class extends _ql{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[yUe](e){return this.#e?(this.#e=!1,e[9]=255,super[yUe](e)):super[yUe](e)}},Q5m=class extends _ql{constructor(e){super(e,"Unzip")}},Uql=class extends fGo{constructor(e,t){e=e||{},e.flush=e.flush||Ere.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Ere.BROTLI_OPERATION_FINISH,e.fullFlushFlag=Ere.BROTLI_OPERATION_FLUSH,super(e,t)}},M5m=class extends Uql{constructor(e){super(e,"BrotliCompress")}},L5m=class extends Uql{constructor(e){super(e,"BrotliDecompress")}},Vql=class extends fGo{constructor(e,t){e=e||{},e.flush=e.flush||Ere.ZSTD_e_continue,e.finishFlush=e.finishFlush||Ere.ZSTD_e_end,e.fullFlushFlag=Ere.ZSTD_e_flush,super(e,t)}},_5m=class extends Vql{constructor(e){super(e,"ZstdCompress")}},U5m=class extends Vql{constructor(e){super(e,"ZstdDecompress")}},V5m=(e,t)=>{if(Number.isSafeInteger(e))e<0?q5m(e,t):G5m(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},G5m=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},q5m=(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]=Gql(i):i===0?t[n-1]=0:(r=!0,t[n-1]=qql(i))}},W5m=e=>{let t=e[0],r=t===128?K5m(e.subarray(1,e.length)):t===255?H5m(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},H5m=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=Gql(o):o===0?s=o:(n=!0,s=qql(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},K5m=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},Gql=e=>(255^e)&255,qql=e=>(255^e)+1&255,J5m={};m5m(J5m,{code:()=>dGo,isCode:()=>PHr,isName:()=>Y5m,name:()=>qHr,normalFsTypes:()=>Wql});PHr=e=>qHr.has(e),Y5m=e=>dGo.has(e),Wql=new Set(["0","","1","2","3","4","5","6","7","D"]),qHr=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"]]),dGo=new Map(Array.from(qHr).map(e=>[e[1],e[0]])),bUe=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");let i=lUe(e,t+156,1),o=Wql.has(i),s=o?r:void 0,a=o?n:void 0;if(this.path=s?.path??lUe(e,t,100),this.mode=s?.mode??a?.mode??xSe(e,t+100,8),this.uid=s?.uid??a?.uid??xSe(e,t+108,8),this.gid=s?.gid??a?.gid??xSe(e,t+116,8),this.size=s?.size??a?.size??xSe(e,t+124,12),this.mtime=s?.mtime??a?.mtime??w8o(e,t+136,12),this.cksum=xSe(e,t+148,12),a&&this.#t(a,!0),s&&this.#t(s),PHr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=lUe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=s?.uname??a?.uname??lUe(e,t+265,32),this.gname=s?.gname??a?.gname??lUe(e,t+297,32),this.devmaj=s?.devmaj??a?.devmaj??xSe(e,t+329,8)??0,this.devmin=s?.devmin??a?.devmin??xSe(e,t+337,8)??0,e[t+475]!==0){let l=lUe(e,t+345,155);this.path=l+"/"+this.path}else{let l=lUe(e,t+345,130);l&&(this.path=l+"/"+this.path),this.atime=r?.atime??n?.atime??w8o(e,t+476,12),this.ctime=r?.ctime??n?.ctime??w8o(e,t+488,12)}let c=256;for(let l=t;l<t+148;l++)c+=e[l];for(let l=t+156;l<t+512;l++)c+=e[l];this.cksumValid=c===this.cksum,this.cksum===void 0&&c===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=X5m(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=uUe(e,t,100,i)||this.needPax,this.needPax=SSe(e,t+100,8,this.mode)||this.needPax,this.needPax=SSe(e,t+108,8,this.uid)||this.needPax,this.needPax=SSe(e,t+116,8,this.gid)||this.needPax,this.needPax=SSe(e,t+124,12,this.size)||this.needPax,this.needPax=T8o(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=uUe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=uUe(e,t+265,32,this.uname)||this.needPax,this.needPax=uUe(e,t+297,32,this.gname)||this.needPax,this.needPax=SSe(e,t+329,8,this.devmaj)||this.needPax,this.needPax=SSe(e,t+337,8,this.devmin)||this.needPax,this.needPax=uUe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=uUe(e,t+345,155,o)||this.needPax:(this.needPax=uUe(e,t+345,130,o)||this.needPax,this.needPax=T8o(e,t+476,12,this.atime)||this.needPax,this.needPax=T8o(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,SSe(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:qHr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(dGo.get(e));if(PHr(t)||t==="Unsupported")this.#e=t;else if(PHr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},X5m=(e,t)=>{let r=e,n="",i,o=hUe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=hUe.posix.dirname(r),r=hUe.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=hUe.posix.join(hUe.posix.basename(n),r),n=hUe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},lUe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),w8o=(e,t,r)=>Z5m(xSe(e,t,r)),Z5m=e=>e===void 0?void 0:new Date(e*1e3),xSe=(e,t,r)=>Number(e[t])&128?W5m(e.subarray(t,t+r)):e8m(e,t,r),$5m=e=>isNaN(e)?void 0:e,e8m=(e,t,r)=>$5m(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),t8m={12:8589934591,8:2097151},SSe=(e,t,r,n)=>n===void 0?!1:n>t8m[r]||n<0?(V5m(n,e.subarray(t,t+r)),!0):(r8m(e,t,r,n),!1),r8m=(e,t,r,n)=>e.write(n8m(n,r),t,r,"ascii"),n8m=(e,t)=>i8m(Math.floor(e).toString(8),t),i8m=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",T8o=(e,t,r,n)=>n===void 0?!1:SSe(e,t,r,n.getTime()/1e3),o8m=new Array(156).join("\0"),uUe=(e,t,r,n)=>n===void 0?!1:(e.write(n+o8m,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),MHr=class Kql{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 bUe({path:("PaxHeader/"+(0,Hql.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+`
|
|
549
549
|
`,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 Kql(s8m(a8m(t),r),n)}},s8m=(e,t)=>t?Object.assign({},t,e):e,a8m=e=>e.replace(/\n$/,"").split(`
|
|
550
|
-
`).reduce(c8m,Object.create(null)),c8m=(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},l8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lf=l8m!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),u8m=class extends EUe{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=lf(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?lf(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=lf(e.path)),e.linkpath&&(e.linkpath=lf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},WHr=(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))},p8m=1024*1024,U8o=Buffer.from([31,139]),V8o=Buffer.from([40,181,47,253]),f8m=Math.max(U8o.length,V8o.length),p8=Symbol("state"),pUe=Symbol("writeEntry"),zme=Symbol("readEntry"),O8o=Symbol("nextEntry"),lql=Symbol("processEntry"),yre=Symbol("extendedHeader"),rGt=Symbol("globalExtendedHeader"),bSe=Symbol("meta"),uql=Symbol("emitMeta"),Jb=Symbol("buffer"),Qme=Symbol("queue"),ESe=Symbol("ended"),P8o=Symbol("emittedEnd"),fUe=Symbol("emit"),Wx=Symbol("unzip"),bHr=Symbol("consumeChunk"),EHr=Symbol("consumeChunkSub"),B8o=Symbol("consumeBody"),pql=Symbol("consumeMeta"),fql=Symbol("consumeHeader"),nGt=Symbol("consuming"),D8o=Symbol("bufferConcat"),IHr=Symbol("maybeEnd"),bct=Symbol("writing"),ISe=Symbol("aborted"),vHr=Symbol("onDone"),dUe=Symbol("sawValidEntry"),CHr=Symbol("sawNullBlock"),xHr=Symbol("sawEOF"),dql=Symbol("closeStream"),d8m=()=>!0,yGt=class extends Mql.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Qme]=[];[Jb];[zme];[pUe];[p8]="begin";[bSe]="";[yre];[rGt];[ESe]=!1;[Wx];[ISe]=!1;[dUe];[CHr]=!1;[xHr]=!1;[bct]=!1;[nGt]=!1;[P8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(vHr,()=>{(this[p8]==="begin"||this[dUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(vHr,e.ondone):this.on(vHr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||p8m,this.filter=typeof e.filter=="function"?e.filter:d8m;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[dql]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){WHr(this,e,t,r)}[fql](e,t){this[dUe]===void 0&&(this[dUe]=!1);let r;try{r=new bUe(e,t,this[yre],this[rGt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[CHr]?(this[xHr]=!0,this[p8]==="begin"&&(this[p8]="header"),this[fUe]("eof")):(this[CHr]=!0,this[fUe]("nullBlock"));else if(this[CHr]=!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[pUe]=new u8m(r,this[yre],this[rGt]);if(!this[dUe])if(i.remain){let o=()=>{i.invalid||(this[dUe]=!0)};i.on("end",o)}else this[dUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[fUe]("ignoredEntry",i),this[p8]="ignore",i.resume()):i.size>0&&(this[bSe]="",i.on("data",o=>this[bSe]+=o),this[p8]="meta"):(this[yre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[fUe]("ignoredEntry",i),this[p8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[p8]="body":(this[p8]="header",i.end()),this[zme]?this[Qme].push(i):(this[Qme].push(i),this[O8o]())))}}}[dql](){queueMicrotask(()=>this.emit("close"))}[lql](e){let t=!0;if(!e)this[zme]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[zme]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[O8o]()),t=!1);return t}[O8o](){do;while(this[lql](this[Qme].shift()));if(this[Qme].length===0){let e=this[zme];!e||e.flowing||e.size===e.remain?this[bct]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[B8o](e,t){let r=this[pUe];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[p8]="header",this[pUe]=void 0,r.end()),i.length}[pql](e,t){let r=this[pUe],n=this[B8o](e,t);return!this[pUe]&&r&&this[uql](r),n}[fUe](e,t,r){this[Qme].length===0&&!this[zme]?this.emit(e,t,r):this[Qme].push([e,t,r])}[uql](e){switch(this[fUe]("meta",this[bSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[yre]=MHr.parse(this[bSe],this[yre],!1);break;case"GlobalExtendedHeader":this[rGt]=MHr.parse(this[bSe],this[rGt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[yre]??Object.create(null);this[yre]=t,t.path=this[bSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[yre]||Object.create(null);this[yre]=t,t.linkpath=this[bSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ISe]=!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[ISe])return r?.(),!1;if((this[Wx]===void 0||this.brotli===void 0&&this[Wx]===!1)&&e){if(this[Jb]&&(e=Buffer.concat([this[Jb],e]),this[Jb]=void 0),e.length<f8m)return this[Jb]=e,r?.(),!0;for(let s=0;this[Wx]===void 0&&s<U8o.length;s++)e[s]!==U8o[s]&&(this[Wx]=!1);let i=!1;if(this[Wx]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<V8o.length;s++)if(e[s]!==V8o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Wx]===!1&&o)if(e.length<512)if(this[ESe])this.brotli=!0;else return this[Jb]=e,r?.(),!0;else try{new bUe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Wx]===void 0||this[Wx]===!1&&(this.brotli||i)){let s=this[ESe];this[ESe]=!1,this[Wx]=this[Wx]===void 0?new Q5m({}):i?new U5m({}):new L5m({}),this[Wx].on("data",c=>this[bHr](c)),this[Wx].on("error",c=>this.abort(c)),this[Wx].on("end",()=>{this[ESe]=!0,this[bHr]()}),this[bct]=!0;let a=!!this[Wx][s?"end":"write"](e);return this[bct]=!1,r?.(),a}}this[bct]=!0,this[Wx]?this[Wx].write(e):this[bHr](e),this[bct]=!1;let n=this[Qme].length>0?!1:this[zme]?this[zme].flowing:!0;return!n&&this[Qme].length===0&&this[zme]?.once("drain",()=>this.emit("drain")),r?.(),n}[D8o](e){e&&!this[ISe]&&(this[Jb]=this[Jb]?Buffer.concat([this[Jb],e]):e)}[IHr](){if(this[ESe]&&!this[P8o]&&!this[ISe]&&!this[nGt]){this[P8o]=!0;let e=this[pUe];if(e&&e.blockRemain){let t=this[Jb]?this[Jb].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Jb]&&e.write(this[Jb]),e.end()}this[fUe](vHr)}}[bHr](e){if(this[nGt]&&e)this[D8o](e);else if(!e&&!this[Jb])this[IHr]();else if(e){if(this[nGt]=!0,this[Jb]){this[D8o](e);let t=this[Jb];this[Jb]=void 0,this[EHr](t)}else this[EHr](e);for(;this[Jb]&&this[Jb]?.length>=512&&!this[ISe]&&!this[xHr];){let t=this[Jb];this[Jb]=void 0,this[EHr](t)}this[nGt]=!1}(!this[Jb]||this[ESe])&&this[IHr]()}[EHr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ISe]&&!this[xHr];)switch(this[p8]){case"begin":case"header":this[fql](e,t),t+=512;break;case"ignore":case"body":t+=this[B8o](e,t);break;case"meta":t+=this[pql](e,t);break;default:throw new Error("invalid state: "+this[p8])}t<r&&(this[Jb]=this[Jb]?Buffer.concat([e.subarray(t),this[Jb]]):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[ISe]||(this[Wx]?(e&&this[Wx].write(e),this[Wx].end()):(this[ESe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[IHr]())),this}},fGt=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)},m8m=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},Jql=(e,t)=>{let r=new Map(t.map(o=>[fGt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,GHr.parse)(o).root||".",c;if(o===a)c=!1;else{let l=r.get(o);c=l!==void 0?l:i((0,GHr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(fGt(o)):o=>i(fGt(o))},h8m=e=>{let t=new yGt(e),r=e.file,n;try{n=gUe.default.openSync(r,"r");let i=gUe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=gUe.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=gUe.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{gUe.default.closeSync(n)}catch{}}},g8m=(e,t)=>{let r=new yGt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),gUe.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},HHr=IGt(h8m,g8m,e=>new yGt(e),e=>new yGt(e),(e,t)=>{t?.length&&Jql(e,t),e.noResume||m8m(e)}),Yql=(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:A8m,parse:mql}=Xql.win32,mGo=e=>{let t="",r=mql(e);for(;A8m(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=mql(e)}return[t,e]},KHr=["|","<",">","?",":"],hGo=KHr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),y8m=new Map(KHr.map((e,t)=>[e,hGo[t]])),b8m=new Map(hGo.map((e,t)=>[e,KHr[t]])),hql=e=>KHr.reduce((t,r)=>t.split(r).join(y8m.get(r)),e),E8m=e=>hGo.reduce((t,r)=>t.split(r).join(b8m.get(r)),e),Zql=(e,t)=>t?(e=lf(e).replace(/^\.(\/|$)/,""),fGt(t)+"/"+e):lf(e),I8m=16*1024*1024,gql=Symbol("process"),Aql=Symbol("file"),yql=Symbol("directory"),q8o=Symbol("symlink"),bql=Symbol("hardlink"),iGt=Symbol("header"),BHr=Symbol("read"),W8o=Symbol("lstat"),DHr=Symbol("onlstat"),H8o=Symbol("onread"),K8o=Symbol("onreadlink"),J8o=Symbol("openfile"),Y8o=Symbol("onopenfile"),wSe=Symbol("close"),LHr=Symbol("mode"),X8o=Symbol("awaitDrain"),R8o=Symbol("ondrain"),bre=Symbol("prefix"),$ql=class extends EUe{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=pGo(t);super(),this.path=lf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||I8m,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=lf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?lf(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]=mGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=E8m(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=lf(r.absolute||G8o.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[DHr](i):this[W8o]()}warn(e,t,r={}){return WHr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[W8o](){ZK.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[DHr](t)})}[DHr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=x8m(e),this.emit("stat",e),this[gql]()}[gql](){switch(this.type){case"File":return this[Aql]();case"Directory":return this[yql]();case"SymbolicLink":return this[q8o]();default:return this.end()}}[LHr](e){return Yql(e,this.type==="Directory",this.portable)}[bre](e){return Zql(e,this.prefix)}[iGt](){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 bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this[LHr](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 MHr({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[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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)}[yql](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[iGt](),this.end()}[q8o](){ZK.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[K8o](t)})}[K8o](e){this.linkpath=lf(e),this[iGt](),this.end()}[bql](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=lf(G8o.default.relative(this.cwd,e)),this.stat.size=0,this[iGt](),this.end()}[Aql](){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[bql](t);this.linkCache.set(e,this.absolute)}if(this[iGt](),this.stat.size===0)return this.end();this[J8o]()}[J8o](){ZK.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Y8o](t)})}[Y8o](e){if(this.fd=e,this.#e)return this[wSe]();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[BHr]()}[BHr](){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");ZK.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[wSe](()=>this.emit("error",o));this[H8o](s)})}[wSe](e=()=>{}){this.fd!==void 0&&ZK.default.close(this.fd,e)}[H8o](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[wSe](()=>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[wSe](()=>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[R8o]():this[X8o](()=>this[R8o]())}[X8o](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)}[R8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[wSe](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[BHr]()}},v8m=class extends $ql{sync=!0;[W8o](){this[DHr](ZK.default.lstatSync(this.absolute))}[q8o](){this[K8o](ZK.default.readlinkSync(this.absolute))}[J8o](){this[Y8o](ZK.default.openSync(this.absolute,"r"))}[BHr](){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=ZK.default.readSync(t,r,n,i,o);this[H8o](s),e=!1}finally{if(e)try{this[wSe](()=>{})}catch{}}}[X8o](e){e()}[wSe](e=()=>{}){this.fd!==void 0&&ZK.default.closeSync(this.fd),e()}},C8m=class extends EUe{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 WHr(this,e,t,r)}constructor(e,t={}){let r=pGo(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=lf(e.path),this.mode=e.mode!==void 0?this[LHr](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?lf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=mGo(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 bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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 MHr({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[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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)}[bre](e){return Zql(e,this.prefix)}[LHr](e){return Yql(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}},x8m=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",S8m=class Sct{tail;head;length=0;static create(t=[]){return new Sct(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++)T8m(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)O8m(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 Sct;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 Sct;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 Sct;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 Sct;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=w8m(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}};gGo=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}},Eql=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Iql=Buffer.alloc(1024),RHr=Symbol("onStat"),oGt=Symbol("ended"),YK=Symbol("queue"),sGt=Symbol("pendingLinks"),vSe=Symbol("current"),mUe=Symbol("process"),aGt=Symbol("processing"),SHr=Symbol("processJob"),XK=Symbol("jobs"),k8o=Symbol("jobDone"),kHr=Symbol("addFSEntry"),vql=Symbol("addTarEntry"),$8o=Symbol("stat"),eGo=Symbol("readdir"),FHr=Symbol("onreaddir"),NHr=Symbol("pipe"),Cql=Symbol("entry"),F8o=Symbol("entryOpt"),jHr=Symbol("writeEntryClass"),eWl=Symbol("write"),N8o=Symbol("ondrain"),JHr=class extends EUe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[jHr];onWriteEntry;[YK];[sGt]=new Map;[XK]=0;[aGt]=!1;[oGt]=!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=lf(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[jHr]=$ql,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 z5m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new M5m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new _5m(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[N8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[N8o]);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[YK]=new S8m,this[XK]=0,this.jobs=Number(e.jobs)||4,this[aGt]=!1,this[oGt]=!1}[eWl](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[oGt]=!0,this[mUe](),r&&r(),this}write(e){if(this[oGt])throw new Error("write after end");return typeof e=="string"?this[kHr](e):this[vql](e),this.flowing}[vql](e){let t=lf(Z8o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new Eql(e.path,t);r.entry=new C8m(e,this[F8o](r)),r.entry.on("end",()=>this[k8o](r)),this[XK]+=1,this[YK].push(r)}this[mUe]()}[kHr](e){let t=lf(Z8o.default.resolve(this.cwd,e));this[YK].push(new Eql(e,t)),this[mUe]()}[$8o](e){e.pending=!0,this[XK]+=1;let t=this.follow?"stat":"lstat";bGt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[XK]-=1,r?this.emit("error",r):this[RHr](e,n)})}[RHr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[vSe])this[SHr](e);else{let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);n?n.push(e):this[sGt].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[mUe]()}[eGo](e){e.pending=!0,this[XK]+=1,bGt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[XK]-=1,t)return this.emit("error",t);this[FHr](e,r)})}[FHr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[mUe]()}[mUe](){if(!this[aGt]){this[aGt]=!0;for(let e=this[YK].head;e&&this[XK]<this.jobs;e=e.next)if(this[SHr](e.value),e.value.ignore){let t=e.next;this[YK].removeNode(e),e.next=t}this[aGt]=!1,this[oGt]&&this[YK].length===0&&this[XK]===0&&(this.zip?this.zip.end(Iql):(super.write(Iql),super.end()))}}get[vSe](){return this[YK]&&this[YK].head&&this[YK].head.value}[k8o](e){this[YK].shift(),this[XK]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);if(n){this[sGt].delete(r);for(let i of n)i.pending=!1,this[SHr](i)}}this[mUe]()}[SHr](e){if(e.pending&&e.pendingLink&&e===this[vSe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[vSe]&&!e.piped&&this[NHr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[RHr](e,t):this[$8o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[FHr](e,t):this[eGo](e),!e.readdir)return}if(e.entry=this[Cql](e),!e.entry){e.ignore=!0;return}e===this[vSe]&&!e.piped&&this[NHr](e)}}}[F8o](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}}[Cql](e){this[XK]+=1;try{return new this[jHr](e.path,this[F8o](e)).on("end",()=>this[k8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[N8o](){this[vSe]&&this[vSe].entry&&this[vSe].entry.resume()}[NHr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](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={}){WHr(this,e,t,r)}},AGo=class extends JHr{sync=!0;constructor(e){super(e),this[jHr]=v8m}pause(){}resume(){}[$8o](e){let t=this.follow?"statSync":"lstatSync";this[RHr](e,bGt.default[t](e.absolute))}[eGo](e){this[FHr](e,bGt.default.readdirSync(e.absolute))}[NHr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[eWl](n)})}},P8m=(e,t)=>{let r=new AGo(e),n=new Qql(e.file,{mode:e.mode||438});r.pipe(n),tWl(r,t)},B8m=(e,t)=>{let r=new JHr(e),n=new VHr(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 rWl(r,t).catch(o=>r.emit("error",o)),i},tWl=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:uGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},rWl=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:uGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},D8m=(e,t)=>{let r=new AGo(e);return tWl(r,t),r},R8m=(e,t)=>{let r=new JHr(e);return rWl(r,t).catch(n=>r.emit("error",n)),r},YHr=IGt(P8m,B8m,D8m,R8m,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),k8m=process.env.__FAKE_PLATFORM__||process.platform,iWl=k8m==="win32",{O_CREAT:oWl,O_NOFOLLOW:xql,O_TRUNC:sWl,O_WRONLY:aWl}=EGo.default.constants,cWl=Number(process.env.__FAKE_FS_O_FILENAME__)||EGo.default.constants.UV_FS_O_FILEMAP||0,F8m=iWl&&!!cWl,N8m=512*1024,j8m=cWl|sWl|oWl|aWl,Sql=!iWl&&typeof xql=="number"?xql|sWl|oWl|aWl:null,lWl=Sql!==null?()=>Sql:F8m?e=>e<N8m?j8m:"w":()=>"w",tGo=(e,t,r)=>{try{return vGt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},_Hr=(e,t,r,n)=>{vGt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},z8m=(e,t,r,n,i)=>{if(t.isDirectory())uWl(Tct.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Tct.default.resolve(e,t.name);_Hr(s,r,n,i)});else{let o=Tct.default.resolve(e,t.name);_Hr(o,r,n,i)}},uWl=(e,t,r,n)=>{vGt.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 _Hr(e,t,r,n);let s=o.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--s===0)return _Hr(e,t,r,n)}};for(let l of o)z8m(e,l,t,r,c)})},Q8m=(e,t,r,n)=>{t.isDirectory()&&pWl(Tct.default.resolve(e,t.name),r,n),tGo(Tct.default.resolve(e,t.name),r,n)},pWl=(e,t,r)=>{let n;try{n=vGt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return tGo(e,t,r);throw o}for(let i of n)Q8m(e,i,t,r);return tGo(e,t,r)},dWl=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"}},XHr=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"}},M8m=(e,t)=>{VQ.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new dWl(e,r?.code||"ENOTDIR")),t(r)})},L8m=(e,t,r)=>{e=lf(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),l=t.preserve,u=t.unlink,p=lf(t.cwd),d=(m,g)=>{m?r(m):g&&c?uWl(g,s,a,A=>d(A)):o?VQ.default.chmod(e,i,r):r()};if(e===p)return M8m(e,d);if(l)return fWl.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=lf(EGt.default.relative(p,e)).split("/");rGo(p,f,i,u,p,void 0,d)},rGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=lf(EGt.default.resolve(e+"/"+a));VQ.default.mkdir(c,r,mWl(c,t,r,n,i,o,s))},mWl=(e,t,r,n,i,o,s)=>a=>{a?VQ.default.lstat(e,(c,l)=>{if(c)c.path=c.path&&lf(c.path),s(c);else if(l.isDirectory())rGo(e,t,r,n,i,o,s);else if(n)VQ.default.unlink(e,u=>{if(u)return s(u);VQ.default.mkdir(e,r,mWl(e,t,r,n,i,o,s))});else{if(l.isSymbolicLink())return s(new XHr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,rGo(e,t,r,n,i,o,s))},_8m=e=>{let t=!1,r;try{t=VQ.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new dWl(e,r??"ENOTDIR")}},U8m=(e,t)=>{e=lf(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,l=t.unlink,u=lf(t.cwd),p=m=>{m&&a&&pWl(m,o,s),i&&VQ.default.chmodSync(e,n)};if(e===u)return _8m(u),p();if(c)return p(VQ.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=lf(EGt.default.relative(u,e)).split("/"),f;for(let m=d.shift(),g=u;m&&(g+="/"+m);m=d.shift()){g=lf(EGt.default.resolve(g));try{VQ.default.mkdirSync(g,n),f=f||g}catch{let A=VQ.default.lstatSync(g);if(A.isDirectory())continue;if(l){VQ.default.unlinkSync(g),VQ.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new XHr(g,g+"/"+d.join("/"))}}return p(f)},j8o=Object.create(null),wql=1e4,Ect=new Set,V8m=e=>{Ect.has(e)?Ect.delete(e):j8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ect.add(e);let t=j8o[e],r=Ect.size-wql;if(r>wql/10){for(let n of Ect)if(Ect.delete(n),delete j8o[n],--r<=0)break}return t},G8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,q8m=G8m==="win32",W8m=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,IGo.join)(n,r)),t.push(r||"/"),t},[]),H8m=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=q8m?["win32 parallelization disabled"]:e.map(n=>fGt((0,IGo.join)(V8m(n))));let r=new Set(e.map(n=>W8m(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}},K8m=()=>process.umask(),Tql=Symbol("onEntry"),nGo=Symbol("checkFs"),Oql=Symbol("checkFs2"),iGo=Symbol("isReusable"),f8=Symbol("makeFs"),oGo=Symbol("file"),sGo=Symbol("directory"),zHr=Symbol("link"),Pql=Symbol("symlink"),Bql=Symbol("hardlink"),uGt=Symbol("ensureNoSymlink"),Dql=Symbol("unsupported"),Rql=Symbol("checkPath"),z8o=Symbol("stripAbsolutePath"),OSe=Symbol("mkdir"),FT=Symbol("onError"),wHr=Symbol("pending"),kql=Symbol("pend"),Ict=Symbol("unpend"),Q8o=Symbol("ended"),M8o=Symbol("maybeClose"),aGo=Symbol("skip"),dGt=Symbol("doChown"),mGt=Symbol("uid"),hGt=Symbol("gid"),gGt=Symbol("checkedCwd"),J8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,AGt=J8m==="win32",Y8m=1024,X8m=(e,t)=>{if(!AGt)return Ed.default.unlink(e,t);let r=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.rename(e,r,n=>{if(n)return t(n);Ed.default.unlink(r,t)})},Z8m=e=>{if(!AGt)return Ed.default.unlinkSync(e);let t=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.renameSync(e,t),Ed.default.unlinkSync(t)},Fql=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,vGo=class extends yGt{[Q8o]=!1;[gGt]=!1;[wHr]=0;reservations=new H8m;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[Q8o]=!0,this[M8o]()},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:Y8m,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||AGt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=lf(Hx.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:K8m():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[Tql](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[M8o](){this[Q8o]&&this[wHr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[z8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=mGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||AGt&&/^[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=Hx.default.posix.dirname(e.path),c=Hx.default.posix.normalize(Hx.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}[Rql](e){let t=lf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=lf(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[z8o](e,"path")||!this[z8o](e,"linkpath"))return!1;if(e.absolute=Hx.default.isAbsolute(e.path)?lf(Hx.default.resolve(e.path)):lf(Hx.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:lf(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}=Hx.default.win32.parse(String(e.absolute));e.absolute=n+hql(String(e.absolute).slice(n.length));let{root:i}=Hx.default.win32.parse(e.path);e.path=i+hql(e.path.slice(i.length))}return!0}[Tql](e){if(!this[Rql](e))return e.resume();switch(nWl.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[nGo](e);default:return this[Dql](e)}}[FT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Ict](),t.resume())}[OSe](e,t,r){L8m(lf(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)}[dGt](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}[mGt](e){return Fql(this.uid,e.uid,this.processUid)}[hGt](e){return Fql(this.gid,e.gid,this.processGid)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new VHr(String(e.absolute),{flags:lWl(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Ed.default.close(n.fd,()=>{}),n.write=()=>!0,this[FT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Ed.default.close(n.fd,()=>{}),this[FT](a,e),t();return}--i===0&&n.fd!==void 0&&Ed.default.close(n.fd,c=>{c?this[FT](c,e):this[Ict](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let l=e.atime||new Date,u=e.mtime;Ed.default.futimes(c,l,u,p=>p?Ed.default.utimes(a,l,u,d=>o(d&&p)):o())}if(typeof c=="number"&&this[dGt](e)){i++;let l=this[mGt](e),u=this[hGt](e);typeof l=="number"&&typeof u=="number"&&Ed.default.fchown(c,l,u,p=>p?Ed.default.chown(a,l,u,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[FT](a,e),t()}),e.pipe(s)),s.pipe(n)}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[OSe](String(e.absolute),r,n=>{if(n){this[FT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Ict](),e.resume())};e.mtime&&!this.noMtime&&(i++,Ed.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[dGt](e)&&(i++,Ed.default.chown(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)),o)),o()})}[Dql](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Pql](e,t){let r=lf(Hx.default.relative(this.cwd,Hx.default.resolve(Hx.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[uGt](e,this.cwd,r,()=>this[zHr](e,String(e.linkpath),"symlink",t),n=>{this[FT](n,e),t()})}[Bql](e,t){let r=lf(Hx.default.resolve(this.cwd,String(e.linkpath))),n=lf(String(e.linkpath)).split("/");this[uGt](e,this.cwd,n,()=>this[zHr](e,r,"link",t),i=>{this[FT](i,e),t()})}[uGt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=Hx.default.resolve(t,o);Ed.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new XHr(s,Hx.default.resolve(s,r.join("/"))));this[uGt](e,s,r,n,i)})}[kql](){this[wHr]++}[Ict](){this[wHr]--,this[M8o]()}[aGo](e){this[Ict](),e.resume()}[iGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!AGt}[nGo](e){this[kql]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Oql](e,r))}[Oql](e,t){let r=s=>{t(s)},n=()=>{this[OSe](this.cwd,this.dmode,s=>{if(s){this[FT](s,e),r();return}this[gGt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=lf(Hx.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[OSe](s,this.dmode,a=>{if(a){this[FT](a,e),r();return}o()})}o()},o=()=>{Ed.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[aGo](e),r();return}if(s||this[iGo](e,a))return this[f8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,l=u=>this[f8](u??null,e,r);return c?Ed.default.chmod(String(e.absolute),Number(e.mode),l):l()}if(e.absolute!==this.cwd)return Ed.default.rmdir(String(e.absolute),c=>this[f8](c??null,e,r))}if(e.absolute===this.cwd)return this[f8](null,e,r);X8m(String(e.absolute),c=>this[f8](c??null,e,r))})};this[gGt]?i():n()}[f8](e,t,r){if(e){this[FT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[oGo](t,r);case"Link":return this[Bql](t,r);case"SymbolicLink":return this[Pql](t,r);case"Directory":case"GNUDumpDir":return this[sGo](t,r)}}[zHr](e,t,r,n){Ed.default[r](t,String(e.absolute),i=>{i?this[FT](i,e):(this[Ict](),e.resume()),n()})}},cGt=e=>{try{return[null,e()]}catch(t){return[t,null]}},hWl=class extends vGo{sync=!0;[f8](e,t){return super[f8](e,t,()=>{})}[nGo](e){if(!this[gGt]){let i=this[OSe](this.cwd,this.dmode);if(i)return this[FT](i,e);this[gGt]=!0}if(e.absolute!==this.cwd){let i=lf(Hx.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[OSe](i,this.dmode);if(o)return this[FT](o,e)}}let[t,r]=cGt(()=>Ed.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[aGo](e);if(t||this[iGo](e,r))return this[f8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?cGt(()=>{Ed.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[f8](s,e)}let[i]=cGt(()=>Ed.default.rmdirSync(String(e.absolute)));this[f8](i,e)}let[n]=e.absolute===this.cwd?[]:cGt(()=>Z8m(String(e.absolute)));this[f8](n,e)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Ed.default.closeSync(i)}catch(c){a=c}(s||a)&&this[FT](s||a,e),t()},i;try{i=Ed.default.openSync(String(e.absolute),lWl(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[FT](s,e)),e.pipe(o)),o.on("data",s=>{try{Ed.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{Ed.default.futimesSync(i,a,c)}catch(l){try{Ed.default.utimesSync(String(e.absolute),a,c)}catch{s=l}}}if(this[dGt](e)){let a=this[mGt](e),c=this[hGt](e);try{Ed.default.fchownSync(i,Number(a),Number(c))}catch(l){try{Ed.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||l}}}n(s)})}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[OSe](String(e.absolute),r);if(n){this[FT](n,e),t();return}if(e.mtime&&!this.noMtime)try{Ed.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[dGt](e))try{Ed.default.chownSync(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)))}catch{}t(),e.resume()}[OSe](e,t){try{return U8m(lf(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}}[uGt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=Hx.default.resolve(o,s);let[a,c]=cGt(()=>Ed.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new XHr(o,Hx.default.resolve(t,r.join("/"))))}n()}[zHr](e,t,r,n){let i=`${r}Sync`;try{Ed.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[FT](o,e)}}},$8m=e=>{let t=new hWl(e),r=e.file,n=yGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new w5m(r,{readSize:i,size:n.size}).pipe(t)},eGm=(e,t)=>{let r=new vGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),yGo.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},gWl=IGt($8m,eGm,e=>new hWl(e),e=>new vGo(e),(e,t)=>{t?.length&&Jql(e,t)}),tGm=(e,t)=>{let r=new AGo(e),n=!0,i,o;try{try{i=UQ.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=UQ.default.openSync(e.file,"w+");else throw c}let s=UQ.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let u=0,p=0;u<512;u+=p){if(p=UQ.default.readSync(i,a,u,a.length-u,o+u),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new bUe(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(o+l+512>s.size)break;o+=l,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,rGm(e,r,o,i,t)}finally{if(n)try{UQ.default.closeSync(i)}catch{}}},rGm=(e,t,r,n,i)=>{let o=new Qql(e.file,{fd:n,start:r});t.pipe(o),iGm(t,i)},nGm=(e,t)=>{t=Array.from(t);let r=new JHr(e),n=(i,o,s)=>{let a=(d,f)=>{d?UQ.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let l=0,u=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(l+=f,l<512&&f)return UQ.default.read(i,u,l,u.length-l,c+l,p);if(c===0&&u[0]===31&&u[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let m=new bUe(u);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),l=0,UQ.default.read(i,u,0,512,c,p)};UQ.default.read(i,u,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",UQ.default.open(e.file,s,a);if(c||!l)return o(c);UQ.default.fstat(l,(u,p)=>{if(u)return UQ.default.close(l,()=>o(u));n(l,p.size,(d,f)=>{if(d)return o(d);let m=new VHr(e.file,{fd:l,start:f});r.pipe(m),m.on("error",o),m.on("close",i),oGm(r,t)})})};UQ.default.open(e.file,s,a)})},iGm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:CGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},oGm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:CGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},lGt=IGt(tGm,nGm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!R5m(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")}),gzv=IGt(lGt.syncFile,lGt.asyncFile,lGt.syncNoFile,lGt.asyncNoFile,(e,t=[])=>{lGt.validate?.(e,t),sGm(e)}),sGm=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 Ki,$Hr=h(()=>{"use strict";zn();Ki=class e{breadcrumbs=[];context;static STRING=$t.TypeReference.primitive({v1:"STRING",v2:$t.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=$t.TypeReference.container($t.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var xGo,AWl,yWl=h(()=>{"use strict";xGo=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,l=>{a.has(l.position)||(c--,a.add(l.position),this._path.length===1?this.resolveNode(l,`${o}.${c}`):(s.children.push({...l,path:c.toString()}),s.line=l.line,s.position=l.position,s.lineStart=l.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}}},AWl=xGo});var bWl,HE,Ire,SGo,CGt=h(()=>{"use strict";tr();Iy();bWl=require("fs/promises");Ko();yWl();(function(e){e.WARNING="warning",e.ERROR="error"})(HE||(HE={}));Ire=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new SGo({logger:t,relativePathToFile:be.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||HE.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===HE.ERROR?t++:(n.level===HE.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??HE.WARNING;if(!(n===HE.WARNING&&!t))switch(n){case HE.ERROR:if(this.logger.log(Un.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(Un.Debug,` - at location (${o})`)}break;case HE.WARNING:if(this.logger.log(Un.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(Un.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Un.Warn,` - resolution: ${r.resolution}`);break}}}},SGo=class{logger;relativePathToFile;map=new AWl;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,bWl.readFile)(this.relativePathToFile,"utf-8");Er.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Un.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)}}});function cGm(e){return"deprecated"in e&&e.deprecated===!0}async function lGm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Er.load(r)}}catch{return}}var Yb,EWl=h(()=>{"use strict";QK();mt();zn();Ko();xo();CGt();Uo();Yb=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;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=Tw({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=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ao(n.join("_"));return G6(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}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:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:HE.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 l=t.$ref.split("#"),u=l[0];if(n=l[1],!u)return{resolved:!1};if(s=u,o=await this.loadExternalDocument(u),r=o,r==null)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(l=>l.replace(/~1/g,"/"));for(let l of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let l=new Set;l.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,l,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=lGm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}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,l=s.substring(2).split("/").map(D0);for(let u of l){if(typeof c!="object"||c===null)return t;c=c[u]}if(c!=null){let u=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),u}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 $t.ObjectPropertyAccess.ReadOnly;if(i)return $t.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 vC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new vC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(cGm(t))return{status:eh.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 Hr.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"&&Yh(t)}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(gr(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 Vo,AR=h(()=>{"use strict";Vo=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]}}});var Pct,wGo=h(()=>{"use strict";AR();Pct=class extends Vo{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 eKr,IWl=h(()=>{"use strict";zn();AR();eKr=class extends Vo{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 eh.InDevelopment;case"PRE_RELEASE":return eh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return eh.GeneralAvailability;case"DEPRECATED":return eh.Deprecated;case"ALPHA":return eh.Alpha;case"BETA":return eh.Beta;case"PREVIEW":return eh.Preview;case"LEGACY":return eh.Legacy;default:return}}}});var Bct,TGo=h(()=>{"use strict";AR();Bct=class extends Vo{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 Dct,OGo=h(()=>{"use strict";AR();Dct=class extends Vo{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}}});var uGm,pGm,vWl,CWl=h(()=>{"use strict";nn();uGm=Xt.object({snake:Xt.string().optional(),camel:Xt.string().optional(),screamingSnake:Xt.string().optional(),pascal:Xt.string().optional()}),pGm=Xt.object({description:Xt.string().optional(),name:Xt.string().optional(),casing:uGm.optional()}),vWl=Xt.record(pGm)});var Rct,PGo=h(()=>{"use strict";AR();CWl();Rct=class extends Vo{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=vWl.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 IUe,xWl=h(()=>{"use strict";AR();IUe=class extends Vo{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 tKr,SWl=h(()=>{"use strict";AR();tKr=class extends Vo{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 rKr,wWl=h(()=>{"use strict";AR();rKr=class extends Vo{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 nKr,TWl=h(()=>{"use strict";AR();nKr=class extends Vo{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 iKr,OWl=h(()=>{"use strict";AR();iKr=class extends Vo{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 oKr,PWl=h(()=>{"use strict";AR();oKr=class extends Vo{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 sKr,BWl=h(()=>{"use strict";AR();sKr=class extends Vo{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}}});function fGm({isText:e,isAttribute:t}){return e?rQ.Text:t?rQ.Attribute:rQ.Element}function kWl(e){return typeof e=="object"&&e!=null}function aKr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function BGo(...e){return e.find(t=>t!=null)}var DWl,RWl,kct,Fct,cKr=h(()=>{"use strict";zn();AR();DWl="x-fern-xml-text",RWl="x-fern-xml-list-separator",kct=class extends Vo{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(kWl(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},Fct=class extends Vo{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=BGo(this.getExtensionValue(t),this.getExtensionValue(r)),i=BGo(aKr(t,DWl),aKr(r,DWl)),o=BGo(aKr(t,RWl),aKr(r,RWl)),s=kWl(n)?n:{};return{kind:fGm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var vC={};ne(vC,{AudienceExtension:()=>Pct,FernAvailabilityExtension:()=>eKr,FernDiscriminatedExtension:()=>Bct,FernDiscriminatorContextExtension:()=>Dct,FernEnumExtension:()=>Rct,FernIgnoreExtension:()=>IUe,FernOptionalExtension:()=>tKr,FernTypeExtension:()=>oKr,FernTypeNameExtension:()=>sKr,SdkGroupNameExtension:()=>rKr,SdkMethodNameExtension:()=>nKr,ServerFromOperationNameExtension:()=>iKr,XmlPropertyExtension:()=>Fct,XmlSchemaExtension:()=>kct});var DGo=h(()=>{"use strict";wGo();IWl();TGo();OGo();PGo();xWl();SWl();wWl();TWl();OWl();PWl();BWl();cKr()});function NWl(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>dw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(KD.Object);case"enum":return s(KD.Enum);case"union":return s(KD.Union);case"undiscriminatedUnion":return s(KD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=FWl(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||FWl(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:ic.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function FWl(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var jWl=h(()=>{"use strict";zn()});var tJ,zWl=h(()=>{"use strict";zn();sc();xo();$Hr();DGo();jWl();tJ=class extends Ki{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new M4e(n),this.ir={auth:{docs:void 0,requirement:$t.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:$t.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,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,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IUe({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 IUe({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},$5t(this.ir,{onWarning:a=>this.context.logger.warn(a)}),NWl(this.ir.types);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)),K5t({ir:i});let o=this.context.exampleGenerationArgs,s=d4o({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=Y5t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...Z5t(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,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,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let l=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),u=this.getOrCreatePackage({group:n});u!==this.ir.rootPackage&&u.docs==null&&o!=null&&(u.docs=o);let p=[...l].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];u.service==null&&(u.service=s??`service_${l.map(m=>ao(m)).join("/")}`),this.ir.services[u.service]==null&&(this.ir.services[u.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[u.service]?.endpoints.push(t);let f=this.ir.services[u.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ao(i?.join(".")),s=ao(r),a=this.context.namespace?`${ao(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,l=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?l.websocket==null&&(l.websocket=c):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,c,t),n!=null&&this.irGraph.markChannelForAudiences(u,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,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}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:zy(""),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,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ao(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}}});function vUe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function hGm(e){if(!vUe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>vUe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function gGm(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 MWl(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var dGm,QWl,mGm,Bw,DSe=h(()=>{"use strict";mt();Uo();dGm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,QWl=new WeakMap,mGm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Bw=class e extends Ki{MAX_DEPTH=12;EXAMPLE_STRING=Mo.STRING;EXAMPLE_NUMBER=Mo.DOUBLE;EXAMPLE_BOOLEAN=Mo.BOOLEAN;EXAMPLE_INTEGER=Mo.INT;EXAMPLE_DATE=Mo.DATE;EXAMPLE_DATE_TIME=Mo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;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;let l=QWl.get(r);l!=null?this.sharedState=l:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},QWl.set(r,this.sharedState))}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&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();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=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([b,I])=>{if(typeof I!="object")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:b,resolvedSchema:t}))return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let C=hGm(I),x=!(b in r)||!C&&r[b]==null||C&&r[b]===void 0,S=!o.includes(b);if(x&&S){if(this.example===void 0&&this.generateOptionalProperties){let P=this.maybeResolveSchemaExample(I),D=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:P,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:b,result:D.convert()}}return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let P=r[b],D=P!==void 0?P:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:D,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:b,result:O}}}),a=n?[]:(t.allOf??[]).map((b,I)=>{let C=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return C&&this.isConstraintOnlySchema(C)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...b,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:b})=>b.usedProvidedExample)||a.some(b=>b.usedProvidedExample)),l=Object.fromEntries(s.map(({key:b,result:I})=>[b,I.validExample]).filter(([b,I])=>I!==void 0));for(let b of a)if(typeof b.validExample=="object"&&b.validExample!==null){let I=b.validExample,C=Object.fromEntries(Object.entries(I).filter(([x,S])=>S!==void 0));for(let[x,S]of Object.entries(C))(!(x in l)||l[x]==null)&&(l[x]=S)}let u=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(b=>!p.has(b)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(b=>{let I=[...this.breadcrumbs,b].join("."),C={message:`Found unexpected property '${b}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,b]};u.push({key:b,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[C]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})});else{let b=t.additionalProperties;g.forEach(I=>{let x=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:b,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();u.push({key:I,result:x})})}for(let{key:b,result:I}of u)I.validExample!==void 0&&l[b]===void 0&&(l[b]=I.validExample);let A=s.every(b=>b.result.isValid)&&a.every(b=>b.isValid)&&u.every(({result:b})=>b.isValid);if(Object.keys(l).length===0){let b=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));b&&(l=b.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:l,errors:[...s.flatMap(({result:b})=>b.errors),...a.flatMap(b=>b.errors),...u.flatMap(({result:b})=>b.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 g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>gGm(m))){let m=d.findIndex(g=>MWl(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let b=MWl(A),C=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(C.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:C.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,g=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,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,l=c!==null,u=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:l,coerced:!1,usedProvidedExample:p,validExample:u,errors:l?[]: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(dGm);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:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,b]of Object.entries(g.mergedProperties))if(typeof b=="object"&&b!==null){let I=a[A];I!=null&&vUe(I)&&vUe(b)?a[A]={...I,...b}:a[A]=b}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&vUe(A)&&vUe(g)?a[m]={...A,...g}:a[m]=g}}}}let l={...o};for(let[p,d]of Object.entries(l)){let f=a[p];if(f==null||!vUe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(l[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in l||(l[p]=d);let u={mergedProperties:l,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,u),u}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>mGm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||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}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...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),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function LWl(e){return fC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Hr.primitive({v1:"BASE_64",v2:di.base64({})});case"BOOLEAN":return Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})});case"DATE":return Hr.primitive({v1:"DATE",v2:di.date({})});case"DATE_TIME":return Hr.primitive({v1:"DATE_TIME",v2:di.dateTime({})});case"DATE_TIME_RFC_2822":return Hr.primitive({v1:"DATE_TIME_RFC_2822",v2:di.dateTimeRfc2822({})});case"FLOAT":return Hr.primitive({v1:"FLOAT",v2:di.float({default:void 0,validation:void 0})});case"DOUBLE":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:void 0,validation:void 0})});case"UINT":return Hr.primitive({v1:"UINT",v2:di.uint({default:void 0,validation:void 0})});case"UINT_64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:void 0,validation:void 0})});case"INTEGER":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:void 0,validation:void 0})});case"LONG":return Hr.primitive({v1:"LONG",v2:di.long({default:void 0,validation:void 0})});case"STRING":return Hr.primitive({v1:"STRING",v2:di.string({default:void 0,validation:void 0})});case"UUID":return Hr.primitive({v1:"UUID",v2:di.uuid({})});case"BIG_INTEGER":return Hr.primitive({v1:"BIG_INTEGER",v2:di.bigInteger({default:void 0})});default:return}},unknown:()=>Hr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Hr.container(As.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Hr.container(As.list(t))},optional:t=>{if(t!=null)return Hr.container(As.optional(t))},nullable:t=>{if(t!=null)return Hr.container(As.nullable(t))},set:t=>{if(t!=null)return Hr.container(As.set(t))},literal:t=>Hr.container(As.literal(t._visit({string:r=>kE.string(r),boolean:r=>kE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var _Wl=h(()=>{"use strict";lo();zn();Bt()});var RSe,lKr=h(()=>{"use strict";zn();sc();Uo();RSe=class extends Ki{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:ic.enum({default:n!=null?r.find(i=>cr(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var uKr,UWl=h(()=>{"use strict";zn();Uo();Nct();CUe();uKr=class extends Ki{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=Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()}));return{type:ic.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Hr.container(As.map({keyType:Ki.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 c3(r.type,i),{type:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function qWl(e,t,r){let n=WWl(t,r),i={};for(let o of n)i=RGo(i,o);return vGm(i,e),i}function WWl(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let l of s)if("$ref"in l){if(t==null)continue;let u=l.$ref;if(n.has(u))continue;n.add(u);let p=t(l);p!=null&&c.push(p)}else c.push(l);i.push(...WWl(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function RGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||EGm.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]=IGm(o??{},i);continue}if(n==="items"){gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i;continue}if(VWl.includes(n)){gr(o)&&gr(i)?r[n]=HWl(o,i):r[n]=i;continue}if(GWl.includes(n)){r[n]=!!o||!!i;continue}if(yGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(bGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function IGm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i}return r}function HWl(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=HWl(o,i):r[n]=i}return r}function vGm(e,t){for(let r of AGm){let n=t[r];n!=null&&(e[r]=n)}for(let r of VWl){let n=t[r];n!=null&&(e[r]=n)}for(let r of GWl)t[r]===!0&&(e[r]=!0)}var AGm,VWl,GWl,yGm,bGm,EGm,KWl=h(()=>{"use strict";mt();AGm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],VWl=["example","default"],GWl=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],yGm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],bGm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],EGm=["allOf","oneOf","anyOf"]});var jct,kGo=h(()=>{"use strict";mt();zn();sc();cKr();Uo();Nct();jct=class extends Ki{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new kct({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:ic.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,l=n,u=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,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let D=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(D==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=D,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(R=>!this.schema.required?.includes(R))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let b=g.oneOf??g.anyOf;if(b!=null&&g.type==null&&g.properties==null){let D=new Set(r.map(R=>cr(R.name)));for(let[R,O]of b.entries()){let j=[...m,g.oneOf!=null?"oneOf":"anyOf",R.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:j}):O;if(Y==null)continue;let ee={};for(let[Te,pe]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(pe)&&"not"in pe||(ee[Te]=pe);let te=Object.keys(ee).filter(Te=>!D.has(Te));if(te.length===0)continue;let ce={};for(let Te of te){let pe=ee[Te];pe!=null&&(ce[Te]=pe,D.add(Te))}let{convertedProperties:le,inlinedTypesFromProperties:ae,referencedTypes:he,propertiesByAudience:xe}=xUe({properties:ce,required:[],breadcrumbs:j,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),l={...l,...ae},u={...u,...xe},he.forEach(Te=>{a.add(Te)})}continue}let I=g.properties??{};if(A){I={};for(let[D,R]of Object.entries(g.properties??{})){let O=p[D];O!=null&&!this.context.isReferenceObject(R)?I[D]={...O,...R}:I[D]=R}}let{convertedProperties:C,inlinedTypesFromProperties:x,referencedTypes:S,propertiesByAudience:P}=xUe({properties:I,required:[...this.schema.required??[],...g.required??[],...Hue(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...C),l={...l,...x},u={...u,...P},S.forEach(D=>{a.add(D)})}for(let d of Object.keys(l))a.add(d);return{type:ic.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(gs),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:u,referencedTypes:a,inlinedTypes:l,xmlEncoding:this.xmlEncoding}}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)}}});function CGm(e){return e.type==="union"&&e.types.length===0}function xGm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var SUe,FGo=h(()=>{"use strict";zn();TGo();OGo();PGo();Uo();Nct();lKr();pKr();CUe();SUe=class extends Ki{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 Bct({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!CGm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}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 l;if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});u.resolved&&(l=u.value)}else l=c;l!=null&&(l.enum!=null&&l.enum.length>1&&(l.type==="string"||l.type==null)?r=l:l.type==="string"&&l.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Rct({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new RSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}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}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?xGm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let l=s.$ref,u=l.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??u;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:l,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:u,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),b=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||b)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let C=new NT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let x=I&&p!=null&&!A;x&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=C.convert()}finally{x&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let P=this.context.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),D=d?.split("/").pop()??p,R=f?.title,O=f?.description,j=R??u??D;S.schema?.typeDeclaration!=null&&R!=null&&(S.schema.typeDeclaration.name.displayName=R),r.push({docs:O,discriminantValue:P,availability:S.availability,displayName:j,shape:eT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(D),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:j})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=xUe({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[u,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",u.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let u of Object.keys({...i,...a}))n.add(u);let l=new Dct({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:ic.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:l.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[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let b=this.getDiscriminatorKeyForRef(c);b!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:b,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let b=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=b.resolved?b.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let u=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new kSe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:u??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let b of Object.keys(m.inlinedTypes))r.add(b)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:ic.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}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=>!(typeof i=="object"&&i!==null&&"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 NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:ic.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 Hr.container(As.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 zct,NGo=h(()=>{"use strict";zn();Uo();zct=class extends Ki{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 Hr.container(As.literal(kE.string(t)));if(this.schema.format==="date-time-rfc-2822")return Hr.primitive({v1:ss.DateTimeRfc2822,v2:di.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Hr.primitive({v1:ss.Date,v2:di.date({})});if(this.schema.format==="date-time")return Hr.primitive({v1:ss.DateTime,v2:di.dateTime({})})}return Hr.primitive({v1:"STRING",v2:di.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"INTEGER",v2:di.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?Hr.container(As.literal(kE.boolean(t))):Hr.primitive({v1:"BOOLEAN",v2:di.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}}}});function wGm(e){let t=Hue(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var SGm,kSe,pKr=h(()=>{"use strict";mt();zn();Uo();Nct();_Wl();DSe();jGo();lKr();UWl();KWl();kGo();FGo();NGo();SGm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],kSe=class e extends Ki{static MAX_DISTRIBUTED_VARIANTS=64;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.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let l=this.tryConvertSiblingAnyOfConstraint();if(l!=null)return l;let u=this.tryConvertSiblingOneOfConstraint();if(u!=null)return u;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return c3(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new vC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new RSe({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 l;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;l=d}else l=c;let u=l.oneOf??l.anyOf;if(!this.context.isReferenceObject(c)&&u!=null&&l.type==null&&l.properties==null){let p={};for(let d of u){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(wGm(l))}if(i)return;let o=qWl(this.schema,n,c=>{let l=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(l!=null&&this.context.isReferenceObject(l)))return l}),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()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,l)=>c*l.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,l)=>l!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let l=this.getVariantTitle(c);return{...l!=null?{title:l}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new zct({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Qct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.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()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!Sze(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!wze(this.schema)||new vC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=Hue(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new SUe({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 uKr({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 SUe({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 jct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:Hr.unknown(),resolvedType:Hr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new vC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=LWl(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,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=[...SGm,...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 Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function OGm(e){return Object.keys(e).every(t=>TGm.has(t))}var NT,TGm,CUe=h(()=>{"use strict";zn();Uo();pKr();NT=class extends Ki{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??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}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??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>OGm(i))){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??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new kSe({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 Hr.container(As.optional(t))}wrapInNullable(t){return Hr.container(As.nullable(t))}},TGm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function xUe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},l=new Set;for(let[u,p]of Object.entries(e??{})){let d=[...r,"properties",u];if(typeof p!="object"){i.collect({message:`Schema property ${u} should be an object`,path:d});continue}let f=BGm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new NT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(u),wrapAsNullable:m}).convert();if(A!=null){let b=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:b?.default,xml:o?new Fct({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:b??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??PGm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{l.add(I)}),c3(A.type,l);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(a))l.add(u);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:l}}function PGm({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 l={};for(let[u,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${u}`,m=new Bw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();l[f]=g}return{userSpecifiedExamples:l,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Bw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function BGm(e,t,r){return r.isReferenceObject(t)?void 0:new vC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function c3(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":DGm(e.container,t);return}}function DGm(e,t){switch(e.type){case"list":c3(e.list,t);return;case"set":c3(e.set,t);return;case"optional":c3(e.optional,t);return;case"nullable":c3(e.nullable,t);return;case"map":c3(e.keyType,t),c3(e.valueType,t);return;case"literal":return}}var Nct=h(()=>{"use strict";DSe();CUe();cKr();Uo()});var Qct,jGo=h(()=>{"use strict";zn();Uo();Nct();CUe();Qct=class e extends Ki{static LIST_UNKNOWN=Hr.container(As.list(Hr.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 NT({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)})}),c3(r.type,n),{typeReference:Hr.container(As.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var zGo={};ne(zGo,{ArraySchemaConverter:()=>Qct,EnumSchemaConverter:()=>RSe,ObjectSchemaConverter:()=>jct,OneOfSchemaConverter:()=>SUe,PrimitiveSchemaConverter:()=>zct,SchemaConverter:()=>kSe,SchemaOrReferenceConverter:()=>NT});var QGo=h(()=>{"use strict";jGo();lKr();kGo();FGo();NGo();pKr();CUe()});var fKr,JWl=h(()=>{"use strict";xo();Uo();DSe();QGo();fKr=class extends Ki{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 NT({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,l])=>{if(this.context.isReferenceObject(l)){let u=this.context.resolveReference({reference:l,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return u.resolved?[c,u.value.value??u.value]:null}return[c,l.value??l]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new NT({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,l]of s){let u=this.context.resolveExampleWithValue(l),p=this.context.resolveExampleRecursively({example:l,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),u!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=u)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((l,u)=>{let p=`Example ${u+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ao(`${[...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}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}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 Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var dKr,YWl=h(()=>{"use strict";Uo();DSe();dKr=class extends Ki{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}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema: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:c,valueType:r??Ki.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??Ki.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Bw({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}}});var MGo={};ne(MGo,{AbstractMediaTypeObjectConverter:()=>fKr,AbstractParameterConverter:()=>dKr});var XWl=h(()=>{"use strict";JWl();YWl()});function Mct({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let l=RGm({context:e,header:c}),u=l?.schema,p=c.required===!0,d=b=>p?b:Hr.container(As.optional(b)),f=d(Ki.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(u!=null)if(m=e.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(Hr.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?di.integer({default:void 0,validation:void 0}):di.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})}));else{let b=new NT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:u,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(b!=null){f=b.type;for(let[I,C]of Object.entries(b.inlinedTypes))i[I]=C}}let A=kGm({context:e,breadcrumbs:o,header:c,headerName:s,schema:u,mediaTypeObject:l?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function RGm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&gp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function kGm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[l,u]of Object.entries(c??{})){let p=e.resolveExampleWithValue(u);p!=null&&(s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let l=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[l,u]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(u);if(p!=null){let d=e.generateUniqueName({prefix:l,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=xGt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=e.getExamplesFromSchema({schema:FGm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let u of l){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=xGt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(u)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=`${n}_example`;s.autogeneratedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function FGm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function xGt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Bw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var ZWl=h(()=>{"use strict";mt();zn();$Hr();DSe();CUe()});var mKr,$Wl=h(()=>{"use strict";AR();mKr=class extends Vo{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 e7l,NGm,l3,t7l=h(()=>{"use strict";mt();zn();wGo();$Wl();Uo();e7l="Base",NGm="x-fern-default-url",l3=class e extends Ki{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}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 l=e.getServerName({server:c,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((c,l,u)=>u.findIndex(p=>p.id===c.id)===l),s=[i,...o],a=this.servers.map(c=>{let l=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),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:l,name:this.context.casingsGenerator.generateName(l),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.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(gs);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.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 mKr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Pct({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?e7l:e.getServerExtensionName({server:this.servers[0],context:this.context})??e7l}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 l=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let u=this.extractFernDefaultUrlFromServer(c);u!=null&&(i[l]=u),o[l]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[l]=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[NGm];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 Tm={};ne(Tm,{AbstractConverters:()=>MGo,ExampleConverter:()=>Bw,SchemaConverters:()=>zGo,ServersConverter:()=>l3,convertResponseHeaders:()=>Mct});var LGo=h(()=>{"use strict";XWl();DSe();ZWl();QGo();t7l()});var SGt,r7l=h(()=>{"use strict";DSe();CGt();SGt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Bw({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 l=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid request example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:l.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let l=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid response example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:l.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}),l={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},u=this.validateEndpointExample({exampleToValidate:l}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=u.errors.length>0||u.warnings.length>0;!u.isValid||d||p?i.push({example:o,validationResult:u}):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||this.schemaHasPatternProperties(n))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}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...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),this.schemaHasPatternProperties(o,r)))return!0}}return!1}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,l]of Object.entries(t.paths)){if(!l)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let p of u){let d=l[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of b){n++;let C={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},x=this.validateEndpointExample({exampleToValidate:C});f.push(x),x.isValid?i++:(o++,I.source==="human"?s.push(x):I.source==="ai"&&a.push(x))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.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,l]of Object.entries(a.examples)){let u=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;u&&typeof u=="object"&&"value"in u&&i.push({name:c,source:"human",request:u.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let l=a.content?.["application/json"];if(l?.example!==void 0){let u=i.find(p=>p.request!==void 0&&p.response===void 0);u?(u.response=l.example,u.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:l.example,statusCode:s})}if(l?.examples)for(let[u,p]of Object.entries(l.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===u);f?(f.response=d.value,f.statusCode=s):i.push({name:u,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}}});function n7l({tags:e,errorCollector:t}){for(let r of e)if(Lct.test(r.name)){let n=[...r.name].filter(i=>Lct.test(i));t.collect({level:HE.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(Lct,"").trim()}".`})}}function i7l({description:e,path:t,errorCollector:r}){jGm.test(e)&&r.collect({level:HE.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 _Go({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");n7l({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 l=c;if(typeof l.description=="string"&&i7l({description:l.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(l.tags)&&!Array.isArray(e.tags)){for(let u of l.tags)if(typeof u=="string"&&!n.has(u)&&Lct.test(u)){n.add(u);let p=[...u].filter(d=>Lct.test(d));t.collect({level:HE.ERROR,message:`Tag name "${u}" 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 "${u}" to "${u.replace(Lct,"").trim()}".`})}}}}}}var Lct,jGm,o7l=h(()=>{"use strict";CGt();Lct=new RegExp("[^\\x00-\\x7F]"),jGm=/(?:^|\n)\s*---\s*(?:\n|$)/});var hKr,zGm,s7l=h(()=>{"use strict";hKr={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"},zGm=new Set(Object.values(hKr))});function UGo(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var a7l=h(()=>{"use strict"});var Uo=h(()=>{"use strict";$Hr();EWl();AR();zWl();LGo();LGo();CGt();r7l();DGo();o7l();s7l();a7l()});var QGm,MGm,c7l,l7l=h(()=>{"use strict";nn();QGm=Xt.object({type:Xt.string(),channelId:Xt.string().optional(),messageId:Xt.string(),value:Xt.any()}),MGm=Xt.object({summary:Xt.string().optional(),description:Xt.string().optional(),"query-parameters":Xt.record(Xt.string()).optional(),headers:Xt.record(Xt.string()).optional(),messages:Xt.array(QGm)}),c7l=Xt.array(MGm)});var gKr,u7l=h(()=>{"use strict";Uo();l7l();gKr=class extends Vo{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=c7l.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 _ct,VGo=h(()=>{"use strict";Uo();u7l();_ct=class extends Ki{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 gKr({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 LGm,rJ,wGt=h(()=>{"use strict";zn();Uo();LGm="x-fern-server-name",rJ=class e extends Ki{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,baseUrlEnvVar:void 0,environments:DE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[LGm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var FSe,GGo=h(()=>{"use strict";Uo();FSe=class extends Tm.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 vC.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 Tm.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 AKr,p7l=h(()=>{"use strict";Uo();AKr=class extends Vo{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 NSe,qGo=h(()=>{"use strict";Uo();NSe=class extends Vo{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 jSe,WGo=h(()=>{"use strict";Uo();jSe=class extends Vo{node;key="x-fern-explorer";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){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var yKr,f7l=h(()=>{"use strict";Uo();yKr=class extends Vo{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 bKr,d7l=h(()=>{"use strict";zn();sc();Uo();xo();VGo();wGt();GGo();p7l();qGo();WGo();f7l();bKr=class extends _ct{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 NSe({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 u=new AKr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(u??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=zy(p),m=ao(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,b=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),C=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??b;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"})},apiPlayground:C},audiences:g,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=Qze(ao(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();u!=null&&u.schema!=null&&(i=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let l=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(l!=null){let p=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:l,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let l=i,u=Hr.named({fernFilepath:t.createFernFilepath(),name:l.typeDeclaration.name.name,typeId:l.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=$P.reference({bodyType:u,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new NSe({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 FSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).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 FSe({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},parameterNamePrefix:this.channelPath}).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 rJ.getServerName(t,n)}return t}getOperationMethodName(t){return new yKr({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 FSe({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},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var EKr,m7l=h(()=>{"use strict";wGt();EKr=class extends rJ{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 HGo,h7l,KGo,IKr,g7l=h(()=>{"use strict";zn();sc();Bt();VGo();wGt();GGo();qGo();WGo();HGo="$message.",h7l="#/channels/",KGo="#/servers/",IKr=class extends _ct{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 NSe({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((A,[b,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[b]=I)}catch{}return A},{}),a=[];for(let[A,b]of Object.entries(s)){let C=new NSe({breadcrumbs:[...this.breadcrumbs,A],node:b,context:this.context}).convert()??A;for(let x of b.messages){let S=this.context.convertReferenceToTypeReference({reference:x});if(S.ok){let P=this.resolveMessageDocs(x)??b.description,D=$P.reference({bodyType:S.reference,docs:P});a.push({type:A,displayName:C,origin:b.action==="send"?"client":"server",body:D,availability:this.context.getAvailability({node:b,breadcrumbs:this.breadcrumbs}),docs:P,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),l=this.transformToValidPath(this.channel.address??this.channelPath),u=zy(l),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:u,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:l,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},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(KGo,""),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:l}=a,p=new FSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:l,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(HGo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${HGo} prefix`,path:this.breadcrumbs});return}let i=r.substring(HGo.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}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(KGo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(KGo.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 rJ.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 rJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(h7l))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(h7l.length)}}});var vKr,A7l=h(()=>{"use strict";wGt();vKr=class extends rJ{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 TGt,y7l=h(()=>{"use strict";zn();sc();Uo();d7l();m7l();g7l();A7l();TGt=class extends tJ{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 l=`${r}_${i}`;this.convertSchema({id:l,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 Tm.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 vKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new EKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=G5t({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 kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return kp.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,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return kp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:Ki.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new vC.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 IKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new bKr({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 OGt,b7l=h(()=>{"use strict";zn();Uo();OGt=class extends Yb{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 l=a[1],u=a[2];return o=`${l}_${u}`,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:Hr.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:Hr.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:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var E7l=h(()=>{"use strict";y7l();b7l()});function UGm(e){let t=new Set,r,n=new RegExp(_Gm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var _Gm,CKr,I7l=h(()=>{"use strict";Uo();_Gm=/\{([^}]+)\}/g,CKr=class extends Vo{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")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=UGm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let l=o[c];if(l==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof l!="object"||Array.isArray(l)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let u=l,p=typeof u.type=="string"?u.type:"string",d=typeof u.docs=="string"?u.docs:void 0;s.push({name:c,type:p,default:u.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var xKr,v7l=h(()=>{"use strict";Uo();xKr=class extends Vo{document;key="x-fern-base-url-env";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"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var SKr,C7l=h(()=>{"use strict";Uo();SKr=class extends Vo{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 VGm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var wKr,x7l=h(()=>{"use strict";Uo();wKr=class extends Vo{document;key="x-fern-global-parameters";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)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:VGm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function GGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function S7l({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:Ki.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:Ki.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:GGm(i.default),defaultValue:i.default})}return r}var w7l=h(()=>{"use strict";zn();Uo()});function qGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function T7l({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ki.OPTIONAL_STRING:Ki.STRING,env:r.env,v2Examples:r.optional?void 0:WGm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:qGm(r["x-fern-default"]),defaultValue:void 0}))}function WGm({header:e,context:t}){let r=new Bw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var O7l=h(()=>{"use strict";zn();Uo()});function HGm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return $t.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return $t.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return $t.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function KGm(e,t,r){switch(e){case void 0:case"body":return $t.GlobalParameterLocation.Body;case"query":return $t.GlobalParameterLocation.Query;case"header":return $t.GlobalParameterLocation.Header;case"path":return $t.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),$t.GlobalParameterLocation.Body}}function JGm(e,t,r){switch(e){case void 0:return;case"explicit":return $t.GlobalParameterApplyMode.Explicit;case"auto":return $t.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function YGm(e,t){let r=XGm(e);return t===!0?$t.TypeReference.container($t.ContainerType.optional(r)):r}function XGm(e){switch(e){case"boolean":return $t.TypeReference.primitive({v1:"BOOLEAN",v2:$t.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return $t.TypeReference.primitive({v1:"INTEGER",v2:$t.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return $t.TypeReference.primitive({v1:"DOUBLE",v2:$t.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return Ki.STRING}}function ZGm(e){return e.target!=null?e.target:e.name}function P7l({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=KGm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:ZGm(n),valueType:YGm(n.type,n.optional),env:n.env,clientDefault:HGm(n.default,n.type,o,t),optional:n.optional,apply:JGm(n.apply,[...o,"apply"],t),docs:n.docs}})}var B7l=h(()=>{"use strict";zn();Uo()});var TKr,D7l=h(()=>{"use strict";mt();Uo();TKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&gp.parse(t)?.isJSON())return r.schema}}}});function e9m({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return $Gm[e.contentType]}}var OKr,$Gm,R7l=h(()=>{"use strict";mt();zn();sc();Uo();OKr=class extends Tm.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:l,queryParameters:u}){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=l,this.queryParameters=u??[]}get bodyRequired(){return this.required===!1?!1:void 0}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(gp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=gp.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=gp.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:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:md.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}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,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 l=this.context.resolveExampleWithValue(c),u=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(u)){let d=u.summary;s.has(d)||(p=d)}s.add(p),l!=null&&(i.userSpecifiedExamples[p]=l)}return{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:Hr.unknown(),required:this.bodyRequired,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:md.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[cr(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:md.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?kx.file(eQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.file(eQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.bodyProperty({...t,contentType:n?.contentType??r,style:e9m({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)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({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}})}}buildStreamConditionRequestBody({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 l=c.schema?.typeDeclaration.shape;return l?.type==="object"?{requestBody:md.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:l.extendedProperties,extends:l.extends,properties:l.properties,extraProperties:l.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:md.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,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=>cr(n.name).toLowerCase()));return t.some(n=>r.has(cr(n.name).toLowerCase()))}},$Gm={"application/json":"json"}});function n9m(e){return e?.header!=null}var t9m,r9m,Uct,JGo=h(()=>{"use strict";mt();zn();sc();Uo();xo();D7l();R7l();t9m=/{([^}]+)}/g,r9m=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Uct=class extends Ki{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return gm.Get;case"post":return gm.Post;case"put":return gm.Put;case"delete":return gm.Delete;case"patch":return gm.Patch;case"head":return gm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let l=new TKr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(l!=null)switch(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type){case"path":r.push(l.parameter);break;case"query":n.push(l.parameter);break;case"header":{let u=jr(l.parameter.name),p=cr(l.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(n9m(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!r9m.has(u.toLowerCase())&&!d&&i.push(l.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll(t9m)].map(i=>i[1]).filter(i=>!t.some(o=>jr(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:Ki.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,l]of Object.entries(s.content)){let p=new OKr({context:this.context,breadcrumbs:t,contentType:c,mediaType:l,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,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new vC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new vC.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?ao(this.operation.summary):ao(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ao(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=D7(t,n),o=D7(r,n);return qv(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ao(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Tm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Vct,YGo=h(()=>{"use strict";zn();JGo();Vct=class extends Uct{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}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 l=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,u,p;if(c.type==="inlinedRequestBody")u=tT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=tT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=tT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:l,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:p,responses:d.length>0?d: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 k7l,F7l=h(()=>{"use strict";k7l=["get","post","put","delete","patch","head"]});var PKr,N7l=h(()=>{"use strict";Uo();PKr=class extends Vo{operation;key="x-fern-global-parameter";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;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var BKr,j7l=h(()=>{"use strict";Uo();BKr=class extends Vo{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}}}});var i9m,o9m,s9m,a9m,XGo,z7l=h(()=>{"use strict";nn();i9m=Xt.object({cursor:Xt.string(),next_cursor:Xt.string(),results:Xt.string()}),o9m=Xt.object({offset:Xt.string(),results:Xt.string(),step:Xt.string().optional(),"has-next-page":Xt.string().optional()}),s9m=Xt.object({next_uri:Xt.string(),results:Xt.string()}),a9m=Xt.object({next_path:Xt.string(),results:Xt.string()}),XGo=Xt.union([Xt.boolean(),i9m,o9m,s9m,a9m])});var ZGo,zSe,DKr,Q7l=h(()=>{"use strict";Uo();z7l();ZGo="$request.",zSe="$response.",DKr=class extends Vo{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=XGo.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=XGo.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:Yb.maybeTrimPrefix(r.cursor,ZGo),nextCursor:Yb.maybeTrimPrefix(r.next_cursor,zSe),results:Yb.maybeTrimPrefix(r.results,zSe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:Yb.maybeTrimPrefix(n.next_uri,zSe),results:Yb.maybeTrimPrefix(n.results,zSe)};let i=t;if("next_path"in i)return{type:"path",nextPath:Yb.maybeTrimPrefix(i.next_path,zSe),results:Yb.maybeTrimPrefix(i.results,zSe)};let o=t;return{type:"offset",offset:Yb.maybeTrimPrefix(o.offset,ZGo),results:Yb.maybeTrimPrefix(o.results,zSe),step:o.step!=null?Yb.maybeTrimPrefix(o.step,ZGo):void 0,hasNextPage:o["has-next-page"]!=null?Yb.maybeTrimPrefix(o["has-next-page"],zSe):void 0}}}});function $Go(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var c9m,l9m,u9m,RKr,M7l=h(()=>{"use strict";Uo();nn();c9m="$request.",l9m=Xt.object({"stream-condition":Xt.string().optional(),format:Xt.enum(["sse","json"]).optional(),"stream-description":Xt.string().optional(),"stream-request-name":Xt.string().optional(),"response-stream":Xt.any(),response:Xt.any(),terminator:Xt.string().optional(),resumable:Xt.boolean().optional()}),u9m=Xt.union([Xt.boolean(),l9m]),RKr=class extends Vo{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=u9m.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,resumable:!1}:void 0;let n=r.data.resumable??$Go(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};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:Yb.maybeTrimPrefix(r.data["stream-condition"],c9m),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var kKr,L7l=h(()=>{"use strict";Uo();kKr=class extends Vo{operation;key="x-fern-subtitle";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!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var FKr,_7l=h(()=>{"use strict";Uo();FKr=class extends Vo{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}}}});function p9m(e){return oi(e)&&typeof e.$ref=="string"}function f9m(e,t){if(e!=null){if(typeof e=="string")return e;if(p9m(e)){let r=(0,U7l.resolve)(t??process.cwd(),e.$ref);if((0,jKr.existsSync)(r))try{return(0,jKr.readFileSync)(r,"utf-8")}catch{return}}}}var jKr,U7l,NKr,V7l=h(()=>{"use strict";mt();Uo();jKr=require("fs"),U7l=require("path");NKr=class extends Vo{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=oi(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(!oi(c))continue;let l=c,u=l.lang,p=l.label,d=l.source;if(typeof u!="string")continue;let f=f9m(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:u,language:u,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function d9m(e){return oi(e)&&typeof e.$ref=="string"}function m9m(e,t){if(e!=null){if(typeof e=="string")return e;if(d9m(e)){let r=(0,G7l.resolve)(t??process.cwd(),e.$ref);if((0,QKr.existsSync)(r))try{return(0,QKr.readFileSync)(r,"utf-8")}catch{return}}}}function h9m(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=m9m(n.code,t);o!=null&&r.push({...n,code:o})}return r}var QKr,G7l,zKr,q7l=h(()=>{"use strict";mt();lo();Uo();QKr=require("fs"),G7l=require("path");zKr=class extends Vo{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(!oi(o))return o;let a=o["code-samples"];if(a!=null){let c=h9m(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=Qd.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 PGt,W7l=h(()=>{"use strict";Uo();PGt=class extends Vo{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}}}});var BGt,H7l=h(()=>{"use strict";mt();zn();Uo();BGt=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;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(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}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,contentType:o})}}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:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:kl.streaming(rv.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:kl.streaming(rv.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,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:kl.streaming(rv.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:kl.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:kl.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:kl.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:gp.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}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 gp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var MKr,K7l=h(()=>{"use strict";mt();zn();Uo();MKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;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)return this.constructSchemalessErrorOutput();let t=Object.keys(this.responseError.content).filter(n=>n.includes("json"));if(t.length===0)return this.constructSchemalessErrorOutput();let 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:G6(`${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})}}constructSchemalessErrorOutput(){let t=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(t==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let r=this.getErrorIdFromErrorName(t),n={error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:r},docs:this.responseError.description},i=this.convertResponseHeaders();return{error:n,errorType:Hr.unknown(),displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:{},headers:i.headers}}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,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}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}),l=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(l),a!=null&&(i[l]=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 hKr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?G6(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var LKr,J7l=h(()=>{"use strict";lo();zn();sc();W5();Uo();xo();V7l();q7l();W7l();H7l();K7l();JGo();LKr=class e extends Uct{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:l,idToAuthScheme:u,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=l,this.idToAuthScheme=u,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=u?.[0]?.requestBody,d=u?.[0]?.streamRequestBody,f=u?.[0]?.inlinedPropertiesByAudience,m={requestBodies:u?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,b=g?.streamResponse,I=g!=null?g.errors:[],C={},x=I.map(ue=>ue.error),S=zy(this.path),P=this.context.perSpecBasePath,D=this.getEndpointBaseUrl(),R=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:D});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&u!=null&&u.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:u,httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let j=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(j));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,je=Pe.error.errorId,_e=ue.examples;C[je]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let ee=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ce=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),he=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ce,xe={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:D,v2BaseUrls:R,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(je=>cr(je.name)===cr(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:x,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:P!=null?zy(P):void 0,fullPath:P!=null?zy(`${P}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:HD.openapi(),audiences:ee,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:he},Te=this.context.namespace!=null?[this.context.namespace]:[],pe=r?.map(ue=>ao(ue));return Te.push(...pe??[]),{audiences:ee,group:r,groupDisplayName:i,groupDescription:o,errors:C,endpoint:{...xe,id:`endpoint_${Te.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:b!=null&&b.body!=null?{...xe,id:`endpoint_${Te.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:b,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:b.body,docs:b.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:l}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,l]of Object.entries(this.operation.responses)){let u=/^[45]XX$/i.test(c),p,d=!1;if(u)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:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new BGt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new MKr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:u?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let l=new BGt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:l.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:l.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 l=c.value.responseBodyType;(l.type!=="container"||l.container.type!=="optional")&&(o.response={...o.response,body:kl.json(K0.response({...c.value,responseBodyType:Hr.container(As.optional(l))}))})}}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.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():UGo(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&rnt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())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:Ki.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue: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 zKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new NKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],l=o.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?o:[...o,...a];return l.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}),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[l,u]of c){let p=this.context.resolveExampleWithValue(u);p!=null&&(s[l]={displayName:void 0,contentType: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:$t.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,l=c.contentType,u=c.v2Examples;if(u==null)continue;let p=u.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=l!=null?s.get(l):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&l!=null?`${f} (${l})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:l??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,l]of c){let u=this.context.resolveExampleWithValue(l);if(u!=null){t.set(s,{docs:void 0,statusCode:i,body:$t.V2HttpEndpointResponseBody.json(u)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(l=>!(l.response!=null&&"stream"in l.response)),s=i.filter(l=>l.response!=null&&"stream"in l.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,contentType: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 $t.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return $t.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new vC.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 "${un.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 l3.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return l3.getServerName({server:a,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],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ao(r)===ao(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ao(r)===ao(n))return this.context.getDescriptionForTag(r)}}});var e9o,_Kr,Y7l=h(()=>{"use strict";Uo();e9o=Ae(zUt(),1);F7l();N7l();j7l();Q7l();M7l();L7l();_7l();J7l();YGo();_Kr=class extends Ki{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of k7l){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 l=new RKr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();l==null&&this.operationHasTextEventStreamResponse(o)&&(l={type:"stream",format:"sse",terminator:void 0,resumable:$Go(this.context.spec)??!1});let u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:l});u!=null&&(t.push(u),Object.assign(n,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new FKr({breadcrumbs:n,operation:t,context:i}).convert()?new Vct({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).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 DKr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new BKr({breadcrumbs:n,operation:t,context:this.context}).convert(),u=new kKr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new PKr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new LKr({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:u,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var UKr,X7l=h(()=>{"use strict";zn();Uo();UKr=class extends Ki{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(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return kp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return kp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:Ki.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function g9m(e){if(e!=null){if(typeof e=="string")return kE.string(e);if(typeof e=="boolean")return kE.boolean(e)}}var Z7l,DGt,$7l=h(()=>{"use strict";mt();lo();zn();sc();W5();Uo();Z7l=Ae(zUt(),1);I7l();v7l();C7l();x7l();w7l();O7l();B7l();YGo();Y7l();X7l();DGt=class extends tJ{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}),this.context.spec=QUt({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),_Go({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),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=S7l({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new SKr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=T7l({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new wKr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=P7l({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new CKr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Xh(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=zy(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:Ki.STRING,docs:n.docs,location:$t.PathParameterLocation.Root,variable:void 0,clientDefault:g9m(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=jUt({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=G5t({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}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 UKr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new xKr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=q5t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.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 Vct({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:Z7l.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new _Kr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let l of c.servers)this.shouldAddServerToCollectedServers({server:l,currentServers:t})&&t.push(l);if(c.errors)for(let[l,u]of Object.entries(c.errors))r[l]=u}for(let c of a.webhooks){let l=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:l.join("."),group:l,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&rnt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],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!=null&&i.security.length>0&&delete i.security}}}}});var VKr,eHl=h(()=>{"use strict";Uo();VKr=class extends Vo{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 wUe,tHl=h(()=>{"use strict";zn();sc();Uo();eHl();wUe=class extends Yb{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;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 l;if(o.includes("/")){let p=new Tm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(l={[o]:p.convertedSchema})}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:l}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>cr(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new VKr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function r9o({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=Ode(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>y9m({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function y9m({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=rHl({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],l=n["response-properties"],u=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-id"],"client_id")}),p=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-secret"],"client_secret")}),d=Gct({ir:e,endpoint:o,wireValue:nJ(l?.["access-token"],"access_token")});if(!(u==null||p==null||d==null))return kp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:qD.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:u,clientSecret:p,scopes:void 0,customProperties:I9m({ir:e,endpoint:o,excludeWireValues:[nJ(c?.["client-id"],"client_id"),nJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?b9m({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function b9m({ir:e,refreshTokenConfig:t}){let r=rHl({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=t9o({ir:e,endpoint:n,wireValue:nJ(s?.["refresh-token"],"refresh_token")}),l=Gct({ir:e,endpoint:n,wireValue:nJ(a?.["access-token"],"access_token")});if(!(c==null||l==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:l,expiresIn:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["refresh-token"],"refresh_token")})}}}function rHl({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=A9m[r[0]?.toUpperCase()??""],i=Xh(r[1]);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(E9m(a.fullPath)===i){let l=Object.entries(e.subpackages).find(([,u])=>u.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:l}}}}function E9m(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Xh(t)}function nJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function nHl(e,t){return e.find(r=>cr(r.name)===t)}function n9o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function t9o({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?nHl(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:XP.body({...i})}}function I9m({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(cr(s.name))).map(s=>({propertyPath:void 0,property:XP.body({...s})}));return o.length>0?o:void 0}function Gct({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=n9o(e,n.typeId),o=i!=null?nHl(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var A9m,iHl=h(()=>{"use strict";mt();lo();zn();sc();A9m={GET:gm.Get,POST:gm.Post,PUT:gm.Put,PATCH:gm.Patch,DELETE:gm.Delete}});var i9o=h(()=>{"use strict";$7l();tHl();iHl()});var qct,o9o=h(()=>{"use strict";Uo();qct=class extends Vo{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}}}});var v9m,C9m,x9m,GKr,oHl=h(()=>{"use strict";mt();Uo();nn();v9m=Xt.object({description:Xt.string().optional(),required:Xt.boolean().optional(),deprecated:Xt.boolean().optional(),allowEmptyValue:Xt.boolean().optional(),style:Xt.string().optional(),explode:Xt.boolean().optional(),allowReserved:Xt.boolean().optional(),schema:Xt.any().optional(),example:Xt.any().optional(),examples:Xt.record(Xt.string(),Xt.any()).optional(),content:Xt.record(Xt.string(),Xt.any()).optional()}),C9m=v9m.extend({name:Xt.string(),in:Xt.string()}),x9m=Xt.array(C9m),GKr=class extends Vo{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 x9m.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${rn(r)}`,path:this.breadcrumbs});return}}}});var qKr,sHl=h(()=>{"use strict";zn();sc();Uo();o9o();qKr=class extends Ki{method;pathParameters;queryParameters;headers;topLevelServers;globalApiPlayground;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[],globalApiPlayground:c}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a,this.globalApiPlayground=c}convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${jr(l.name)}}`;let n=zy(r),i=[];for(let[l,u]of this.method.params.entries()){let p;if(this.context.isReferenceObject(u)){let g=this.context.resolveReference({reference:u});if(g.resolved)p=g.value;else continue}else p=u;let d=[this.method.name,"Param",p.name].join("_"),m=new Tm.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:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,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 l=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),p=[this.method.name,"Result"].join("_"),d=u.convert();d!=null&&(o={docs:l.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,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?md.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:kl.json(K0.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(r)},transport:void 0,availability:void 0,source:HD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:this.convertApiPlayground(),responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertApiPlayground(){return new qct({breadcrumbs:[...this.breadcrumbs,this.method.name],document:this.method,context:this.context}).convert()??this.globalApiPlayground}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return $t.OpenRpcParamStructure.ByName;case"by-position":return $t.OpenRpcParamStructure.ByPosition;case"either":return $t.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}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 l3.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[jr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let u=this.context.resolveReference({reference:o});if(u.resolved)s=u.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let u=this.context.resolveReference({reference:s.result});u.resolved&&(a=u.value)}else a=s.result;let c=s.name??`Example ${i+1}`,l=[];if(s.params&&Array.isArray(s.params)){l=[];for(let u of s.params)if(this.context.isReferenceObject(u)){let p=this.context.resolveReference({reference:u});if(p.resolved)l.push(p.value);else continue}else l.push(u)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(l)},response:{docs:void 0,statusCode:void 0,body:a?.value!==void 0?$t.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var WKr,aHl=h(()=>{"use strict";Uo();WKr=class extends Tm.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 Tm.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 RGt,cHl=h(()=>{"use strict";Uo();o9o();oHl();sHl();aHl();RGt=class extends tJ{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 l3({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 Tm.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 GKr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[l,u]of n.entries()){let d=new WKr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${l}]`],parameter:u}).convert();if(d!=null)switch(d.type){case"path":{i.push(d.parameter);break}case"query":{o.push(d.parameter);break}case"header":{s.push(d.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),c=new qct({breadcrumbs:[],document:this.context.spec,context:this.context}).convert();for(let l of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:["methods"]});if(u==null)continue;let d=new qKr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers,globalApiPlayground:c}).convert();if(d!=null&&(this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(d.inlinedTypes),d.servers))for(let f of d.servers)this.shouldAddServerToCollectedServers({server:f,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(f))}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 kGt,lHl=h(()=>{"use strict";zn();Uo();kGt=class extends Yb{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=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:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var uHl=h(()=>{"use strict";cHl();lHl()});var pHl,fHl=h(()=>{"use strict";pHl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function S9m(e){return typeof e=="string"&&pHl.test(e)}var s9o,dHl=h(()=>{"use strict";fHl();s9o=S9m});function mHl(e,t=0){return(EB[e[t+0]]+EB[e[t+1]]+EB[e[t+2]]+EB[e[t+3]]+"-"+EB[e[t+4]]+EB[e[t+5]]+"-"+EB[e[t+6]]+EB[e[t+7]]+"-"+EB[e[t+8]]+EB[e[t+9]]+"-"+EB[e[t+10]]+EB[e[t+11]]+EB[e[t+12]]+EB[e[t+13]]+EB[e[t+14]]+EB[e[t+15]]).toLowerCase()}var EB,hHl=h(()=>{"use strict";EB=[];for(let e=0;e<256;++e)EB.push((e+256).toString(16).slice(1))});function a9o(){return crypto.getRandomValues(w9m)}var w9m,gHl=h(()=>{"use strict";w9m=new Uint8Array(16)});function T9m(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():O9m(e,t,r)}function O9m(e,t,r){e=e||{};let n=e.random??e.rng?.()??a9o();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return mHl(n)}var Dw,AHl=h(()=>{"use strict";gHl();hHl();Dw=T9m});var TUe=h(()=>{"use strict";AHl();dHl()});async function Wct({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,yHl.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Er.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return QX({data:t,overrides:i,allowNullKeys:n})}var yHl,HKr=h(()=>{"use strict";mt();Bt();yHl=require("fs/promises");Ko()});async function c9o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,bHl.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Er.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await Wct({absoluteFilePathToOverrides:a,context:e,data:s});return s}var bHl,EHl=h(()=>{"use strict";bHl=require("fs/promises");Ko();HKr()});async function l9o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await P9m(Zt.of(r.schema)):r.schema;return{document:Bjo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function P9m(e){let t=(await(0,IHl.readFile)(e)).toString(),r=Er.load(t);if(!gr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var IHl,vHl=h(()=>{"use strict";vc();mt();tr();Bt();IHl=require("fs/promises");Ko()});var xHl=E((UUv,CHl)=>{"use strict";function B9m(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}CHl.exports=B9m()});var THl=E((VUv,wHl)=>{"use strict";var SHl=xHl();wHl.exports=function(t,r){if(t){r.then(function(n){SHl(function(){t(null,n)})},function(n){SHl(function(){t(n)})});return}else return r}});var p9o=E((GUv,PHl)=>{"use strict";var u9o=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},KKr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function OHl(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new KKr(t,r,e);throw Error.captureStackTrace(n,OHl),n}}PHl.exports={ERR_INVALID_ARG_TYPE:KKr,assertIsObject:OHl,DebounceTimers:u9o}});var RHl=E((qUv,DHl)=>{"use strict";var{assertIsObject:BHl}=p9o();function D9m(e){return BHl(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,BHl(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function R9m(e,t){e=D9m.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}DHl.exports={initializeTLSOptions:R9m}});var ZKr=E((HUv,jHl)=>{"use strict";var{URL:JKr}=require("url"),{EventEmitter:FHl}=require("events"),YKr=require("util")._extend,{DebounceTimers:k9m,assertIsObject:kHl,ERR_INVALID_ARG_TYPE:WUv}=p9o(),{initializeTLSOptions:F9m}=RHl(),FGt=require("http"),f9o=require("https"),{Stream:N9m}=require("stream");function XKr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var _me=[];XKr(_me,FGt.ClientRequest);XKr(_me,FGt.OutgoingMessage);XKr(_me,FHl);XKr(_me,N9m);var j9m=["httpVersionMajor","httpVersionMinor","httpVersion"],z9m=["host","connection"],QSe=Symbol("stubs");function NGt(){this.http2Mimic=!0,this[QSe]=[];for(var e=0;e<_me.length;e++){let l=_me[e];NGt.prototype[l]||(this[l]=function(){return this.genericStubber(l,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof jGt;var s,a;if(o){let l=arguments[0];l.method&&(s=l.method),l.protocol&&(a=l.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=d9o(new JKr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=YKr(d9o(new JKr(n)),t):t=YKr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}NGt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?LSe.globalManager:_Se.globalManager:MSe.globalManager},genericStubber(e,t){return this[QSe]?(this[QSe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[QSe])this[QSe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<_me.length;t++){let n=_me[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[QSe].length;n++){var r=this[QSe][n];e[r[0]](...r[1])}this[QSe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(_me),i=Object.keys(this),o=[].concat(j9m);i.forEach(function(l){n.indexOf(l)==-1&&o.indexOf(l)==-1&&o.push(l)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],l=s[c],u;l||(u=!0),l&&(l.writable||l)&&(u=!0),u&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var MSe=class e extends FHl{constructor(t){super(),this.httpsAgent=f9o.globalAgent,this.httpAgent=FGt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new k9m(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new jGt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new NGt(i)}get(){var t=new jGt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var l={createConnection(){return o}};if(c=="h2"&&this.http2Support){var u=this.http2.connect(r,l);this.setHttp2Client(t,u)}else this.cachedHTTP1Result[t]=Date.now();n(null,l),this.emit(i,l)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof JKr&&(n=d9o(n));let s=YKr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(u){this.emit("http1.response",u)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=YKr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{z9m.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let l,u=0;c.on("data",function(f){u+=f.length,u>=l&&s.unpauseAndTime(t)}),r.take(c);function p(d){l=parseInt(d["content-length"]),l<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),kHl(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new JKr(t)),kHl(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,F9m.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function d9o(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var jGt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},LSe=class extends MSe{constructor(){super(...arguments),this.Agent=f9o.Agent,this.globalAgent=f9o.globalAgent,this.enforceProtocol="https:"}},Q9m=new LSe;LSe.globalManager=Q9m;LSe.Manager=LSe;var _Se=class extends MSe{constructor(){super(...arguments),this.Agent=FGt.Agent,this.globalAgent=FGt.globalAgent,this.enforceProtocol="http:"}},M9m=new _Se;_Se.globalManager=M9m;_Se.Manager=_Se;var NHl=new MSe;NHl.enforceProtocol="detect";MSe.globalManager=NHl;jHl.exports={HttpRequest:_Se,HttpsRequest:LSe,HTTP2OutgoingMessage:NGt,ClientRequest:NGt,HttpRequestManager:MSe}});var QHl=E((KUv,zHl)=>{"use strict";var{HttpRequest:L9m,ClientRequest:_9m}=ZKr(),zGt=L9m.globalManager,U9m=zGt.request.bind(zGt),V9m=zGt.get.bind(zGt),G9m=Object.assign({},require("http"));zHl.exports=Object.assign(G9m,{ClientRequest:_9m,globalManager:zGt,request:U9m,get:V9m})});var LHl=E((JUv,MHl)=>{"use strict";var{HttpsRequest:q9m,ClientRequest:W9m}=ZKr(),QGt=q9m.globalManager,H9m=QGt.request.bind(QGt),K9m=QGt.get.bind(QGt),J9m=Object.assign({},require("https"));MHl.exports=Object.assign(J9m,{ClientRequest:W9m,globalManager:QGt,request:H9m,get:K9m})});var UHl=E((YUv,_Hl)=>{"use strict";var{HttpRequestManager:m9o,HTTP2OutgoingMessage:Y9m,ClientRequest:X9m}=ZKr(),Z9m=QHl(),$9m=LHl(),MGt=new m9o;m9o.globalManager=MGt;var eqm=MGt.request.bind(MGt),tqm=MGt.get.bind(MGt);_Hl.exports={HTTP2OutgoingMessage:Y9m,ClientRequest:X9m,globalManager:m9o.globalManager,request:eqm,get:tqm,http:Z9m,https:$9m}});var C9o={};ne(C9o,{FetchError:()=>yR,Headers:()=>d8,Request:()=>VSe,Response:()=>vre,default:()=>fqm});function yR(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function jT(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:KHl(e)?e=Buffer.from(e.toString()):e instanceof BUe?e=e[PUe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof iJ.default||(e=Buffer.from(String(e)))),this[Vme]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof iJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new yR(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[Vme].error=c})}function Hct(){var e=this;if(this[Vme].disturbed)return jT.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[Vme].disturbed=!0,this[Vme].error)return jT.Promise.reject(this[Vme].error);if(this.body===null)return jT.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return jT.Promise.resolve(this.body);if(!(this.body instanceof iJ.default))return jT.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new jT.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new yR(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new yR(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new yR(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new yR(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function rqm(e,t){if(typeof y9o!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),y9o(e,"UTF-8",n).toString()}function KHl(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function JHl(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof iJ.default&&typeof n.getBoundary!="function"&&(t=new VHl,r=new VHl,n.pipe(t),n.pipe(r),e[Vme].body=t,n=r),n}function YHl(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":KHl(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof BUe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof iJ.default?null:"text/plain;charset=UTF-8"}function XHl(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function nqm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function LGt(e){if(e=`${e}`,ZHl.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function GHl(e){if(e=`${e}`,b9o.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function Jct(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function E9o(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[CC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[CC][n].join(", ")}:function(n){return[n.toLowerCase(),e[CC][n].join(", ")]})}function g9o(e,t){let r=Object.create(v9o);return r[I9o]={target:e,kind:t,index:0},r}function iqm(e){let t=Object.assign({__proto__:null},e[CC]),r=Jct(e[CC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function oqm(e){let t=new d8;for(let r of Object.keys(e))if(!ZHl.test(r))if(Array.isArray(e[r]))for(let n of e[r])b9o.test(n)||(t[CC][r]===void 0?t[CC][r]=[n]:t[CC][r].push(n));else b9o.test(e[r])||(t[CC][r]=[e[r]]);return t}function $Kr(e){return typeof e=="object"&&typeof e[Ume]=="object"}function lqm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function uqm(e){let t=e[Ume].parsedURL,r=new d8(e[Ume].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof iJ.default.Readable&&!cqm)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=XHl(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:iqm(r),agent:e.agent})}function _Gt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function USe(e,t){if(!USe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return jT.Promise=USe.Promise,new USe.Promise(function(r,n){let i=new VSe(e,t),o=uqm(i),s=HHl.default.request,a=i.signal,c=null,l=function(){let g=new _Gt("The user aborted a request.");n(g),i.body&&i.body instanceof iJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){l();return}let u=function(){l(),f()},p=s(o),d;a&&a.addEventListener("abort",u);function f(){p.abort(),a&&a.removeEventListener("abort",u),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new yR(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new yR(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=oqm(m.headers);if(USe.isRedirect(m.statusCode)){let x=g.get("Location"),S=x===null?null:pqm(i.url,x);switch(i.redirect){case"error":n(new yR(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(D){n(D)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new yR(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let P={headers:new d8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&XHl(i)===null){n(new yR("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(P.method="GET",P.body=void 0,P.headers.delete("content-length")),r(USe(new VSe(S,P))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",u)});let A=m.pipe(new qHl),b={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new vre(A,b),r(c);return}let C={flush:Kct.default.Z_SYNC_FLUSH,finishFlush:Kct.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Kct.default.createGunzip(C)),c=new vre(A,b),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new qHl).once("data",function(S){(S[0]&15)===8?A=A.pipe(Kct.default.createInflate()):A=A.pipe(Kct.default.createInflateRaw()),c=new vre(A,b),r(c)});return}c=new vre(A,b),r(c)}),nqm(p,i)})}var iJ,WHl,eJr,HHl,Kct,PUe,h9o,BUe,y9o,Vme,VHl,ZHl,b9o,CC,d8,I9o,v9o,OUe,sqm,vre,Ume,A9o,aqm,cqm,VSe,qHl,pqm,fqm,x9o=h(()=>{"use strict";iJ=Ae(require("stream"),1),WHl=Ae(require("http"),1),eJr=Ae(require("url"),1),HHl=Ae(UHl(),1),Kct=Ae(require("zlib"),1),PUe=Symbol("buffer"),h9o=Symbol("type"),BUe=class e{constructor(){this[h9o]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],l;c instanceof Buffer?l=c:ArrayBuffer.isView(c)?l=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?l=Buffer.from(c):c instanceof e?l=c[PUe]:l=Buffer.from(typeof c=="string"?c:String(c)),n.push(l)}}this[PUe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[h9o]=i)}get size(){return this[PUe].length}get type(){return this[h9o]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[PUe].slice(i,i+s),l=new e([],{type:arguments[2]});return l[PUe]=c,l}};Object.defineProperties(BUe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(BUe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});yR.prototype=Object.create(Error.prototype);yR.prototype.constructor=yR;yR.prototype.name="FetchError";try{y9o=require("encoding").convert}catch{}Vme=Symbol("Body internals"),VHl=iJ.default.PassThrough;jT.prototype={get body(){return this[Vme].body},get bodyUsed(){return this[Vme].disturbed},arrayBuffer(){return Hct.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Hct.call(this).then(function(t){return Object.assign(new BUe([],{type:e.toLowerCase()}),{[PUe]:t})})},json(){var e=this;return Hct.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return jT.Promise.reject(new yR(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Hct.call(this).then(function(e){return e.toString()})},buffer(){return Hct.call(this)},textConverted(){var e=this;return Hct.call(this).then(function(t){return rqm(t,e.headers)})}};Object.defineProperties(jT.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});jT.mixIn=function(e){for(let t of Object.getOwnPropertyNames(jT.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(jT.prototype,t);Object.defineProperty(e,t,r)}};jT.Promise=global.Promise;ZHl=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,b9o=/[^\t\x20-\x7e\x80-\xff]/;CC=Symbol("map"),d8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[CC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);return r===void 0?null:this[CC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=E9o(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=E9o(this),i++}}set(t,r){t=`${t}`,r=`${r}`,LGt(t),GHl(r);let n=Jct(this[CC],t);this[CC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,LGt(t),GHl(r);let n=Jct(this[CC],t);n!==void 0?this[CC][n].push(r):this[CC][t]=[r]}has(t){return t=`${t}`,LGt(t),Jct(this[CC],t)!==void 0}delete(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);r!==void 0&&delete this[CC][r]}raw(){return this[CC]}keys(){return g9o(this,"key")}values(){return g9o(this,"value")}[Symbol.iterator](){return g9o(this,"key+value")}};d8.prototype.entries=d8.prototype[Symbol.iterator];Object.defineProperty(d8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(d8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});I9o=Symbol("internal");v9o=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==v9o)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[I9o];let t=e.target,r=e.kind,n=e.index,i=E9o(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[I9o].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(v9o,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});OUe=Symbol("Response internals"),sqm=WHl.default.STATUS_CODES,vre=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jT.call(this,t,r);let n=r.status||200,i=new d8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=YHl(t);o&&i.append("Content-Type",o)}this[OUe]={url:r.url,status:n,statusText:r.statusText||sqm[n],headers:i}}get url(){return this[OUe].url}get status(){return this[OUe].status}get ok(){return this[OUe].status>=200&&this[OUe].status<300}get statusText(){return this[OUe].statusText}get headers(){return this[OUe].headers}clone(){return new e(JHl(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};jT.mixIn(vre.prototype);Object.defineProperties(vre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(vre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ume=Symbol("Request internals"),A9o=eJr.default.parse,aqm=eJr.default.format,cqm="destroy"in iJ.default.Readable.prototype;VSe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;$Kr(t)?n=A9o(t.url):(t&&t.href?n=A9o(t.href):n=A9o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||$Kr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:$Kr(t)&&t.body!==null?JHl(t):null;jT.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new d8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=YHl(o);c&&s.append("Content-Type",c)}let a=$Kr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!lqm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ume]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ume].method}get url(){return aqm(this[Ume].parsedURL)}get headers(){return this[Ume].headers}get redirect(){return this[Ume].redirect}get signal(){return this[Ume].signal}clone(){return new e(this)}};jT.mixIn(VSe.prototype);Object.defineProperty(VSe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(VSe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});_Gt.prototype=Object.create(Error.prototype);_Gt.prototype.constructor=_Gt;_Gt.prototype.name="AbortError";qHl=iJ.default.PassThrough,pqm=eJr.default.resolve;USe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};USe.Promise=global.Promise;fqm=USe});var RUe=E(GQ=>{"use strict";var Gme={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},UGt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},dqm="tag:yaml.org,2002:",mqm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function $Hl(e){let t=[0],r=e.indexOf(`
|
|
550
|
+
`).reduce(c8m,Object.create(null)),c8m=(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},l8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lf=l8m!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),u8m=class extends EUe{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=lf(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?lf(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=lf(e.path)),e.linkpath&&(e.linkpath=lf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},WHr=(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))},p8m=1024*1024,U8o=Buffer.from([31,139]),V8o=Buffer.from([40,181,47,253]),f8m=Math.max(U8o.length,V8o.length),p8=Symbol("state"),pUe=Symbol("writeEntry"),zme=Symbol("readEntry"),O8o=Symbol("nextEntry"),lql=Symbol("processEntry"),yre=Symbol("extendedHeader"),rGt=Symbol("globalExtendedHeader"),bSe=Symbol("meta"),uql=Symbol("emitMeta"),Jb=Symbol("buffer"),Qme=Symbol("queue"),ESe=Symbol("ended"),P8o=Symbol("emittedEnd"),fUe=Symbol("emit"),Wx=Symbol("unzip"),bHr=Symbol("consumeChunk"),EHr=Symbol("consumeChunkSub"),B8o=Symbol("consumeBody"),pql=Symbol("consumeMeta"),fql=Symbol("consumeHeader"),nGt=Symbol("consuming"),D8o=Symbol("bufferConcat"),IHr=Symbol("maybeEnd"),bct=Symbol("writing"),ISe=Symbol("aborted"),vHr=Symbol("onDone"),dUe=Symbol("sawValidEntry"),CHr=Symbol("sawNullBlock"),xHr=Symbol("sawEOF"),dql=Symbol("closeStream"),d8m=()=>!0,yGt=class extends Mql.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Qme]=[];[Jb];[zme];[pUe];[p8]="begin";[bSe]="";[yre];[rGt];[ESe]=!1;[Wx];[ISe]=!1;[dUe];[CHr]=!1;[xHr]=!1;[bct]=!1;[nGt]=!1;[P8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(vHr,()=>{(this[p8]==="begin"||this[dUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(vHr,e.ondone):this.on(vHr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||p8m,this.filter=typeof e.filter=="function"?e.filter:d8m;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[dql]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){WHr(this,e,t,r)}[fql](e,t){this[dUe]===void 0&&(this[dUe]=!1);let r;try{r=new bUe(e,t,this[yre],this[rGt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[CHr]?(this[xHr]=!0,this[p8]==="begin"&&(this[p8]="header"),this[fUe]("eof")):(this[CHr]=!0,this[fUe]("nullBlock"));else if(this[CHr]=!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[pUe]=new u8m(r,this[yre],this[rGt]);if(!this[dUe])if(i.remain){let o=()=>{i.invalid||(this[dUe]=!0)};i.on("end",o)}else this[dUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[fUe]("ignoredEntry",i),this[p8]="ignore",i.resume()):i.size>0&&(this[bSe]="",i.on("data",o=>this[bSe]+=o),this[p8]="meta"):(this[yre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[fUe]("ignoredEntry",i),this[p8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[p8]="body":(this[p8]="header",i.end()),this[zme]?this[Qme].push(i):(this[Qme].push(i),this[O8o]())))}}}[dql](){queueMicrotask(()=>this.emit("close"))}[lql](e){let t=!0;if(!e)this[zme]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[zme]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[O8o]()),t=!1);return t}[O8o](){do;while(this[lql](this[Qme].shift()));if(this[Qme].length===0){let e=this[zme];!e||e.flowing||e.size===e.remain?this[bct]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[B8o](e,t){let r=this[pUe];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[p8]="header",this[pUe]=void 0,r.end()),i.length}[pql](e,t){let r=this[pUe],n=this[B8o](e,t);return!this[pUe]&&r&&this[uql](r),n}[fUe](e,t,r){this[Qme].length===0&&!this[zme]?this.emit(e,t,r):this[Qme].push([e,t,r])}[uql](e){switch(this[fUe]("meta",this[bSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[yre]=MHr.parse(this[bSe],this[yre],!1);break;case"GlobalExtendedHeader":this[rGt]=MHr.parse(this[bSe],this[rGt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[yre]??Object.create(null);this[yre]=t,t.path=this[bSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[yre]||Object.create(null);this[yre]=t,t.linkpath=this[bSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ISe]=!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[ISe])return r?.(),!1;if((this[Wx]===void 0||this.brotli===void 0&&this[Wx]===!1)&&e){if(this[Jb]&&(e=Buffer.concat([this[Jb],e]),this[Jb]=void 0),e.length<f8m)return this[Jb]=e,r?.(),!0;for(let s=0;this[Wx]===void 0&&s<U8o.length;s++)e[s]!==U8o[s]&&(this[Wx]=!1);let i=!1;if(this[Wx]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<V8o.length;s++)if(e[s]!==V8o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Wx]===!1&&o)if(e.length<512)if(this[ESe])this.brotli=!0;else return this[Jb]=e,r?.(),!0;else try{new bUe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Wx]===void 0||this[Wx]===!1&&(this.brotli||i)){let s=this[ESe];this[ESe]=!1,this[Wx]=this[Wx]===void 0?new Q5m({}):i?new U5m({}):new L5m({}),this[Wx].on("data",c=>this[bHr](c)),this[Wx].on("error",c=>this.abort(c)),this[Wx].on("end",()=>{this[ESe]=!0,this[bHr]()}),this[bct]=!0;let a=!!this[Wx][s?"end":"write"](e);return this[bct]=!1,r?.(),a}}this[bct]=!0,this[Wx]?this[Wx].write(e):this[bHr](e),this[bct]=!1;let n=this[Qme].length>0?!1:this[zme]?this[zme].flowing:!0;return!n&&this[Qme].length===0&&this[zme]?.once("drain",()=>this.emit("drain")),r?.(),n}[D8o](e){e&&!this[ISe]&&(this[Jb]=this[Jb]?Buffer.concat([this[Jb],e]):e)}[IHr](){if(this[ESe]&&!this[P8o]&&!this[ISe]&&!this[nGt]){this[P8o]=!0;let e=this[pUe];if(e&&e.blockRemain){let t=this[Jb]?this[Jb].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Jb]&&e.write(this[Jb]),e.end()}this[fUe](vHr)}}[bHr](e){if(this[nGt]&&e)this[D8o](e);else if(!e&&!this[Jb])this[IHr]();else if(e){if(this[nGt]=!0,this[Jb]){this[D8o](e);let t=this[Jb];this[Jb]=void 0,this[EHr](t)}else this[EHr](e);for(;this[Jb]&&this[Jb]?.length>=512&&!this[ISe]&&!this[xHr];){let t=this[Jb];this[Jb]=void 0,this[EHr](t)}this[nGt]=!1}(!this[Jb]||this[ESe])&&this[IHr]()}[EHr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ISe]&&!this[xHr];)switch(this[p8]){case"begin":case"header":this[fql](e,t),t+=512;break;case"ignore":case"body":t+=this[B8o](e,t);break;case"meta":t+=this[pql](e,t);break;default:throw new Error("invalid state: "+this[p8])}t<r&&(this[Jb]=this[Jb]?Buffer.concat([e.subarray(t),this[Jb]]):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[ISe]||(this[Wx]?(e&&this[Wx].write(e),this[Wx].end()):(this[ESe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[IHr]())),this}},fGt=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)},m8m=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},Jql=(e,t)=>{let r=new Map(t.map(o=>[fGt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,GHr.parse)(o).root||".",c;if(o===a)c=!1;else{let l=r.get(o);c=l!==void 0?l:i((0,GHr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(fGt(o)):o=>i(fGt(o))},h8m=e=>{let t=new yGt(e),r=e.file,n;try{n=gUe.default.openSync(r,"r");let i=gUe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=gUe.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=gUe.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{gUe.default.closeSync(n)}catch{}}},g8m=(e,t)=>{let r=new yGt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),gUe.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},HHr=IGt(h8m,g8m,e=>new yGt(e),e=>new yGt(e),(e,t)=>{t?.length&&Jql(e,t),e.noResume||m8m(e)}),Yql=(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:A8m,parse:mql}=Xql.win32,mGo=e=>{let t="",r=mql(e);for(;A8m(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=mql(e)}return[t,e]},KHr=["|","<",">","?",":"],hGo=KHr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),y8m=new Map(KHr.map((e,t)=>[e,hGo[t]])),b8m=new Map(hGo.map((e,t)=>[e,KHr[t]])),hql=e=>KHr.reduce((t,r)=>t.split(r).join(y8m.get(r)),e),E8m=e=>hGo.reduce((t,r)=>t.split(r).join(b8m.get(r)),e),Zql=(e,t)=>t?(e=lf(e).replace(/^\.(\/|$)/,""),fGt(t)+"/"+e):lf(e),I8m=16*1024*1024,gql=Symbol("process"),Aql=Symbol("file"),yql=Symbol("directory"),q8o=Symbol("symlink"),bql=Symbol("hardlink"),iGt=Symbol("header"),BHr=Symbol("read"),W8o=Symbol("lstat"),DHr=Symbol("onlstat"),H8o=Symbol("onread"),K8o=Symbol("onreadlink"),J8o=Symbol("openfile"),Y8o=Symbol("onopenfile"),wSe=Symbol("close"),LHr=Symbol("mode"),X8o=Symbol("awaitDrain"),R8o=Symbol("ondrain"),bre=Symbol("prefix"),$ql=class extends EUe{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=pGo(t);super(),this.path=lf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||I8m,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=lf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?lf(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]=mGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=E8m(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=lf(r.absolute||G8o.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[DHr](i):this[W8o]()}warn(e,t,r={}){return WHr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[W8o](){ZK.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[DHr](t)})}[DHr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=x8m(e),this.emit("stat",e),this[gql]()}[gql](){switch(this.type){case"File":return this[Aql]();case"Directory":return this[yql]();case"SymbolicLink":return this[q8o]();default:return this.end()}}[LHr](e){return Yql(e,this.type==="Directory",this.portable)}[bre](e){return Zql(e,this.prefix)}[iGt](){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 bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this[LHr](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 MHr({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[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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)}[yql](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[iGt](),this.end()}[q8o](){ZK.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[K8o](t)})}[K8o](e){this.linkpath=lf(e),this[iGt](),this.end()}[bql](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=lf(G8o.default.relative(this.cwd,e)),this.stat.size=0,this[iGt](),this.end()}[Aql](){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[bql](t);this.linkCache.set(e,this.absolute)}if(this[iGt](),this.stat.size===0)return this.end();this[J8o]()}[J8o](){ZK.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Y8o](t)})}[Y8o](e){if(this.fd=e,this.#e)return this[wSe]();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[BHr]()}[BHr](){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");ZK.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[wSe](()=>this.emit("error",o));this[H8o](s)})}[wSe](e=()=>{}){this.fd!==void 0&&ZK.default.close(this.fd,e)}[H8o](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[wSe](()=>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[wSe](()=>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[R8o]():this[X8o](()=>this[R8o]())}[X8o](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)}[R8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[wSe](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[BHr]()}},v8m=class extends $ql{sync=!0;[W8o](){this[DHr](ZK.default.lstatSync(this.absolute))}[q8o](){this[K8o](ZK.default.readlinkSync(this.absolute))}[J8o](){this[Y8o](ZK.default.openSync(this.absolute,"r"))}[BHr](){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=ZK.default.readSync(t,r,n,i,o);this[H8o](s),e=!1}finally{if(e)try{this[wSe](()=>{})}catch{}}}[X8o](e){e()}[wSe](e=()=>{}){this.fd!==void 0&&ZK.default.closeSync(this.fd),e()}},C8m=class extends EUe{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 WHr(this,e,t,r)}constructor(e,t={}){let r=pGo(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=lf(e.path),this.mode=e.mode!==void 0?this[LHr](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?lf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=mGo(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 bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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 MHr({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[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](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)}[bre](e){return Zql(e,this.prefix)}[LHr](e){return Yql(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}},x8m=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",S8m=class Sct{tail;head;length=0;static create(t=[]){return new Sct(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++)T8m(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)O8m(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 Sct;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 Sct;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 Sct;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 Sct;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=w8m(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}};gGo=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}},Eql=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Iql=Buffer.alloc(1024),RHr=Symbol("onStat"),oGt=Symbol("ended"),YK=Symbol("queue"),sGt=Symbol("pendingLinks"),vSe=Symbol("current"),mUe=Symbol("process"),aGt=Symbol("processing"),SHr=Symbol("processJob"),XK=Symbol("jobs"),k8o=Symbol("jobDone"),kHr=Symbol("addFSEntry"),vql=Symbol("addTarEntry"),$8o=Symbol("stat"),eGo=Symbol("readdir"),FHr=Symbol("onreaddir"),NHr=Symbol("pipe"),Cql=Symbol("entry"),F8o=Symbol("entryOpt"),jHr=Symbol("writeEntryClass"),eWl=Symbol("write"),N8o=Symbol("ondrain"),JHr=class extends EUe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[jHr];onWriteEntry;[YK];[sGt]=new Map;[XK]=0;[aGt]=!1;[oGt]=!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=lf(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[jHr]=$ql,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 z5m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new M5m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new _5m(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[N8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[N8o]);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[YK]=new S8m,this[XK]=0,this.jobs=Number(e.jobs)||4,this[aGt]=!1,this[oGt]=!1}[eWl](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[oGt]=!0,this[mUe](),r&&r(),this}write(e){if(this[oGt])throw new Error("write after end");return typeof e=="string"?this[kHr](e):this[vql](e),this.flowing}[vql](e){let t=lf(Z8o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new Eql(e.path,t);r.entry=new C8m(e,this[F8o](r)),r.entry.on("end",()=>this[k8o](r)),this[XK]+=1,this[YK].push(r)}this[mUe]()}[kHr](e){let t=lf(Z8o.default.resolve(this.cwd,e));this[YK].push(new Eql(e,t)),this[mUe]()}[$8o](e){e.pending=!0,this[XK]+=1;let t=this.follow?"stat":"lstat";bGt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[XK]-=1,r?this.emit("error",r):this[RHr](e,n)})}[RHr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[vSe])this[SHr](e);else{let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);n?n.push(e):this[sGt].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[mUe]()}[eGo](e){e.pending=!0,this[XK]+=1,bGt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[XK]-=1,t)return this.emit("error",t);this[FHr](e,r)})}[FHr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[mUe]()}[mUe](){if(!this[aGt]){this[aGt]=!0;for(let e=this[YK].head;e&&this[XK]<this.jobs;e=e.next)if(this[SHr](e.value),e.value.ignore){let t=e.next;this[YK].removeNode(e),e.next=t}this[aGt]=!1,this[oGt]&&this[YK].length===0&&this[XK]===0&&(this.zip?this.zip.end(Iql):(super.write(Iql),super.end()))}}get[vSe](){return this[YK]&&this[YK].head&&this[YK].head.value}[k8o](e){this[YK].shift(),this[XK]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);if(n){this[sGt].delete(r);for(let i of n)i.pending=!1,this[SHr](i)}}this[mUe]()}[SHr](e){if(e.pending&&e.pendingLink&&e===this[vSe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[vSe]&&!e.piped&&this[NHr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[RHr](e,t):this[$8o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[FHr](e,t):this[eGo](e),!e.readdir)return}if(e.entry=this[Cql](e),!e.entry){e.ignore=!0;return}e===this[vSe]&&!e.piped&&this[NHr](e)}}}[F8o](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}}[Cql](e){this[XK]+=1;try{return new this[jHr](e.path,this[F8o](e)).on("end",()=>this[k8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[N8o](){this[vSe]&&this[vSe].entry&&this[vSe].entry.resume()}[NHr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](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={}){WHr(this,e,t,r)}},AGo=class extends JHr{sync=!0;constructor(e){super(e),this[jHr]=v8m}pause(){}resume(){}[$8o](e){let t=this.follow?"statSync":"lstatSync";this[RHr](e,bGt.default[t](e.absolute))}[eGo](e){this[FHr](e,bGt.default.readdirSync(e.absolute))}[NHr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[eWl](n)})}},P8m=(e,t)=>{let r=new AGo(e),n=new Qql(e.file,{mode:e.mode||438});r.pipe(n),tWl(r,t)},B8m=(e,t)=>{let r=new JHr(e),n=new VHr(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 rWl(r,t).catch(o=>r.emit("error",o)),i},tWl=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:uGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},rWl=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:uGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},D8m=(e,t)=>{let r=new AGo(e);return tWl(r,t),r},R8m=(e,t)=>{let r=new JHr(e);return rWl(r,t).catch(n=>r.emit("error",n)),r},YHr=IGt(P8m,B8m,D8m,R8m,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),k8m=process.env.__FAKE_PLATFORM__||process.platform,iWl=k8m==="win32",{O_CREAT:oWl,O_NOFOLLOW:xql,O_TRUNC:sWl,O_WRONLY:aWl}=EGo.default.constants,cWl=Number(process.env.__FAKE_FS_O_FILENAME__)||EGo.default.constants.UV_FS_O_FILEMAP||0,F8m=iWl&&!!cWl,N8m=512*1024,j8m=cWl|sWl|oWl|aWl,Sql=!iWl&&typeof xql=="number"?xql|sWl|oWl|aWl:null,lWl=Sql!==null?()=>Sql:F8m?e=>e<N8m?j8m:"w":()=>"w",tGo=(e,t,r)=>{try{return vGt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},_Hr=(e,t,r,n)=>{vGt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},z8m=(e,t,r,n,i)=>{if(t.isDirectory())uWl(Tct.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Tct.default.resolve(e,t.name);_Hr(s,r,n,i)});else{let o=Tct.default.resolve(e,t.name);_Hr(o,r,n,i)}},uWl=(e,t,r,n)=>{vGt.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 _Hr(e,t,r,n);let s=o.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--s===0)return _Hr(e,t,r,n)}};for(let l of o)z8m(e,l,t,r,c)})},Q8m=(e,t,r,n)=>{t.isDirectory()&&pWl(Tct.default.resolve(e,t.name),r,n),tGo(Tct.default.resolve(e,t.name),r,n)},pWl=(e,t,r)=>{let n;try{n=vGt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return tGo(e,t,r);throw o}for(let i of n)Q8m(e,i,t,r);return tGo(e,t,r)},dWl=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"}},XHr=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"}},M8m=(e,t)=>{VQ.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new dWl(e,r?.code||"ENOTDIR")),t(r)})},L8m=(e,t,r)=>{e=lf(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),l=t.preserve,u=t.unlink,p=lf(t.cwd),d=(m,g)=>{m?r(m):g&&c?uWl(g,s,a,A=>d(A)):o?VQ.default.chmod(e,i,r):r()};if(e===p)return M8m(e,d);if(l)return fWl.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=lf(EGt.default.relative(p,e)).split("/");rGo(p,f,i,u,p,void 0,d)},rGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=lf(EGt.default.resolve(e+"/"+a));VQ.default.mkdir(c,r,mWl(c,t,r,n,i,o,s))},mWl=(e,t,r,n,i,o,s)=>a=>{a?VQ.default.lstat(e,(c,l)=>{if(c)c.path=c.path&&lf(c.path),s(c);else if(l.isDirectory())rGo(e,t,r,n,i,o,s);else if(n)VQ.default.unlink(e,u=>{if(u)return s(u);VQ.default.mkdir(e,r,mWl(e,t,r,n,i,o,s))});else{if(l.isSymbolicLink())return s(new XHr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,rGo(e,t,r,n,i,o,s))},_8m=e=>{let t=!1,r;try{t=VQ.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new dWl(e,r??"ENOTDIR")}},U8m=(e,t)=>{e=lf(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,l=t.unlink,u=lf(t.cwd),p=m=>{m&&a&&pWl(m,o,s),i&&VQ.default.chmodSync(e,n)};if(e===u)return _8m(u),p();if(c)return p(VQ.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=lf(EGt.default.relative(u,e)).split("/"),f;for(let m=d.shift(),g=u;m&&(g+="/"+m);m=d.shift()){g=lf(EGt.default.resolve(g));try{VQ.default.mkdirSync(g,n),f=f||g}catch{let A=VQ.default.lstatSync(g);if(A.isDirectory())continue;if(l){VQ.default.unlinkSync(g),VQ.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new XHr(g,g+"/"+d.join("/"))}}return p(f)},j8o=Object.create(null),wql=1e4,Ect=new Set,V8m=e=>{Ect.has(e)?Ect.delete(e):j8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ect.add(e);let t=j8o[e],r=Ect.size-wql;if(r>wql/10){for(let n of Ect)if(Ect.delete(n),delete j8o[n],--r<=0)break}return t},G8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,q8m=G8m==="win32",W8m=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,IGo.join)(n,r)),t.push(r||"/"),t},[]),H8m=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=q8m?["win32 parallelization disabled"]:e.map(n=>fGt((0,IGo.join)(V8m(n))));let r=new Set(e.map(n=>W8m(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}},K8m=()=>process.umask(),Tql=Symbol("onEntry"),nGo=Symbol("checkFs"),Oql=Symbol("checkFs2"),iGo=Symbol("isReusable"),f8=Symbol("makeFs"),oGo=Symbol("file"),sGo=Symbol("directory"),zHr=Symbol("link"),Pql=Symbol("symlink"),Bql=Symbol("hardlink"),uGt=Symbol("ensureNoSymlink"),Dql=Symbol("unsupported"),Rql=Symbol("checkPath"),z8o=Symbol("stripAbsolutePath"),OSe=Symbol("mkdir"),FT=Symbol("onError"),wHr=Symbol("pending"),kql=Symbol("pend"),Ict=Symbol("unpend"),Q8o=Symbol("ended"),M8o=Symbol("maybeClose"),aGo=Symbol("skip"),dGt=Symbol("doChown"),mGt=Symbol("uid"),hGt=Symbol("gid"),gGt=Symbol("checkedCwd"),J8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,AGt=J8m==="win32",Y8m=1024,X8m=(e,t)=>{if(!AGt)return Ed.default.unlink(e,t);let r=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.rename(e,r,n=>{if(n)return t(n);Ed.default.unlink(r,t)})},Z8m=e=>{if(!AGt)return Ed.default.unlinkSync(e);let t=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.renameSync(e,t),Ed.default.unlinkSync(t)},Fql=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,vGo=class extends yGt{[Q8o]=!1;[gGt]=!1;[wHr]=0;reservations=new H8m;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[Q8o]=!0,this[M8o]()},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:Y8m,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||AGt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=lf(Hx.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:K8m():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[Tql](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[M8o](){this[Q8o]&&this[wHr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[z8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=mGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||AGt&&/^[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=Hx.default.posix.dirname(e.path),c=Hx.default.posix.normalize(Hx.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}[Rql](e){let t=lf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=lf(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[z8o](e,"path")||!this[z8o](e,"linkpath"))return!1;if(e.absolute=Hx.default.isAbsolute(e.path)?lf(Hx.default.resolve(e.path)):lf(Hx.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:lf(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}=Hx.default.win32.parse(String(e.absolute));e.absolute=n+hql(String(e.absolute).slice(n.length));let{root:i}=Hx.default.win32.parse(e.path);e.path=i+hql(e.path.slice(i.length))}return!0}[Tql](e){if(!this[Rql](e))return e.resume();switch(nWl.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[nGo](e);default:return this[Dql](e)}}[FT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Ict](),t.resume())}[OSe](e,t,r){L8m(lf(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)}[dGt](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}[mGt](e){return Fql(this.uid,e.uid,this.processUid)}[hGt](e){return Fql(this.gid,e.gid,this.processGid)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new VHr(String(e.absolute),{flags:lWl(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Ed.default.close(n.fd,()=>{}),n.write=()=>!0,this[FT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Ed.default.close(n.fd,()=>{}),this[FT](a,e),t();return}--i===0&&n.fd!==void 0&&Ed.default.close(n.fd,c=>{c?this[FT](c,e):this[Ict](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let l=e.atime||new Date,u=e.mtime;Ed.default.futimes(c,l,u,p=>p?Ed.default.utimes(a,l,u,d=>o(d&&p)):o())}if(typeof c=="number"&&this[dGt](e)){i++;let l=this[mGt](e),u=this[hGt](e);typeof l=="number"&&typeof u=="number"&&Ed.default.fchown(c,l,u,p=>p?Ed.default.chown(a,l,u,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[FT](a,e),t()}),e.pipe(s)),s.pipe(n)}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[OSe](String(e.absolute),r,n=>{if(n){this[FT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Ict](),e.resume())};e.mtime&&!this.noMtime&&(i++,Ed.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[dGt](e)&&(i++,Ed.default.chown(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)),o)),o()})}[Dql](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Pql](e,t){let r=lf(Hx.default.relative(this.cwd,Hx.default.resolve(Hx.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[uGt](e,this.cwd,r,()=>this[zHr](e,String(e.linkpath),"symlink",t),n=>{this[FT](n,e),t()})}[Bql](e,t){let r=lf(Hx.default.resolve(this.cwd,String(e.linkpath))),n=lf(String(e.linkpath)).split("/");this[uGt](e,this.cwd,n,()=>this[zHr](e,r,"link",t),i=>{this[FT](i,e),t()})}[uGt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=Hx.default.resolve(t,o);Ed.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new XHr(s,Hx.default.resolve(s,r.join("/"))));this[uGt](e,s,r,n,i)})}[kql](){this[wHr]++}[Ict](){this[wHr]--,this[M8o]()}[aGo](e){this[Ict](),e.resume()}[iGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!AGt}[nGo](e){this[kql]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Oql](e,r))}[Oql](e,t){let r=s=>{t(s)},n=()=>{this[OSe](this.cwd,this.dmode,s=>{if(s){this[FT](s,e),r();return}this[gGt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=lf(Hx.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[OSe](s,this.dmode,a=>{if(a){this[FT](a,e),r();return}o()})}o()},o=()=>{Ed.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[aGo](e),r();return}if(s||this[iGo](e,a))return this[f8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,l=u=>this[f8](u??null,e,r);return c?Ed.default.chmod(String(e.absolute),Number(e.mode),l):l()}if(e.absolute!==this.cwd)return Ed.default.rmdir(String(e.absolute),c=>this[f8](c??null,e,r))}if(e.absolute===this.cwd)return this[f8](null,e,r);X8m(String(e.absolute),c=>this[f8](c??null,e,r))})};this[gGt]?i():n()}[f8](e,t,r){if(e){this[FT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[oGo](t,r);case"Link":return this[Bql](t,r);case"SymbolicLink":return this[Pql](t,r);case"Directory":case"GNUDumpDir":return this[sGo](t,r)}}[zHr](e,t,r,n){Ed.default[r](t,String(e.absolute),i=>{i?this[FT](i,e):(this[Ict](),e.resume()),n()})}},cGt=e=>{try{return[null,e()]}catch(t){return[t,null]}},hWl=class extends vGo{sync=!0;[f8](e,t){return super[f8](e,t,()=>{})}[nGo](e){if(!this[gGt]){let i=this[OSe](this.cwd,this.dmode);if(i)return this[FT](i,e);this[gGt]=!0}if(e.absolute!==this.cwd){let i=lf(Hx.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[OSe](i,this.dmode);if(o)return this[FT](o,e)}}let[t,r]=cGt(()=>Ed.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[aGo](e);if(t||this[iGo](e,r))return this[f8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?cGt(()=>{Ed.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[f8](s,e)}let[i]=cGt(()=>Ed.default.rmdirSync(String(e.absolute)));this[f8](i,e)}let[n]=e.absolute===this.cwd?[]:cGt(()=>Z8m(String(e.absolute)));this[f8](n,e)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Ed.default.closeSync(i)}catch(c){a=c}(s||a)&&this[FT](s||a,e),t()},i;try{i=Ed.default.openSync(String(e.absolute),lWl(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[FT](s,e)),e.pipe(o)),o.on("data",s=>{try{Ed.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{Ed.default.futimesSync(i,a,c)}catch(l){try{Ed.default.utimesSync(String(e.absolute),a,c)}catch{s=l}}}if(this[dGt](e)){let a=this[mGt](e),c=this[hGt](e);try{Ed.default.fchownSync(i,Number(a),Number(c))}catch(l){try{Ed.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||l}}}n(s)})}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[OSe](String(e.absolute),r);if(n){this[FT](n,e),t();return}if(e.mtime&&!this.noMtime)try{Ed.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[dGt](e))try{Ed.default.chownSync(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)))}catch{}t(),e.resume()}[OSe](e,t){try{return U8m(lf(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}}[uGt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=Hx.default.resolve(o,s);let[a,c]=cGt(()=>Ed.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new XHr(o,Hx.default.resolve(t,r.join("/"))))}n()}[zHr](e,t,r,n){let i=`${r}Sync`;try{Ed.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[FT](o,e)}}},$8m=e=>{let t=new hWl(e),r=e.file,n=yGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new w5m(r,{readSize:i,size:n.size}).pipe(t)},eGm=(e,t)=>{let r=new vGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),yGo.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},gWl=IGt($8m,eGm,e=>new hWl(e),e=>new vGo(e),(e,t)=>{t?.length&&Jql(e,t)}),tGm=(e,t)=>{let r=new AGo(e),n=!0,i,o;try{try{i=UQ.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=UQ.default.openSync(e.file,"w+");else throw c}let s=UQ.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let u=0,p=0;u<512;u+=p){if(p=UQ.default.readSync(i,a,u,a.length-u,o+u),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new bUe(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(o+l+512>s.size)break;o+=l,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,rGm(e,r,o,i,t)}finally{if(n)try{UQ.default.closeSync(i)}catch{}}},rGm=(e,t,r,n,i)=>{let o=new Qql(e.file,{fd:n,start:r});t.pipe(o),iGm(t,i)},nGm=(e,t)=>{t=Array.from(t);let r=new JHr(e),n=(i,o,s)=>{let a=(d,f)=>{d?UQ.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let l=0,u=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(l+=f,l<512&&f)return UQ.default.read(i,u,l,u.length-l,c+l,p);if(c===0&&u[0]===31&&u[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let m=new bUe(u);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),l=0,UQ.default.read(i,u,0,512,c,p)};UQ.default.read(i,u,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",UQ.default.open(e.file,s,a);if(c||!l)return o(c);UQ.default.fstat(l,(u,p)=>{if(u)return UQ.default.close(l,()=>o(u));n(l,p.size,(d,f)=>{if(d)return o(d);let m=new VHr(e.file,{fd:l,start:f});r.pipe(m),m.on("error",o),m.on("close",i),oGm(r,t)})})};UQ.default.open(e.file,s,a)})},iGm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:CGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},oGm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:CGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},lGt=IGt(tGm,nGm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!R5m(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")}),gzv=IGt(lGt.syncFile,lGt.asyncFile,lGt.syncNoFile,lGt.asyncNoFile,(e,t=[])=>{lGt.validate?.(e,t),sGm(e)}),sGm=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 Ki,$Hr=h(()=>{"use strict";zn();Ki=class e{breadcrumbs=[];context;static STRING=$t.TypeReference.primitive({v1:"STRING",v2:$t.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=$t.TypeReference.container($t.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var xGo,AWl,yWl=h(()=>{"use strict";xGo=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,l=>{a.has(l.position)||(c--,a.add(l.position),this._path.length===1?this.resolveNode(l,`${o}.${c}`):(s.children.push({...l,path:c.toString()}),s.line=l.line,s.position=l.position,s.lineStart=l.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}}},AWl=xGo});var bWl,HE,Ire,SGo,CGt=h(()=>{"use strict";tr();Iy();bWl=require("fs/promises");Ko();yWl();(function(e){e.WARNING="warning",e.ERROR="error"})(HE||(HE={}));Ire=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new SGo({logger:t,relativePathToFile:be.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||HE.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===HE.ERROR?t++:(n.level===HE.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??HE.WARNING;if(!(n===HE.WARNING&&!t))switch(n){case HE.ERROR:if(this.logger.log(Un.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(Un.Debug,` - at location (${o})`)}break;case HE.WARNING:if(this.logger.log(Un.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(Un.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Un.Warn,` - resolution: ${r.resolution}`);break}}}},SGo=class{logger;relativePathToFile;map=new AWl;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,bWl.readFile)(this.relativePathToFile,"utf-8");Er.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Un.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)}}});function cGm(e){return"deprecated"in e&&e.deprecated===!0}async function lGm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Er.load(r)}}catch{return}}var Yb,EWl=h(()=>{"use strict";QK();mt();zn();Ko();xo();CGt();Uo();Yb=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;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=Tw({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=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ao(n.join("_"));return G6(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}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:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:HE.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 l=t.$ref.split("#"),u=l[0];if(n=l[1],!u)return{resolved:!1};if(s=u,o=await this.loadExternalDocument(u),r=o,r==null)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(l=>l.replace(/~1/g,"/"));for(let l of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let l=new Set;l.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,l,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=lGm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}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,l=s.substring(2).split("/").map(D0);for(let u of l){if(typeof c!="object"||c===null)return t;c=c[u]}if(c!=null){let u=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),u}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 $t.ObjectPropertyAccess.ReadOnly;if(i)return $t.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 vC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new vC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(cGm(t))return{status:eh.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 Hr.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"&&Yh(t)}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(gr(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 Vo,AR=h(()=>{"use strict";Vo=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]}}});var Pct,wGo=h(()=>{"use strict";AR();Pct=class extends Vo{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 eKr,IWl=h(()=>{"use strict";zn();AR();eKr=class extends Vo{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 eh.InDevelopment;case"PRE_RELEASE":return eh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return eh.GeneralAvailability;case"DEPRECATED":return eh.Deprecated;case"ALPHA":return eh.Alpha;case"BETA":return eh.Beta;case"PREVIEW":return eh.Preview;case"LEGACY":return eh.Legacy;default:return}}}});var Bct,TGo=h(()=>{"use strict";AR();Bct=class extends Vo{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 Dct,OGo=h(()=>{"use strict";AR();Dct=class extends Vo{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}}});var uGm,pGm,vWl,CWl=h(()=>{"use strict";nn();uGm=Xt.object({snake:Xt.string().optional(),camel:Xt.string().optional(),screamingSnake:Xt.string().optional(),pascal:Xt.string().optional()}),pGm=Xt.object({description:Xt.string().optional(),name:Xt.string().optional(),casing:uGm.optional()}),vWl=Xt.record(pGm)});var Rct,PGo=h(()=>{"use strict";AR();CWl();Rct=class extends Vo{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=vWl.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 IUe,xWl=h(()=>{"use strict";AR();IUe=class extends Vo{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 tKr,SWl=h(()=>{"use strict";AR();tKr=class extends Vo{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 rKr,wWl=h(()=>{"use strict";AR();rKr=class extends Vo{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 nKr,TWl=h(()=>{"use strict";AR();nKr=class extends Vo{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 iKr,OWl=h(()=>{"use strict";AR();iKr=class extends Vo{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 oKr,PWl=h(()=>{"use strict";AR();oKr=class extends Vo{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 sKr,BWl=h(()=>{"use strict";AR();sKr=class extends Vo{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}}});function fGm({isText:e,isAttribute:t}){return e?rQ.Text:t?rQ.Attribute:rQ.Element}function kWl(e){return typeof e=="object"&&e!=null}function aKr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function BGo(...e){return e.find(t=>t!=null)}var DWl,RWl,kct,Fct,cKr=h(()=>{"use strict";zn();AR();DWl="x-fern-xml-text",RWl="x-fern-xml-list-separator",kct=class extends Vo{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(kWl(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},Fct=class extends Vo{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=BGo(this.getExtensionValue(t),this.getExtensionValue(r)),i=BGo(aKr(t,DWl),aKr(r,DWl)),o=BGo(aKr(t,RWl),aKr(r,RWl)),s=kWl(n)?n:{};return{kind:fGm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var vC={};ne(vC,{AudienceExtension:()=>Pct,FernAvailabilityExtension:()=>eKr,FernDiscriminatedExtension:()=>Bct,FernDiscriminatorContextExtension:()=>Dct,FernEnumExtension:()=>Rct,FernIgnoreExtension:()=>IUe,FernOptionalExtension:()=>tKr,FernTypeExtension:()=>oKr,FernTypeNameExtension:()=>sKr,SdkGroupNameExtension:()=>rKr,SdkMethodNameExtension:()=>nKr,ServerFromOperationNameExtension:()=>iKr,XmlPropertyExtension:()=>Fct,XmlSchemaExtension:()=>kct});var DGo=h(()=>{"use strict";wGo();IWl();TGo();OGo();PGo();xWl();SWl();wWl();TWl();OWl();PWl();BWl();cKr()});function NWl(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>dw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(KD.Object);case"enum":return s(KD.Enum);case"union":return s(KD.Union);case"undiscriminatedUnion":return s(KD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=FWl(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||FWl(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:ic.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function FWl(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var jWl=h(()=>{"use strict";zn()});var tJ,zWl=h(()=>{"use strict";zn();sc();xo();$Hr();DGo();jWl();tJ=class extends Ki{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new M4e(n),this.ir={auth:{docs:void 0,requirement:$t.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:$t.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,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,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IUe({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 IUe({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},$5t(this.ir,{onWarning:a=>this.context.logger.warn(a)}),NWl(this.ir.types);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)),K5t({ir:i});let o=this.context.exampleGenerationArgs,s=d4o({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=Y5t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...Z5t(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,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,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let l=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),u=this.getOrCreatePackage({group:n});u!==this.ir.rootPackage&&u.docs==null&&o!=null&&(u.docs=o);let p=[...l].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];u.service==null&&(u.service=s??`service_${l.map(m=>ao(m)).join("/")}`),this.ir.services[u.service]==null&&(this.ir.services[u.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[u.service]?.endpoints.push(t);let f=this.ir.services[u.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ao(i?.join(".")),s=ao(r),a=this.context.namespace?`${ao(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,l=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?l.websocket==null&&(l.websocket=c):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,c,t),n!=null&&this.irGraph.markChannelForAudiences(u,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,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}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:zy(""),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,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ao(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}}});function vUe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function hGm(e){if(!vUe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>vUe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function gGm(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 MWl(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var dGm,QWl,mGm,Bw,DSe=h(()=>{"use strict";mt();Uo();dGm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,QWl=new WeakMap,mGm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Bw=class e extends Ki{MAX_DEPTH=12;EXAMPLE_STRING=Mo.STRING;EXAMPLE_NUMBER=Mo.DOUBLE;EXAMPLE_BOOLEAN=Mo.BOOLEAN;EXAMPLE_INTEGER=Mo.INT;EXAMPLE_DATE=Mo.DATE;EXAMPLE_DATE_TIME=Mo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;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;let l=QWl.get(r);l!=null?this.sharedState=l:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},QWl.set(r,this.sharedState))}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&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();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=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([b,I])=>{if(typeof I!="object")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:b,resolvedSchema:t}))return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let C=hGm(I),x=!(b in r)||!C&&r[b]==null||C&&r[b]===void 0,S=!o.includes(b);if(x&&S){if(this.example===void 0&&this.generateOptionalProperties){let P=this.maybeResolveSchemaExample(I),D=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:P,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:b,result:D.convert()}}return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let P=r[b],D=P!==void 0?P:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:D,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:b,result:O}}}),a=n?[]:(t.allOf??[]).map((b,I)=>{let C=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return C&&this.isConstraintOnlySchema(C)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...b,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:b})=>b.usedProvidedExample)||a.some(b=>b.usedProvidedExample)),l=Object.fromEntries(s.map(({key:b,result:I})=>[b,I.validExample]).filter(([b,I])=>I!==void 0));for(let b of a)if(typeof b.validExample=="object"&&b.validExample!==null){let I=b.validExample,C=Object.fromEntries(Object.entries(I).filter(([x,S])=>S!==void 0));for(let[x,S]of Object.entries(C))(!(x in l)||l[x]==null)&&(l[x]=S)}let u=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(b=>!p.has(b)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(b=>{let I=[...this.breadcrumbs,b].join("."),C={message:`Found unexpected property '${b}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,b]};u.push({key:b,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[C]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})});else{let b=t.additionalProperties;g.forEach(I=>{let x=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:b,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();u.push({key:I,result:x})})}for(let{key:b,result:I}of u)I.validExample!==void 0&&l[b]===void 0&&(l[b]=I.validExample);let A=s.every(b=>b.result.isValid)&&a.every(b=>b.isValid)&&u.every(({result:b})=>b.isValid);if(Object.keys(l).length===0){let b=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));b&&(l=b.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:l,errors:[...s.flatMap(({result:b})=>b.errors),...a.flatMap(b=>b.errors),...u.flatMap(({result:b})=>b.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 g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>gGm(m))){let m=d.findIndex(g=>MWl(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let b=MWl(A),C=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(C.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:C.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,g=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,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,l=c!==null,u=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:l,coerced:!1,usedProvidedExample:p,validExample:u,errors:l?[]: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(dGm);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:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,b]of Object.entries(g.mergedProperties))if(typeof b=="object"&&b!==null){let I=a[A];I!=null&&vUe(I)&&vUe(b)?a[A]={...I,...b}:a[A]=b}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&vUe(A)&&vUe(g)?a[m]={...A,...g}:a[m]=g}}}}let l={...o};for(let[p,d]of Object.entries(l)){let f=a[p];if(f==null||!vUe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(l[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in l||(l[p]=d);let u={mergedProperties:l,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,u),u}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>mGm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||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}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...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),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function LWl(e){return fC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Hr.primitive({v1:"BASE_64",v2:di.base64({})});case"BOOLEAN":return Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})});case"DATE":return Hr.primitive({v1:"DATE",v2:di.date({})});case"DATE_TIME":return Hr.primitive({v1:"DATE_TIME",v2:di.dateTime({})});case"DATE_TIME_RFC_2822":return Hr.primitive({v1:"DATE_TIME_RFC_2822",v2:di.dateTimeRfc2822({})});case"FLOAT":return Hr.primitive({v1:"FLOAT",v2:di.float({default:void 0,validation:void 0})});case"DOUBLE":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:void 0,validation:void 0})});case"UINT":return Hr.primitive({v1:"UINT",v2:di.uint({default:void 0,validation:void 0})});case"UINT_64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:void 0,validation:void 0})});case"INTEGER":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:void 0,validation:void 0})});case"LONG":return Hr.primitive({v1:"LONG",v2:di.long({default:void 0,validation:void 0})});case"STRING":return Hr.primitive({v1:"STRING",v2:di.string({default:void 0,validation:void 0})});case"UUID":return Hr.primitive({v1:"UUID",v2:di.uuid({})});case"BIG_INTEGER":return Hr.primitive({v1:"BIG_INTEGER",v2:di.bigInteger({default:void 0})});default:return}},unknown:()=>Hr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Hr.container(As.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Hr.container(As.list(t))},optional:t=>{if(t!=null)return Hr.container(As.optional(t))},nullable:t=>{if(t!=null)return Hr.container(As.nullable(t))},set:t=>{if(t!=null)return Hr.container(As.set(t))},literal:t=>Hr.container(As.literal(t._visit({string:r=>kE.string(r),boolean:r=>kE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var _Wl=h(()=>{"use strict";lo();zn();Bt()});var RSe,lKr=h(()=>{"use strict";zn();sc();Uo();RSe=class extends Ki{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:ic.enum({default:n!=null?r.find(i=>cr(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var uKr,UWl=h(()=>{"use strict";zn();Uo();Nct();CUe();uKr=class extends Ki{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=Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()}));return{type:ic.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Hr.container(As.map({keyType:Ki.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 c3(r.type,i),{type:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function qWl(e,t,r){let n=WWl(t,r),i={};for(let o of n)i=RGo(i,o);return vGm(i,e),i}function WWl(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let l of s)if("$ref"in l){if(t==null)continue;let u=l.$ref;if(n.has(u))continue;n.add(u);let p=t(l);p!=null&&c.push(p)}else c.push(l);i.push(...WWl(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function RGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||EGm.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]=IGm(o??{},i);continue}if(n==="items"){gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i;continue}if(VWl.includes(n)){gr(o)&&gr(i)?r[n]=HWl(o,i):r[n]=i;continue}if(GWl.includes(n)){r[n]=!!o||!!i;continue}if(yGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(bGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function IGm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i}return r}function HWl(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=HWl(o,i):r[n]=i}return r}function vGm(e,t){for(let r of AGm){let n=t[r];n!=null&&(e[r]=n)}for(let r of VWl){let n=t[r];n!=null&&(e[r]=n)}for(let r of GWl)t[r]===!0&&(e[r]=!0)}var AGm,VWl,GWl,yGm,bGm,EGm,KWl=h(()=>{"use strict";mt();AGm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],VWl=["example","default"],GWl=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],yGm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],bGm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],EGm=["allOf","oneOf","anyOf"]});var jct,kGo=h(()=>{"use strict";mt();zn();sc();cKr();Uo();Nct();jct=class extends Ki{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new kct({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:ic.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,l=n,u=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,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let D=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(D==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=D,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(R=>!this.schema.required?.includes(R))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let b=g.oneOf??g.anyOf;if(b!=null&&g.type==null&&g.properties==null){let D=new Set(r.map(R=>cr(R.name)));for(let[R,O]of b.entries()){let j=[...m,g.oneOf!=null?"oneOf":"anyOf",R.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:j}):O;if(Y==null)continue;let ee={};for(let[Te,pe]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(pe)&&"not"in pe||(ee[Te]=pe);let te=Object.keys(ee).filter(Te=>!D.has(Te));if(te.length===0)continue;let ce={};for(let Te of te){let pe=ee[Te];pe!=null&&(ce[Te]=pe,D.add(Te))}let{convertedProperties:le,inlinedTypesFromProperties:ae,referencedTypes:he,propertiesByAudience:xe}=xUe({properties:ce,required:[],breadcrumbs:j,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),l={...l,...ae},u={...u,...xe},he.forEach(Te=>{a.add(Te)})}continue}let I=g.properties??{};if(A){I={};for(let[D,R]of Object.entries(g.properties??{})){let O=p[D];O!=null&&!this.context.isReferenceObject(R)?I[D]={...O,...R}:I[D]=R}}let{convertedProperties:C,inlinedTypesFromProperties:x,referencedTypes:S,propertiesByAudience:P}=xUe({properties:I,required:[...this.schema.required??[],...g.required??[],...Hue(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...C),l={...l,...x},u={...u,...P},S.forEach(D=>{a.add(D)})}for(let d of Object.keys(l))a.add(d);return{type:ic.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(gs),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:u,referencedTypes:a,inlinedTypes:l,xmlEncoding:this.xmlEncoding}}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)}}});function CGm(e){return e.type==="union"&&e.types.length===0}function xGm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var SUe,FGo=h(()=>{"use strict";zn();TGo();OGo();PGo();Uo();Nct();lKr();pKr();CUe();SUe=class extends Ki{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 Bct({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!CGm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}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 l;if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});u.resolved&&(l=u.value)}else l=c;l!=null&&(l.enum!=null&&l.enum.length>1&&(l.type==="string"||l.type==null)?r=l:l.type==="string"&&l.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Rct({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new RSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}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}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?xGm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let l=s.$ref,u=l.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??u;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:l,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:u,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),b=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||b)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let C=new NT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let x=I&&p!=null&&!A;x&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=C.convert()}finally{x&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let P=this.context.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),D=d?.split("/").pop()??p,R=f?.title,O=f?.description,j=R??u??D;S.schema?.typeDeclaration!=null&&R!=null&&(S.schema.typeDeclaration.name.displayName=R),r.push({docs:O,discriminantValue:P,availability:S.availability,displayName:j,shape:eT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(D),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:j})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=xUe({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[u,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",u.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let u of Object.keys({...i,...a}))n.add(u);let l=new Dct({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:ic.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:l.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[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let b=this.getDiscriminatorKeyForRef(c);b!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:b,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let b=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=b.resolved?b.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let u=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new kSe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:u??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let b of Object.keys(m.inlinedTypes))r.add(b)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:ic.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}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=>!(typeof i=="object"&&i!==null&&"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 NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:ic.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 Hr.container(As.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 zct,NGo=h(()=>{"use strict";zn();Uo();zct=class extends Ki{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 Hr.container(As.literal(kE.string(t)));if(this.schema.format==="date-time-rfc-2822")return Hr.primitive({v1:ss.DateTimeRfc2822,v2:di.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Hr.primitive({v1:ss.Date,v2:di.date({})});if(this.schema.format==="date-time")return Hr.primitive({v1:ss.DateTime,v2:di.dateTime({})})}return Hr.primitive({v1:"STRING",v2:di.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"INTEGER",v2:di.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?Hr.container(As.literal(kE.boolean(t))):Hr.primitive({v1:"BOOLEAN",v2:di.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}}}});function wGm(e){let t=Hue(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var SGm,kSe,pKr=h(()=>{"use strict";mt();zn();Uo();Nct();_Wl();DSe();jGo();lKr();UWl();KWl();kGo();FGo();NGo();SGm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],kSe=class e extends Ki{static MAX_DISTRIBUTED_VARIANTS=64;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.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let l=this.tryConvertSiblingAnyOfConstraint();if(l!=null)return l;let u=this.tryConvertSiblingOneOfConstraint();if(u!=null)return u;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return c3(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new vC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new RSe({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 l;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;l=d}else l=c;let u=l.oneOf??l.anyOf;if(!this.context.isReferenceObject(c)&&u!=null&&l.type==null&&l.properties==null){let p={};for(let d of u){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(wGm(l))}if(i)return;let o=qWl(this.schema,n,c=>{let l=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(l!=null&&this.context.isReferenceObject(l)))return l}),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()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,l)=>c*l.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,l)=>l!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let l=this.getVariantTitle(c);return{...l!=null?{title:l}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new zct({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Qct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.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()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!Sze(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!wze(this.schema)||new vC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=Hue(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new SUe({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 uKr({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 SUe({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 jct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:Hr.unknown(),resolvedType:Hr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new vC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=LWl(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,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=[...SGm,...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 Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function OGm(e){return Object.keys(e).every(t=>TGm.has(t))}var NT,TGm,CUe=h(()=>{"use strict";zn();Uo();pKr();NT=class extends Ki{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??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}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??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>OGm(i))){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??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new kSe({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 Hr.container(As.optional(t))}wrapInNullable(t){return Hr.container(As.nullable(t))}},TGm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function xUe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},l=new Set;for(let[u,p]of Object.entries(e??{})){let d=[...r,"properties",u];if(typeof p!="object"){i.collect({message:`Schema property ${u} should be an object`,path:d});continue}let f=BGm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new NT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(u),wrapAsNullable:m}).convert();if(A!=null){let b=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:b?.default,xml:o?new Fct({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:b??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??PGm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{l.add(I)}),c3(A.type,l);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(a))l.add(u);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:l}}function PGm({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 l={};for(let[u,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${u}`,m=new Bw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();l[f]=g}return{userSpecifiedExamples:l,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Bw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function BGm(e,t,r){return r.isReferenceObject(t)?void 0:new vC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function c3(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":DGm(e.container,t);return}}function DGm(e,t){switch(e.type){case"list":c3(e.list,t);return;case"set":c3(e.set,t);return;case"optional":c3(e.optional,t);return;case"nullable":c3(e.nullable,t);return;case"map":c3(e.keyType,t),c3(e.valueType,t);return;case"literal":return}}var Nct=h(()=>{"use strict";DSe();CUe();cKr();Uo()});var Qct,jGo=h(()=>{"use strict";zn();Uo();Nct();CUe();Qct=class e extends Ki{static LIST_UNKNOWN=Hr.container(As.list(Hr.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 NT({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)})}),c3(r.type,n),{typeReference:Hr.container(As.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var zGo={};ne(zGo,{ArraySchemaConverter:()=>Qct,EnumSchemaConverter:()=>RSe,ObjectSchemaConverter:()=>jct,OneOfSchemaConverter:()=>SUe,PrimitiveSchemaConverter:()=>zct,SchemaConverter:()=>kSe,SchemaOrReferenceConverter:()=>NT});var QGo=h(()=>{"use strict";jGo();lKr();kGo();FGo();NGo();pKr();CUe()});var fKr,JWl=h(()=>{"use strict";xo();Uo();DSe();QGo();fKr=class extends Ki{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 NT({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,l])=>{if(this.context.isReferenceObject(l)){let u=this.context.resolveReference({reference:l,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return u.resolved?[c,u.value.value??u.value]:null}return[c,l.value??l]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new NT({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,l]of s){let u=this.context.resolveExampleWithValue(l),p=this.context.resolveExampleRecursively({example:l,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),u!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=u)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((l,u)=>{let p=`Example ${u+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ao(`${[...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}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}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 Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var dKr,YWl=h(()=>{"use strict";Uo();DSe();dKr=class extends Ki{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}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema: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:c,valueType:r??Ki.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??Ki.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Bw({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}}});var MGo={};ne(MGo,{AbstractMediaTypeObjectConverter:()=>fKr,AbstractParameterConverter:()=>dKr});var XWl=h(()=>{"use strict";JWl();YWl()});function Mct({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let l=RGm({context:e,header:c}),u=l?.schema,p=c.required===!0,d=b=>p?b:Hr.container(As.optional(b)),f=d(Ki.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(u!=null)if(m=e.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(Hr.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?di.integer({default:void 0,validation:void 0}):di.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})}));else{let b=new NT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:u,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(b!=null){f=b.type;for(let[I,C]of Object.entries(b.inlinedTypes))i[I]=C}}let A=kGm({context:e,breadcrumbs:o,header:c,headerName:s,schema:u,mediaTypeObject:l?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function RGm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&gp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function kGm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[l,u]of Object.entries(c??{})){let p=e.resolveExampleWithValue(u);p!=null&&(s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let l=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[l,u]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(u);if(p!=null){let d=e.generateUniqueName({prefix:l,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=xGt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=e.getExamplesFromSchema({schema:FGm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let u of l){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=xGt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(u)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=`${n}_example`;s.autogeneratedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function FGm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function xGt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Bw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var ZWl=h(()=>{"use strict";mt();zn();$Hr();DSe();CUe()});var mKr,$Wl=h(()=>{"use strict";AR();mKr=class extends Vo{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 e7l,NGm,l3,t7l=h(()=>{"use strict";mt();zn();wGo();$Wl();Uo();e7l="Base",NGm="x-fern-default-url",l3=class e extends Ki{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}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 l=e.getServerName({server:c,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((c,l,u)=>u.findIndex(p=>p.id===c.id)===l),s=[i,...o],a=this.servers.map(c=>{let l=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),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:l,name:this.context.casingsGenerator.generateName(l),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.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(gs);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.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 mKr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Pct({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?e7l:e.getServerExtensionName({server:this.servers[0],context:this.context})??e7l}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 l=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let u=this.extractFernDefaultUrlFromServer(c);u!=null&&(i[l]=u),o[l]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[l]=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[NGm];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 Tm={};ne(Tm,{AbstractConverters:()=>MGo,ExampleConverter:()=>Bw,SchemaConverters:()=>zGo,ServersConverter:()=>l3,convertResponseHeaders:()=>Mct});var LGo=h(()=>{"use strict";XWl();DSe();ZWl();QGo();t7l()});var SGt,r7l=h(()=>{"use strict";DSe();CGt();SGt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Bw({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 l=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid request example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:l.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let l=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid response example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:l.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}),l={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},u=this.validateEndpointExample({exampleToValidate:l}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=u.errors.length>0||u.warnings.length>0;!u.isValid||d||p?i.push({example:o,validationResult:u}):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||this.schemaHasPatternProperties(n))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}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...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),this.schemaHasPatternProperties(o,r)))return!0}}return!1}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,l]of Object.entries(t.paths)){if(!l)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let p of u){let d=l[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of b){n++;let C={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},x=this.validateEndpointExample({exampleToValidate:C});f.push(x),x.isValid?i++:(o++,I.source==="human"?s.push(x):I.source==="ai"&&a.push(x))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.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,l]of Object.entries(a.examples)){let u=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;u&&typeof u=="object"&&"value"in u&&i.push({name:c,source:"human",request:u.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let l=a.content?.["application/json"];if(l?.example!==void 0){let u=i.find(p=>p.request!==void 0&&p.response===void 0);u?(u.response=l.example,u.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:l.example,statusCode:s})}if(l?.examples)for(let[u,p]of Object.entries(l.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===u);f?(f.response=d.value,f.statusCode=s):i.push({name:u,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}}});function n7l({tags:e,errorCollector:t}){for(let r of e)if(Lct.test(r.name)){let n=[...r.name].filter(i=>Lct.test(i));t.collect({level:HE.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(Lct,"").trim()}".`})}}function i7l({description:e,path:t,errorCollector:r}){jGm.test(e)&&r.collect({level:HE.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 _Go({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");n7l({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 l=c;if(typeof l.description=="string"&&i7l({description:l.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(l.tags)&&!Array.isArray(e.tags)){for(let u of l.tags)if(typeof u=="string"&&!n.has(u)&&Lct.test(u)){n.add(u);let p=[...u].filter(d=>Lct.test(d));t.collect({level:HE.ERROR,message:`Tag name "${u}" 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 "${u}" to "${u.replace(Lct,"").trim()}".`})}}}}}}var Lct,jGm,o7l=h(()=>{"use strict";CGt();Lct=new RegExp("[^\\x00-\\x7F]"),jGm=/(?:^|\n)\s*---\s*(?:\n|$)/});var hKr,zGm,s7l=h(()=>{"use strict";hKr={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"},zGm=new Set(Object.values(hKr))});function UGo(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var a7l=h(()=>{"use strict"});var Uo=h(()=>{"use strict";$Hr();EWl();AR();zWl();LGo();LGo();CGt();r7l();DGo();o7l();s7l();a7l()});var QGm,MGm,c7l,l7l=h(()=>{"use strict";nn();QGm=Xt.object({type:Xt.string(),channelId:Xt.string().optional(),messageId:Xt.string(),value:Xt.any()}),MGm=Xt.object({summary:Xt.string().optional(),description:Xt.string().optional(),"query-parameters":Xt.record(Xt.string()).optional(),headers:Xt.record(Xt.string()).optional(),messages:Xt.array(QGm)}),c7l=Xt.array(MGm)});var gKr,u7l=h(()=>{"use strict";Uo();l7l();gKr=class extends Vo{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=c7l.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 _ct,VGo=h(()=>{"use strict";Uo();u7l();_ct=class extends Ki{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 gKr({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 LGm,rJ,wGt=h(()=>{"use strict";zn();Uo();LGm="x-fern-server-name",rJ=class e extends Ki{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,baseUrlEnvVar:void 0,environments:DE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[LGm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var FSe,GGo=h(()=>{"use strict";Uo();FSe=class extends Tm.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 vC.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 Tm.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 AKr,p7l=h(()=>{"use strict";Uo();AKr=class extends Vo{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 NSe,qGo=h(()=>{"use strict";Uo();NSe=class extends Vo{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 jSe,WGo=h(()=>{"use strict";Uo();jSe=class extends Vo{node;key="x-fern-explorer";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){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var yKr,f7l=h(()=>{"use strict";Uo();yKr=class extends Vo{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 bKr,d7l=h(()=>{"use strict";zn();sc();Uo();xo();VGo();wGt();GGo();p7l();qGo();WGo();f7l();bKr=class extends _ct{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 NSe({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 u=new AKr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(u??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=zy(p),m=ao(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,b=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),C=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??b;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"})},apiPlayground:C},audiences:g,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=Qze(ao(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();u!=null&&u.schema!=null&&(i=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let l=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(l!=null){let p=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:l,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let l=i,u=Hr.named({fernFilepath:t.createFernFilepath(),name:l.typeDeclaration.name.name,typeId:l.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=$P.reference({bodyType:u,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new NSe({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 FSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).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 FSe({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},parameterNamePrefix:this.channelPath}).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 rJ.getServerName(t,n)}return t}getOperationMethodName(t){return new yKr({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 FSe({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},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var EKr,m7l=h(()=>{"use strict";wGt();EKr=class extends rJ{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 HGo,h7l,KGo,IKr,g7l=h(()=>{"use strict";zn();sc();Bt();VGo();wGt();GGo();qGo();WGo();HGo="$message.",h7l="#/channels/",KGo="#/servers/",IKr=class extends _ct{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 NSe({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((A,[b,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[b]=I)}catch{}return A},{}),a=[];for(let[A,b]of Object.entries(s)){let C=new NSe({breadcrumbs:[...this.breadcrumbs,A],node:b,context:this.context}).convert()??A;for(let x of b.messages){let S=this.context.convertReferenceToTypeReference({reference:x});if(S.ok){let P=this.resolveMessageDocs(x)??b.description,D=$P.reference({bodyType:S.reference,docs:P});a.push({type:A,displayName:C,origin:b.action==="send"?"client":"server",body:D,availability:this.context.getAvailability({node:b,breadcrumbs:this.breadcrumbs}),docs:P,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),l=this.transformToValidPath(this.channel.address??this.channelPath),u=zy(l),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new jSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:u,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:l,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},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(KGo,""),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:l}=a,p=new FSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:l,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(HGo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${HGo} prefix`,path:this.breadcrumbs});return}let i=r.substring(HGo.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}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(KGo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(KGo.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 rJ.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 rJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(h7l))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(h7l.length)}}});var vKr,A7l=h(()=>{"use strict";wGt();vKr=class extends rJ{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 TGt,y7l=h(()=>{"use strict";zn();sc();Uo();d7l();m7l();g7l();A7l();TGt=class extends tJ{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.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();let t=this.context.spec.info?.version?.trim();return t&&(this.ir.specVersion=t),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 l=`${r}_${i}`;this.convertSchema({id:l,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 Tm.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 vKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new EKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=G5t({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 kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return kp.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,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return kp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:Ki.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new vC.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 IKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new bKr({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 OGt,b7l=h(()=>{"use strict";zn();Uo();OGt=class extends Yb{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 l=a[1],u=a[2];return o=`${l}_${u}`,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:Hr.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:Hr.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:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var E7l=h(()=>{"use strict";y7l();b7l()});function UGm(e){let t=new Set,r,n=new RegExp(_Gm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var _Gm,CKr,I7l=h(()=>{"use strict";Uo();_Gm=/\{([^}]+)\}/g,CKr=class extends Vo{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")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=UGm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let l=o[c];if(l==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof l!="object"||Array.isArray(l)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let u=l,p=typeof u.type=="string"?u.type:"string",d=typeof u.docs=="string"?u.docs:void 0;s.push({name:c,type:p,default:u.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var xKr,v7l=h(()=>{"use strict";Uo();xKr=class extends Vo{document;key="x-fern-base-url-env";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"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var SKr,C7l=h(()=>{"use strict";Uo();SKr=class extends Vo{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 VGm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var wKr,x7l=h(()=>{"use strict";Uo();wKr=class extends Vo{document;key="x-fern-global-parameters";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)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:VGm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function GGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function S7l({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:Ki.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:Ki.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:GGm(i.default),defaultValue:i.default})}return r}var w7l=h(()=>{"use strict";zn();Uo()});function qGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function T7l({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ki.OPTIONAL_STRING:Ki.STRING,env:r.env,v2Examples:r.optional?void 0:WGm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:qGm(r["x-fern-default"]),defaultValue:void 0}))}function WGm({header:e,context:t}){let r=new Bw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var O7l=h(()=>{"use strict";zn();Uo()});function HGm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return $t.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return $t.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return $t.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function KGm(e,t,r){switch(e){case void 0:case"body":return $t.GlobalParameterLocation.Body;case"query":return $t.GlobalParameterLocation.Query;case"header":return $t.GlobalParameterLocation.Header;case"path":return $t.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),$t.GlobalParameterLocation.Body}}function JGm(e,t,r){switch(e){case void 0:return;case"explicit":return $t.GlobalParameterApplyMode.Explicit;case"auto":return $t.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function YGm(e,t){let r=XGm(e);return t===!0?$t.TypeReference.container($t.ContainerType.optional(r)):r}function XGm(e){switch(e){case"boolean":return $t.TypeReference.primitive({v1:"BOOLEAN",v2:$t.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return $t.TypeReference.primitive({v1:"INTEGER",v2:$t.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return $t.TypeReference.primitive({v1:"DOUBLE",v2:$t.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return Ki.STRING}}function ZGm(e){return e.target!=null?e.target:e.name}function P7l({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=KGm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:ZGm(n),valueType:YGm(n.type,n.optional),env:n.env,clientDefault:HGm(n.default,n.type,o,t),optional:n.optional,apply:JGm(n.apply,[...o,"apply"],t),docs:n.docs}})}var B7l=h(()=>{"use strict";zn();Uo()});var TKr,D7l=h(()=>{"use strict";mt();Uo();TKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&gp.parse(t)?.isJSON())return r.schema}}}});function e9m({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return $Gm[e.contentType]}}var OKr,$Gm,R7l=h(()=>{"use strict";mt();zn();sc();Uo();OKr=class extends Tm.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:l,queryParameters:u}){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=l,this.queryParameters=u??[]}get bodyRequired(){return this.required===!1?!1:void 0}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(gp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=gp.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=gp.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:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:md.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}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,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 l=this.context.resolveExampleWithValue(c),u=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(u)){let d=u.summary;s.has(d)||(p=d)}s.add(p),l!=null&&(i.userSpecifiedExamples[p]=l)}return{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:Hr.unknown(),required:this.bodyRequired,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:md.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[cr(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:md.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?kx.file(eQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.file(eQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.bodyProperty({...t,contentType:n?.contentType??r,style:e9m({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)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({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}})}}buildStreamConditionRequestBody({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 l=c.schema?.typeDeclaration.shape;return l?.type==="object"?{requestBody:md.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:l.extendedProperties,extends:l.extends,properties:l.properties,extraProperties:l.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:md.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,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=>cr(n.name).toLowerCase()));return t.some(n=>r.has(cr(n.name).toLowerCase()))}},$Gm={"application/json":"json"}});function n9m(e){return e?.header!=null}var t9m,r9m,Uct,JGo=h(()=>{"use strict";mt();zn();sc();Uo();xo();D7l();R7l();t9m=/{([^}]+)}/g,r9m=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Uct=class extends Ki{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return gm.Get;case"post":return gm.Post;case"put":return gm.Put;case"delete":return gm.Delete;case"patch":return gm.Patch;case"head":return gm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let l=new TKr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(l!=null)switch(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type){case"path":r.push(l.parameter);break;case"query":n.push(l.parameter);break;case"header":{let u=jr(l.parameter.name),p=cr(l.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(n9m(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!r9m.has(u.toLowerCase())&&!d&&i.push(l.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll(t9m)].map(i=>i[1]).filter(i=>!t.some(o=>jr(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:Ki.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,l]of Object.entries(s.content)){let p=new OKr({context:this.context,breadcrumbs:t,contentType:c,mediaType:l,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,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new vC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new vC.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?ao(this.operation.summary):ao(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ao(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=D7(t,n),o=D7(r,n);return qv(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ao(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Tm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Vct,YGo=h(()=>{"use strict";zn();JGo();Vct=class extends Uct{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}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 l=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,u,p;if(c.type==="inlinedRequestBody")u=tT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=tT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=tT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:l,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:p,responses:d.length>0?d: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 k7l,F7l=h(()=>{"use strict";k7l=["get","post","put","delete","patch","head"]});var PKr,N7l=h(()=>{"use strict";Uo();PKr=class extends Vo{operation;key="x-fern-global-parameter";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;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var BKr,j7l=h(()=>{"use strict";Uo();BKr=class extends Vo{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}}}});var i9m,o9m,s9m,a9m,XGo,z7l=h(()=>{"use strict";nn();i9m=Xt.object({cursor:Xt.string(),next_cursor:Xt.string(),results:Xt.string()}),o9m=Xt.object({offset:Xt.string(),results:Xt.string(),step:Xt.string().optional(),"has-next-page":Xt.string().optional()}),s9m=Xt.object({next_uri:Xt.string(),results:Xt.string()}),a9m=Xt.object({next_path:Xt.string(),results:Xt.string()}),XGo=Xt.union([Xt.boolean(),i9m,o9m,s9m,a9m])});var ZGo,zSe,DKr,Q7l=h(()=>{"use strict";Uo();z7l();ZGo="$request.",zSe="$response.",DKr=class extends Vo{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=XGo.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=XGo.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:Yb.maybeTrimPrefix(r.cursor,ZGo),nextCursor:Yb.maybeTrimPrefix(r.next_cursor,zSe),results:Yb.maybeTrimPrefix(r.results,zSe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:Yb.maybeTrimPrefix(n.next_uri,zSe),results:Yb.maybeTrimPrefix(n.results,zSe)};let i=t;if("next_path"in i)return{type:"path",nextPath:Yb.maybeTrimPrefix(i.next_path,zSe),results:Yb.maybeTrimPrefix(i.results,zSe)};let o=t;return{type:"offset",offset:Yb.maybeTrimPrefix(o.offset,ZGo),results:Yb.maybeTrimPrefix(o.results,zSe),step:o.step!=null?Yb.maybeTrimPrefix(o.step,ZGo):void 0,hasNextPage:o["has-next-page"]!=null?Yb.maybeTrimPrefix(o["has-next-page"],zSe):void 0}}}});function $Go(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var c9m,l9m,u9m,RKr,M7l=h(()=>{"use strict";Uo();nn();c9m="$request.",l9m=Xt.object({"stream-condition":Xt.string().optional(),format:Xt.enum(["sse","json"]).optional(),"stream-description":Xt.string().optional(),"stream-request-name":Xt.string().optional(),"response-stream":Xt.any(),response:Xt.any(),terminator:Xt.string().optional(),resumable:Xt.boolean().optional()}),u9m=Xt.union([Xt.boolean(),l9m]),RKr=class extends Vo{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=u9m.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,resumable:!1}:void 0;let n=r.data.resumable??$Go(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};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:Yb.maybeTrimPrefix(r.data["stream-condition"],c9m),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var kKr,L7l=h(()=>{"use strict";Uo();kKr=class extends Vo{operation;key="x-fern-subtitle";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!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var FKr,_7l=h(()=>{"use strict";Uo();FKr=class extends Vo{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}}}});function p9m(e){return oi(e)&&typeof e.$ref=="string"}function f9m(e,t){if(e!=null){if(typeof e=="string")return e;if(p9m(e)){let r=(0,U7l.resolve)(t??process.cwd(),e.$ref);if((0,jKr.existsSync)(r))try{return(0,jKr.readFileSync)(r,"utf-8")}catch{return}}}}var jKr,U7l,NKr,V7l=h(()=>{"use strict";mt();Uo();jKr=require("fs"),U7l=require("path");NKr=class extends Vo{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=oi(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(!oi(c))continue;let l=c,u=l.lang,p=l.label,d=l.source;if(typeof u!="string")continue;let f=f9m(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:u,language:u,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function d9m(e){return oi(e)&&typeof e.$ref=="string"}function m9m(e,t){if(e!=null){if(typeof e=="string")return e;if(d9m(e)){let r=(0,G7l.resolve)(t??process.cwd(),e.$ref);if((0,QKr.existsSync)(r))try{return(0,QKr.readFileSync)(r,"utf-8")}catch{return}}}}function h9m(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=m9m(n.code,t);o!=null&&r.push({...n,code:o})}return r}var QKr,G7l,zKr,q7l=h(()=>{"use strict";mt();lo();Uo();QKr=require("fs"),G7l=require("path");zKr=class extends Vo{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(!oi(o))return o;let a=o["code-samples"];if(a!=null){let c=h9m(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=Qd.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 PGt,W7l=h(()=>{"use strict";Uo();PGt=class extends Vo{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}}}});var BGt,H7l=h(()=>{"use strict";mt();zn();Uo();BGt=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;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(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}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,contentType:o})}}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:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:kl.streaming(rv.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:kl.streaming(rv.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,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:kl.streaming(rv.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:kl.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:kl.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:kl.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:gp.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}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 gp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var MKr,K7l=h(()=>{"use strict";mt();zn();Uo();MKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;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)return this.constructSchemalessErrorOutput();let t=Object.keys(this.responseError.content).filter(n=>n.includes("json"));if(t.length===0)return this.constructSchemalessErrorOutput();let 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:G6(`${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})}}constructSchemalessErrorOutput(){let t=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(t==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let r=this.getErrorIdFromErrorName(t),n={error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:r},docs:this.responseError.description},i=this.convertResponseHeaders();return{error:n,errorType:Hr.unknown(),displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:{},headers:i.headers}}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,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}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}),l=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(l),a!=null&&(i[l]=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 hKr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?G6(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var LKr,J7l=h(()=>{"use strict";lo();zn();sc();W5();Uo();xo();V7l();q7l();W7l();H7l();K7l();JGo();LKr=class e extends Uct{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:l,idToAuthScheme:u,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=l,this.idToAuthScheme=u,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=u?.[0]?.requestBody,d=u?.[0]?.streamRequestBody,f=u?.[0]?.inlinedPropertiesByAudience,m={requestBodies:u?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,b=g?.streamResponse,I=g!=null?g.errors:[],C={},x=I.map(ue=>ue.error),S=zy(this.path),P=this.context.perSpecBasePath,D=this.getEndpointBaseUrl(),R=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:D});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&u!=null&&u.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:u,httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let j=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(j));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,je=Pe.error.errorId,_e=ue.examples;C[je]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let ee=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ce=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),he=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ce,xe={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:D,v2BaseUrls:R,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(je=>cr(je.name)===cr(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:x,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:P!=null?zy(P):void 0,fullPath:P!=null?zy(`${P}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:HD.openapi(),audiences:ee,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:he},Te=this.context.namespace!=null?[this.context.namespace]:[],pe=r?.map(ue=>ao(ue));return Te.push(...pe??[]),{audiences:ee,group:r,groupDisplayName:i,groupDescription:o,errors:C,endpoint:{...xe,id:`endpoint_${Te.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:b!=null&&b.body!=null?{...xe,id:`endpoint_${Te.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:b,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:b.body,docs:b.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:l}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,l]of Object.entries(this.operation.responses)){let u=/^[45]XX$/i.test(c),p,d=!1;if(u)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:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new BGt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new MKr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:u?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let l=new BGt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:l.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:l.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 l=c.value.responseBodyType;(l.type!=="container"||l.container.type!=="optional")&&(o.response={...o.response,body:kl.json(K0.response({...c.value,responseBodyType:Hr.container(As.optional(l))}))})}}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.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():UGo(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&rnt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())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:Ki.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue: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 zKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new NKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],l=o.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?o:[...o,...a];return l.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}),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[l,u]of c){let p=this.context.resolveExampleWithValue(u);p!=null&&(s[l]={displayName:void 0,contentType: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:$t.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,l=c.contentType,u=c.v2Examples;if(u==null)continue;let p=u.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=l!=null?s.get(l):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&l!=null?`${f} (${l})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:l??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,l]of c){let u=this.context.resolveExampleWithValue(l);if(u!=null){t.set(s,{docs:void 0,statusCode:i,body:$t.V2HttpEndpointResponseBody.json(u)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(l=>!(l.response!=null&&"stream"in l.response)),s=i.filter(l=>l.response!=null&&"stream"in l.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,contentType: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 $t.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return $t.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new vC.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 "${un.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 l3.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return l3.getServerName({server:a,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],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ao(r)===ao(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ao(r)===ao(n))return this.context.getDescriptionForTag(r)}}});var e9o,_Kr,Y7l=h(()=>{"use strict";Uo();e9o=Ae(zUt(),1);F7l();N7l();j7l();Q7l();M7l();L7l();_7l();J7l();YGo();_Kr=class extends Ki{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of k7l){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 l=new RKr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();l==null&&this.operationHasTextEventStreamResponse(o)&&(l={type:"stream",format:"sse",terminator:void 0,resumable:$Go(this.context.spec)??!1});let u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:l});u!=null&&(t.push(u),Object.assign(n,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new FKr({breadcrumbs:n,operation:t,context:i}).convert()?new Vct({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).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 DKr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new BKr({breadcrumbs:n,operation:t,context:this.context}).convert(),u=new kKr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new PKr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new LKr({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:u,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var UKr,X7l=h(()=>{"use strict";zn();Uo();UKr=class extends Ki{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(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return kp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return kp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:Ki.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function g9m(e){if(e!=null){if(typeof e=="string")return kE.string(e);if(typeof e=="boolean")return kE.boolean(e)}}var Z7l,DGt,$7l=h(()=>{"use strict";mt();lo();zn();sc();W5();Uo();Z7l=Ae(zUt(),1);I7l();v7l();C7l();x7l();w7l();O7l();B7l();YGo();Y7l();X7l();DGt=class extends tJ{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}),this.context.spec=QUt({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),_Go({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),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();i&&i!=='""'&&(this.ir.apiDisplayName=i);let o=this.context.spec.info?.version?.trim();return o&&(this.ir.specVersion=o),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=S7l({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new SKr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=T7l({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new wKr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=P7l({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new CKr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Xh(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=zy(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:Ki.STRING,docs:n.docs,location:$t.PathParameterLocation.Root,variable:void 0,clientDefault:g9m(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=jUt({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=G5t({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}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 UKr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new xKr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=q5t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.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 Vct({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:Z7l.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new _Kr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let l of c.servers)this.shouldAddServerToCollectedServers({server:l,currentServers:t})&&t.push(l);if(c.errors)for(let[l,u]of Object.entries(c.errors))r[l]=u}for(let c of a.webhooks){let l=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:l.join("."),group:l,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&rnt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],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!=null&&i.security.length>0&&delete i.security}}}}});var VKr,eHl=h(()=>{"use strict";Uo();VKr=class extends Vo{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 wUe,tHl=h(()=>{"use strict";zn();sc();Uo();eHl();wUe=class extends Yb{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;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 l;if(o.includes("/")){let p=new Tm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(l={[o]:p.convertedSchema})}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:l}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>cr(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new VKr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function r9o({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=Ode(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>y9m({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function y9m({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=rHl({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],l=n["response-properties"],u=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-id"],"client_id")}),p=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-secret"],"client_secret")}),d=Gct({ir:e,endpoint:o,wireValue:nJ(l?.["access-token"],"access_token")});if(!(u==null||p==null||d==null))return kp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:qD.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:u,clientSecret:p,scopes:void 0,customProperties:I9m({ir:e,endpoint:o,excludeWireValues:[nJ(c?.["client-id"],"client_id"),nJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?b9m({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function b9m({ir:e,refreshTokenConfig:t}){let r=rHl({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=t9o({ir:e,endpoint:n,wireValue:nJ(s?.["refresh-token"],"refresh_token")}),l=Gct({ir:e,endpoint:n,wireValue:nJ(a?.["access-token"],"access_token")});if(!(c==null||l==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:l,expiresIn:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["refresh-token"],"refresh_token")})}}}function rHl({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=A9m[r[0]?.toUpperCase()??""],i=Xh(r[1]);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(E9m(a.fullPath)===i){let l=Object.entries(e.subpackages).find(([,u])=>u.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:l}}}}function E9m(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Xh(t)}function nJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function nHl(e,t){return e.find(r=>cr(r.name)===t)}function n9o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function t9o({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?nHl(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:XP.body({...i})}}function I9m({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(cr(s.name))).map(s=>({propertyPath:void 0,property:XP.body({...s})}));return o.length>0?o:void 0}function Gct({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=n9o(e,n.typeId),o=i!=null?nHl(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var A9m,iHl=h(()=>{"use strict";mt();lo();zn();sc();A9m={GET:gm.Get,POST:gm.Post,PUT:gm.Put,PATCH:gm.Patch,DELETE:gm.Delete}});var i9o=h(()=>{"use strict";$7l();tHl();iHl()});var qct,o9o=h(()=>{"use strict";Uo();qct=class extends Vo{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}}}});var v9m,C9m,x9m,GKr,oHl=h(()=>{"use strict";mt();Uo();nn();v9m=Xt.object({description:Xt.string().optional(),required:Xt.boolean().optional(),deprecated:Xt.boolean().optional(),allowEmptyValue:Xt.boolean().optional(),style:Xt.string().optional(),explode:Xt.boolean().optional(),allowReserved:Xt.boolean().optional(),schema:Xt.any().optional(),example:Xt.any().optional(),examples:Xt.record(Xt.string(),Xt.any()).optional(),content:Xt.record(Xt.string(),Xt.any()).optional()}),C9m=v9m.extend({name:Xt.string(),in:Xt.string()}),x9m=Xt.array(C9m),GKr=class extends Vo{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 x9m.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${rn(r)}`,path:this.breadcrumbs});return}}}});var qKr,sHl=h(()=>{"use strict";zn();sc();Uo();o9o();qKr=class extends Ki{method;pathParameters;queryParameters;headers;topLevelServers;globalApiPlayground;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[],globalApiPlayground:c}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a,this.globalApiPlayground=c}convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${jr(l.name)}}`;let n=zy(r),i=[];for(let[l,u]of this.method.params.entries()){let p;if(this.context.isReferenceObject(u)){let g=this.context.resolveReference({reference:u});if(g.resolved)p=g.value;else continue}else p=u;let d=[this.method.name,"Param",p.name].join("_"),m=new Tm.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:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,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 l=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),p=[this.method.name,"Result"].join("_"),d=u.convert();d!=null&&(o={docs:l.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,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?md.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:kl.json(K0.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(r)},transport:void 0,availability:void 0,source:HD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:this.convertApiPlayground(),responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertApiPlayground(){return new qct({breadcrumbs:[...this.breadcrumbs,this.method.name],document:this.method,context:this.context}).convert()??this.globalApiPlayground}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return $t.OpenRpcParamStructure.ByName;case"by-position":return $t.OpenRpcParamStructure.ByPosition;case"either":return $t.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}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 l3.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[jr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let u=this.context.resolveReference({reference:o});if(u.resolved)s=u.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let u=this.context.resolveReference({reference:s.result});u.resolved&&(a=u.value)}else a=s.result;let c=s.name??`Example ${i+1}`,l=[];if(s.params&&Array.isArray(s.params)){l=[];for(let u of s.params)if(this.context.isReferenceObject(u)){let p=this.context.resolveReference({reference:u});if(p.resolved)l.push(p.value);else continue}else l.push(u)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(l)},response:{docs:void 0,statusCode:void 0,body:a?.value!==void 0?$t.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var WKr,aHl=h(()=>{"use strict";Uo();WKr=class extends Tm.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 Tm.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 RGt,cHl=h(()=>{"use strict";Uo();o9o();oHl();sHl();aHl();RGt=class extends tJ{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 l3({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 Tm.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 GKr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[l,u]of n.entries()){let d=new WKr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${l}]`],parameter:u}).convert();if(d!=null)switch(d.type){case"path":{i.push(d.parameter);break}case"query":{o.push(d.parameter);break}case"header":{s.push(d.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),c=new qct({breadcrumbs:[],document:this.context.spec,context:this.context}).convert();for(let l of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:["methods"]});if(u==null)continue;let d=new qKr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers,globalApiPlayground:c}).convert();if(d!=null&&(this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(d.inlinedTypes),d.servers))for(let f of d.servers)this.shouldAddServerToCollectedServers({server:f,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(f))}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 kGt,lHl=h(()=>{"use strict";zn();Uo();kGt=class extends Yb{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=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:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var uHl=h(()=>{"use strict";cHl();lHl()});var pHl,fHl=h(()=>{"use strict";pHl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function S9m(e){return typeof e=="string"&&pHl.test(e)}var s9o,dHl=h(()=>{"use strict";fHl();s9o=S9m});function mHl(e,t=0){return(EB[e[t+0]]+EB[e[t+1]]+EB[e[t+2]]+EB[e[t+3]]+"-"+EB[e[t+4]]+EB[e[t+5]]+"-"+EB[e[t+6]]+EB[e[t+7]]+"-"+EB[e[t+8]]+EB[e[t+9]]+"-"+EB[e[t+10]]+EB[e[t+11]]+EB[e[t+12]]+EB[e[t+13]]+EB[e[t+14]]+EB[e[t+15]]).toLowerCase()}var EB,hHl=h(()=>{"use strict";EB=[];for(let e=0;e<256;++e)EB.push((e+256).toString(16).slice(1))});function a9o(){return crypto.getRandomValues(w9m)}var w9m,gHl=h(()=>{"use strict";w9m=new Uint8Array(16)});function T9m(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():O9m(e,t,r)}function O9m(e,t,r){e=e||{};let n=e.random??e.rng?.()??a9o();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return mHl(n)}var Dw,AHl=h(()=>{"use strict";gHl();hHl();Dw=T9m});var TUe=h(()=>{"use strict";AHl();dHl()});async function Wct({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,yHl.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Er.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return QX({data:t,overrides:i,allowNullKeys:n})}var yHl,HKr=h(()=>{"use strict";mt();Bt();yHl=require("fs/promises");Ko()});async function c9o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,bHl.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Er.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await Wct({absoluteFilePathToOverrides:a,context:e,data:s});return s}var bHl,EHl=h(()=>{"use strict";bHl=require("fs/promises");Ko();HKr()});async function l9o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await P9m(Zt.of(r.schema)):r.schema;return{document:Bjo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function P9m(e){let t=(await(0,IHl.readFile)(e)).toString(),r=Er.load(t);if(!gr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var IHl,vHl=h(()=>{"use strict";vc();mt();tr();Bt();IHl=require("fs/promises");Ko()});var xHl=E((UUv,CHl)=>{"use strict";function B9m(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}CHl.exports=B9m()});var THl=E((VUv,wHl)=>{"use strict";var SHl=xHl();wHl.exports=function(t,r){if(t){r.then(function(n){SHl(function(){t(null,n)})},function(n){SHl(function(){t(n)})});return}else return r}});var p9o=E((GUv,PHl)=>{"use strict";var u9o=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},KKr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function OHl(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new KKr(t,r,e);throw Error.captureStackTrace(n,OHl),n}}PHl.exports={ERR_INVALID_ARG_TYPE:KKr,assertIsObject:OHl,DebounceTimers:u9o}});var RHl=E((qUv,DHl)=>{"use strict";var{assertIsObject:BHl}=p9o();function D9m(e){return BHl(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,BHl(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function R9m(e,t){e=D9m.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}DHl.exports={initializeTLSOptions:R9m}});var ZKr=E((HUv,jHl)=>{"use strict";var{URL:JKr}=require("url"),{EventEmitter:FHl}=require("events"),YKr=require("util")._extend,{DebounceTimers:k9m,assertIsObject:kHl,ERR_INVALID_ARG_TYPE:WUv}=p9o(),{initializeTLSOptions:F9m}=RHl(),FGt=require("http"),f9o=require("https"),{Stream:N9m}=require("stream");function XKr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var _me=[];XKr(_me,FGt.ClientRequest);XKr(_me,FGt.OutgoingMessage);XKr(_me,FHl);XKr(_me,N9m);var j9m=["httpVersionMajor","httpVersionMinor","httpVersion"],z9m=["host","connection"],QSe=Symbol("stubs");function NGt(){this.http2Mimic=!0,this[QSe]=[];for(var e=0;e<_me.length;e++){let l=_me[e];NGt.prototype[l]||(this[l]=function(){return this.genericStubber(l,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof jGt;var s,a;if(o){let l=arguments[0];l.method&&(s=l.method),l.protocol&&(a=l.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=d9o(new JKr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=YKr(d9o(new JKr(n)),t):t=YKr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}NGt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?LSe.globalManager:_Se.globalManager:MSe.globalManager},genericStubber(e,t){return this[QSe]?(this[QSe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[QSe])this[QSe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<_me.length;t++){let n=_me[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[QSe].length;n++){var r=this[QSe][n];e[r[0]](...r[1])}this[QSe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(_me),i=Object.keys(this),o=[].concat(j9m);i.forEach(function(l){n.indexOf(l)==-1&&o.indexOf(l)==-1&&o.push(l)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],l=s[c],u;l||(u=!0),l&&(l.writable||l)&&(u=!0),u&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var MSe=class e extends FHl{constructor(t){super(),this.httpsAgent=f9o.globalAgent,this.httpAgent=FGt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new k9m(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new jGt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new NGt(i)}get(){var t=new jGt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var l={createConnection(){return o}};if(c=="h2"&&this.http2Support){var u=this.http2.connect(r,l);this.setHttp2Client(t,u)}else this.cachedHTTP1Result[t]=Date.now();n(null,l),this.emit(i,l)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof JKr&&(n=d9o(n));let s=YKr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(u){this.emit("http1.response",u)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=YKr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{z9m.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let l,u=0;c.on("data",function(f){u+=f.length,u>=l&&s.unpauseAndTime(t)}),r.take(c);function p(d){l=parseInt(d["content-length"]),l<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),kHl(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new JKr(t)),kHl(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,F9m.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function d9o(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var jGt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},LSe=class extends MSe{constructor(){super(...arguments),this.Agent=f9o.Agent,this.globalAgent=f9o.globalAgent,this.enforceProtocol="https:"}},Q9m=new LSe;LSe.globalManager=Q9m;LSe.Manager=LSe;var _Se=class extends MSe{constructor(){super(...arguments),this.Agent=FGt.Agent,this.globalAgent=FGt.globalAgent,this.enforceProtocol="http:"}},M9m=new _Se;_Se.globalManager=M9m;_Se.Manager=_Se;var NHl=new MSe;NHl.enforceProtocol="detect";MSe.globalManager=NHl;jHl.exports={HttpRequest:_Se,HttpsRequest:LSe,HTTP2OutgoingMessage:NGt,ClientRequest:NGt,HttpRequestManager:MSe}});var QHl=E((KUv,zHl)=>{"use strict";var{HttpRequest:L9m,ClientRequest:_9m}=ZKr(),zGt=L9m.globalManager,U9m=zGt.request.bind(zGt),V9m=zGt.get.bind(zGt),G9m=Object.assign({},require("http"));zHl.exports=Object.assign(G9m,{ClientRequest:_9m,globalManager:zGt,request:U9m,get:V9m})});var LHl=E((JUv,MHl)=>{"use strict";var{HttpsRequest:q9m,ClientRequest:W9m}=ZKr(),QGt=q9m.globalManager,H9m=QGt.request.bind(QGt),K9m=QGt.get.bind(QGt),J9m=Object.assign({},require("https"));MHl.exports=Object.assign(J9m,{ClientRequest:W9m,globalManager:QGt,request:H9m,get:K9m})});var UHl=E((YUv,_Hl)=>{"use strict";var{HttpRequestManager:m9o,HTTP2OutgoingMessage:Y9m,ClientRequest:X9m}=ZKr(),Z9m=QHl(),$9m=LHl(),MGt=new m9o;m9o.globalManager=MGt;var eqm=MGt.request.bind(MGt),tqm=MGt.get.bind(MGt);_Hl.exports={HTTP2OutgoingMessage:Y9m,ClientRequest:X9m,globalManager:m9o.globalManager,request:eqm,get:tqm,http:Z9m,https:$9m}});var C9o={};ne(C9o,{FetchError:()=>yR,Headers:()=>d8,Request:()=>VSe,Response:()=>vre,default:()=>fqm});function yR(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function jT(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:KHl(e)?e=Buffer.from(e.toString()):e instanceof BUe?e=e[PUe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof iJ.default||(e=Buffer.from(String(e)))),this[Vme]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof iJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new yR(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[Vme].error=c})}function Hct(){var e=this;if(this[Vme].disturbed)return jT.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[Vme].disturbed=!0,this[Vme].error)return jT.Promise.reject(this[Vme].error);if(this.body===null)return jT.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return jT.Promise.resolve(this.body);if(!(this.body instanceof iJ.default))return jT.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new jT.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new yR(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new yR(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new yR(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new yR(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function rqm(e,t){if(typeof y9o!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),y9o(e,"UTF-8",n).toString()}function KHl(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function JHl(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof iJ.default&&typeof n.getBoundary!="function"&&(t=new VHl,r=new VHl,n.pipe(t),n.pipe(r),e[Vme].body=t,n=r),n}function YHl(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":KHl(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof BUe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof iJ.default?null:"text/plain;charset=UTF-8"}function XHl(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function nqm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function LGt(e){if(e=`${e}`,ZHl.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function GHl(e){if(e=`${e}`,b9o.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function Jct(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function E9o(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[CC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[CC][n].join(", ")}:function(n){return[n.toLowerCase(),e[CC][n].join(", ")]})}function g9o(e,t){let r=Object.create(v9o);return r[I9o]={target:e,kind:t,index:0},r}function iqm(e){let t=Object.assign({__proto__:null},e[CC]),r=Jct(e[CC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function oqm(e){let t=new d8;for(let r of Object.keys(e))if(!ZHl.test(r))if(Array.isArray(e[r]))for(let n of e[r])b9o.test(n)||(t[CC][r]===void 0?t[CC][r]=[n]:t[CC][r].push(n));else b9o.test(e[r])||(t[CC][r]=[e[r]]);return t}function $Kr(e){return typeof e=="object"&&typeof e[Ume]=="object"}function lqm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function uqm(e){let t=e[Ume].parsedURL,r=new d8(e[Ume].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof iJ.default.Readable&&!cqm)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=XHl(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:iqm(r),agent:e.agent})}function _Gt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function USe(e,t){if(!USe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return jT.Promise=USe.Promise,new USe.Promise(function(r,n){let i=new VSe(e,t),o=uqm(i),s=HHl.default.request,a=i.signal,c=null,l=function(){let g=new _Gt("The user aborted a request.");n(g),i.body&&i.body instanceof iJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){l();return}let u=function(){l(),f()},p=s(o),d;a&&a.addEventListener("abort",u);function f(){p.abort(),a&&a.removeEventListener("abort",u),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new yR(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new yR(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=oqm(m.headers);if(USe.isRedirect(m.statusCode)){let x=g.get("Location"),S=x===null?null:pqm(i.url,x);switch(i.redirect){case"error":n(new yR(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(D){n(D)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new yR(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let P={headers:new d8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&XHl(i)===null){n(new yR("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(P.method="GET",P.body=void 0,P.headers.delete("content-length")),r(USe(new VSe(S,P))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",u)});let A=m.pipe(new qHl),b={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new vre(A,b),r(c);return}let C={flush:Kct.default.Z_SYNC_FLUSH,finishFlush:Kct.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Kct.default.createGunzip(C)),c=new vre(A,b),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new qHl).once("data",function(S){(S[0]&15)===8?A=A.pipe(Kct.default.createInflate()):A=A.pipe(Kct.default.createInflateRaw()),c=new vre(A,b),r(c)});return}c=new vre(A,b),r(c)}),nqm(p,i)})}var iJ,WHl,eJr,HHl,Kct,PUe,h9o,BUe,y9o,Vme,VHl,ZHl,b9o,CC,d8,I9o,v9o,OUe,sqm,vre,Ume,A9o,aqm,cqm,VSe,qHl,pqm,fqm,x9o=h(()=>{"use strict";iJ=Ae(require("stream"),1),WHl=Ae(require("http"),1),eJr=Ae(require("url"),1),HHl=Ae(UHl(),1),Kct=Ae(require("zlib"),1),PUe=Symbol("buffer"),h9o=Symbol("type"),BUe=class e{constructor(){this[h9o]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],l;c instanceof Buffer?l=c:ArrayBuffer.isView(c)?l=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?l=Buffer.from(c):c instanceof e?l=c[PUe]:l=Buffer.from(typeof c=="string"?c:String(c)),n.push(l)}}this[PUe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[h9o]=i)}get size(){return this[PUe].length}get type(){return this[h9o]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[PUe].slice(i,i+s),l=new e([],{type:arguments[2]});return l[PUe]=c,l}};Object.defineProperties(BUe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(BUe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});yR.prototype=Object.create(Error.prototype);yR.prototype.constructor=yR;yR.prototype.name="FetchError";try{y9o=require("encoding").convert}catch{}Vme=Symbol("Body internals"),VHl=iJ.default.PassThrough;jT.prototype={get body(){return this[Vme].body},get bodyUsed(){return this[Vme].disturbed},arrayBuffer(){return Hct.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Hct.call(this).then(function(t){return Object.assign(new BUe([],{type:e.toLowerCase()}),{[PUe]:t})})},json(){var e=this;return Hct.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return jT.Promise.reject(new yR(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Hct.call(this).then(function(e){return e.toString()})},buffer(){return Hct.call(this)},textConverted(){var e=this;return Hct.call(this).then(function(t){return rqm(t,e.headers)})}};Object.defineProperties(jT.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});jT.mixIn=function(e){for(let t of Object.getOwnPropertyNames(jT.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(jT.prototype,t);Object.defineProperty(e,t,r)}};jT.Promise=global.Promise;ZHl=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,b9o=/[^\t\x20-\x7e\x80-\xff]/;CC=Symbol("map"),d8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[CC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);return r===void 0?null:this[CC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=E9o(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=E9o(this),i++}}set(t,r){t=`${t}`,r=`${r}`,LGt(t),GHl(r);let n=Jct(this[CC],t);this[CC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,LGt(t),GHl(r);let n=Jct(this[CC],t);n!==void 0?this[CC][n].push(r):this[CC][t]=[r]}has(t){return t=`${t}`,LGt(t),Jct(this[CC],t)!==void 0}delete(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);r!==void 0&&delete this[CC][r]}raw(){return this[CC]}keys(){return g9o(this,"key")}values(){return g9o(this,"value")}[Symbol.iterator](){return g9o(this,"key+value")}};d8.prototype.entries=d8.prototype[Symbol.iterator];Object.defineProperty(d8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(d8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});I9o=Symbol("internal");v9o=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==v9o)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[I9o];let t=e.target,r=e.kind,n=e.index,i=E9o(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[I9o].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(v9o,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});OUe=Symbol("Response internals"),sqm=WHl.default.STATUS_CODES,vre=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jT.call(this,t,r);let n=r.status||200,i=new d8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=YHl(t);o&&i.append("Content-Type",o)}this[OUe]={url:r.url,status:n,statusText:r.statusText||sqm[n],headers:i}}get url(){return this[OUe].url}get status(){return this[OUe].status}get ok(){return this[OUe].status>=200&&this[OUe].status<300}get statusText(){return this[OUe].statusText}get headers(){return this[OUe].headers}clone(){return new e(JHl(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};jT.mixIn(vre.prototype);Object.defineProperties(vre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(vre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ume=Symbol("Request internals"),A9o=eJr.default.parse,aqm=eJr.default.format,cqm="destroy"in iJ.default.Readable.prototype;VSe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;$Kr(t)?n=A9o(t.url):(t&&t.href?n=A9o(t.href):n=A9o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||$Kr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:$Kr(t)&&t.body!==null?JHl(t):null;jT.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new d8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=YHl(o);c&&s.append("Content-Type",c)}let a=$Kr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!lqm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ume]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ume].method}get url(){return aqm(this[Ume].parsedURL)}get headers(){return this[Ume].headers}get redirect(){return this[Ume].redirect}get signal(){return this[Ume].signal}clone(){return new e(this)}};jT.mixIn(VSe.prototype);Object.defineProperty(VSe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(VSe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});_Gt.prototype=Object.create(Error.prototype);_Gt.prototype.constructor=_Gt;_Gt.prototype.name="AbortError";qHl=iJ.default.PassThrough,pqm=eJr.default.resolve;USe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};USe.Promise=global.Promise;fqm=USe});var RUe=E(GQ=>{"use strict";var Gme={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},UGt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},dqm="tag:yaml.org,2002:",mqm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function $Hl(e){let t=[0],r=e.indexOf(`
|
|
551
551
|
`);for(;r!==-1;)r+=1,t.push(r),r=e.indexOf(`
|
|
552
552
|
`,r);return t}function eKl(e){let t,r;return typeof e=="string"?(t=$Hl(e),r=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=$Hl(e.context.src)),t=e.lineStarts,r=e.context.src)),{lineStarts:t,src:r}}function S9o(e,t){if(typeof e!="number"||e<0)return null;let{lineStarts:r,src:n}=eKl(t);if(!r||!n||e>n.length)return null;for(let o=0;o<r.length;++o){let s=r[o];if(e<s)return{line:o,col:e-r[o-1]+1};if(e===s)return{line:o+1,col:1}}let i=r.length;return{line:i,col:e-r[i-1]+1}}function hqm(e,t){let{lineStarts:r,src:n}=eKl(t);if(!r||!(e>=1)||e>r.length)return null;let i=r[e-1],o=r[e];for(;o&&o>i&&n[o-1]===`
|
|
553
553
|
`;)--o;return n.slice(i,o)}function gqm({start:e,end:t},r,n=80){let i=hqm(e.line,r);if(!i)return null;let{col:o}=e;if(i.length>n)if(o<=n-10)i=i.substr(0,n-1)+"\u2026";else{let u=Math.round(n/2);i.length>o+u&&(i=i.substr(0,o+u-1)+"\u2026"),o-=i.length-n,i="\u2026"+i.substr(1-n)}let s=1,a="";t&&(t.line===e.line&&o+(t.col-e.col)<=n+1?s=t.col-e.col:(s=Math.min(i.length+1,n)-o,a="\u2026"));let c=o>1?" ".repeat(o-1):"",l="^".repeat(s);return`${i}
|
|
@@ -1860,7 +1860,7 @@ ${n.map(o=>` ${o}`).join(`,
|
|
|
1860
1860
|
`)}
|
|
1861
1861
|
]`;case 1:return`${i} Did you mean ${r[0]}?`;case 2:return`${i} Did you mean ${r[0]} or ${r[1]}?`;default:return`${i} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function nfi(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function xYh(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}var vYh,CYh,nNu=h(()=>{"use strict";rNu();vYh=3,CYh=5});function ifi({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:n,apiDefinitionId:i}){if(n)return e;let o=[],s=new Map;return e.forEach(a=>{if(a.type!=="endpoint"){o.push(a);return}let c=t(a.endpointId);if(c==null)throw new T({message:`Endpoint ${a.endpointId} not found`,code:T.Code.InternalError});let l=`${c.method} ${r(c)}`,u=s.get(l);if(s.set(l,a),u==null||u.isResponseStream===a.isResponseStream){o.push(a);return}let p=o.indexOf(u),d=a.isResponseStream?a:u,f=a.isResponseStream?u:a,m={id:Vt.V1.NodeId(`${i}:${f.endpointId}+${d.endpointId}`),type:"endpointPair",collapsed:void 0,stream:d,nonStream:f};o[p]=m}),o}var $ms=h(()=>{"use strict";sm();Bt()});function iNu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:o}){return ifi({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:o}).filter(s=>s.type==="apiPackage"?s.children.length>0||s.overviewPageId!=null:!0)}var oNu=h(()=>{"use strict";$ms()});function sNu(e){if(e!=null)switch(e){case"unset":return;case"stable":case"generally-available":return"generally-available";case"in-development":case"pre-release":case"beta":return"beta";case"alpha":case"preview":case"legacy":case"deprecated":return e;default:return Ye(e)}}function wYh(e){switch(e.type){case"endpointPair":return e.nonStream.availability;case"apiPackage":case"endpoint":case"webSocket":case"webhook":case"grpc":case"graphql":case"graphqlType":case"apiType":case"page":return e.availability;case"link":return;default:return Ye(e)}}function aNu(e,t){let r=[];for(let o of t){let s=sNu(o);r.includes(s)||r.push(s)}for(let o of SYh)r.includes(o)||r.push(o);let n=new Map(r.map((o,s)=>[o,s])),i=o=>n.get(sNu(wYh(o)))??r.length;return[...e].sort((o,s)=>i(o)-i(s))}var SYh,cNu=h(()=>{"use strict";mt();SYh=[void 0,"generally-available","alpha","beta","preview","legacy","deprecated"]});function Oxt(e,t){if(t!=null)return go(e.absoluteFilePath,t)}var ehs=h(()=>{"use strict";tr()});function lNu({docsWorkspace:e,page:t,parentSlug:r,idgen:n,markdownFilesToFullSlugs:i,markdownFilesToNoIndex:o,hideChildren:s,resolveIconFileId:a}){let c=Vt.V1.PageId(Oxt(e,t.absolutePath)),l=r.apply({fullSlug:i.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Tu(t.title)});return{id:n.get(c),type:"page",collapsed:void 0,pageId:c,title:t.title,slug:l.get(),icon:a?a(t.icon):t.icon,hidden:s||t.hidden,noindex:t.noindex||o.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:Mh(t.availability)}}var uNu=h(()=>{"use strict";sm();xo();tfi();ehs()});function ths(e){return e.fieldPath}function pNu(e){return e.name??e.id}var fNu,TYh,OYh,PYh,BYh,DYh,RYh,kYh,_Jt,dNu=h(()=>{"use strict";mt();sm();tr();Bt();xo();fNu=Ae(kf(),1);Q2u();L2u();Yms();tfi();q2u();W2u();nNu();Wms();oNu();$ms();cNu();Hms();uNu();ehs();TYh=[{category:"object",title:"Objects",urlSlug:"objects"},{category:"input",title:"Inputs",urlSlug:"inputs"},{category:"enum",title:"Enums",urlSlug:"enums"},{category:"scalar",title:"Scalars",urlSlug:"scalars"},{category:"interface",title:"Interfaces",urlSlug:"interfaces"},{category:"union",title:"Unions",urlSlug:"unions"}],OYh="types",PYh="types",BYh="schemas",DYh="Types",RYh="Schemas",kYh="Types",_Jt=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;openApiTags;profileVars;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#o=new Set;#s=new Set;#a=new Map;#c=[];#l;#f;#p;disableEndpointPairs;collectedFileIds=new Map;#d;#u;#m;#h;constructor(t,r,n,i,o,s,a,c,l,u,p,d,f,m,g,A,b,I=z2u){this.apiSection=t,this.docsWorkspace=i,this.taskContext=o,this.markdownFilesToFullSlugs=s,this.markdownFilesToNoIndex=a,this.markdownFilesToTags=c,this.workspace=p,this.hideChildren=d,this.parentAvailability=f,this.openApiTags=m,this.profileVars=I,this.#d=new Map,this.#u=g??new Map,this.#m=A??{},this.#h=b??new Set,this.disableEndpointPairs=i.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Vt.V1.ApiDefinitionId(r.id),this.#e=Kke.create(r,o),this.collectedFileIds=u,this.#p=l,this.#l=this.apiSection.overviewAbsolutePath!=null?Vt.V1.PageId(Oxt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let C=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#f=n.apply({fullSlug:C?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Tu(this.apiSection.title)});let x=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#c=this.#b(this.apiSection.navigation,this.#e.api.rootPackage,this.#f,x)),this.#c=this.#w(this.#c.map(S=>this.#A(S,x)),this.#O(this.#e.api.rootPackage,this.#f,x))}get(){let t=Vt.V1.followRedirects(this.#c),r=new x8e(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(o=>o.absoluteFilepath),this.docsWorkspace,this.#p,this.profileVars).orUndefined(),n=this.#l,i=this.profileVars.forNode({texts:[this.apiSection.title],absolutePath:this.apiSection.overviewAbsolutePath});if(n==null&&!this.apiSection.tagDescriptionPages){let o=this.#c.find(s=>s.type==="apiPackage"&&s.overviewPageId!=null);if(o!=null){n=o.overviewPageId;let{profileVars:s}=o,a={...i.profileVars,...s};i=Object.keys(a).length>0?{profileVars:a}:{}}}return{id:this.#p.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:n,collapsed:this.apiSection.collapsed,collapsible:void 0,collapsedByDefault:void 0,paginated:this.apiSection.paginated,slug:this.#f.get(),icon:this.resolveIconFileId(this.apiSection.icon),hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#f,viewers:void 0,hidden:this.hideChildren}),children:this.#c,availability:Mh(this.apiSection.availability??this.parentAvailability),pointsTo:t,noindex:void 0,playground:this.#R(this.apiSection.playground),postmanCollectionUrl:this.apiSection.postman,authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags,...i}}#g(t){if(t==null)return{};let r=Zt.of(`/${t}`),n=this.#d.get(r);return n==null?{}:this.profileVars.forNode({texts:[n]})}getTagDescriptionContent(){return this.#d}createTagDescriptionPageId(t,r){if(!this.apiSection.tagDescriptionPages||!this.openApiTags)return;let n=sY(t)?t.name:void 0;if(!n)return;let i=this.openApiTags[n]??(r!=null?this.openApiTags[ao(r)]:void 0);if(!i||!i.description)return;let o=`tag-${n}.md`,s=Zt.of(`/${o}`),a=Vt.V1.PageId(o),c=`# ${yP(i.id.replace(/[_-]/g," "))}
|
|
1862
1862
|
|
|
1863
|
-
${i.description}`;return this.#d.set(s,c),this.markdownFilesToNoIndex.set(s,!1),this.markdownFilesToTags.set(s,[n]),a}#b(t,r,n,i){r=this.#e.resolveSubpackage(r);let o=r!=null?Kke.getSubpackageId(r):void 0;return t.map(s=>GX(s)._visit({link:a=>({id:this.#p.get(a.url),type:"link",collapsed:void 0,title:a.text,icon:this.resolveIconFileId(a.icon),url:Vt.Url(a.url),target:a.target}),page:a=>this.#E(a,n,i),package:a=>this.#C(a,n,i),section:a=>this.#I(a,n,i),item:({value:a})=>this.#y(a,o,n,i),endpoint:a=>this.#v(a,o,n,i),operation:a=>this.#x(a,o,n,i)})).filter(gs)}#E(t,r,n){return{...lNu({page:{...t,availability:t.availability??n},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#p,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)}),...this.profileVars.forNode({texts:[t.title],absolutePath:t.absolutePath,pageProfile:t.profile})}}#C(t,r,n){let i=t.overviewAbsolutePath!=null?Vt.V1.PageId(Oxt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,s=t.availability??n,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let c=Kke.getSubpackageId(a),l=i??this.createTagDescriptionPageId(a,t.package),u=this.#p.get(l??`${this.apiDefinitionId}:${c}`);this.#s.has(c)&&this.taskContext.logger.warn(nfi(t.package)),this.#s.add(c),this.#a.set(u,[c]);let p=t.slug??(sY(a)?a.urlSlug:this.apiSection.slug??Tu(this.apiSection.title)),d=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:p}),f=this.#b(t.contents,a,d,s);return{id:u,type:"apiPackage",collapsed:void 0,children:f,title:t.title??(sY(a)?a.displayName??yP(a.name):this.apiSection.title),slug:d.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:l,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(s),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...i!=null?this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath}):this.#g(l)}}else{this.taskContext.logger.warn(rfi(t.package,this.#e.subpackageLocators));let c=t.slug??Tu(t.package),l=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),u=this.#b(t.contents,void 0,l,s);return{id:this.#p.get(i??`${this.apiDefinitionId}:${Tu(t.package)}`),type:"apiPackage",collapsed:void 0,children:u,title:t.title??t.package,slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:i,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(s),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath})}}}#I(t,r,n){let i=t.overviewAbsolutePath!=null?Vt.V1.PageId(Oxt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,s=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,a=this.#p.get(i??o??r.get()),c=t.referencedSubpackages.map(f=>{let m=this.#e.getSubpackageByIdOrLocator(f),g=m!=null?Kke.getSubpackageId(m):void 0;if(g===void 0){this.taskContext.logger.error(rfi(f,this.#e.subpackageLocators));return}return{subpackageId:g,locator:f}}).filter(f=>f!=null).filter(gs);this.#a.set(a,c.map(f=>f.subpackageId)),c.forEach(f=>{this.#s.has(f.subpackageId)&&this.taskContext.logger.error(nfi(f.locator)),this.#s.add(f.subpackageId)});let l=t.slug??Tu(t.title),u=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),p=t.availability??n,d=this.#b(t.contents,void 0,u,p);return{id:a,type:"apiPackage",children:d,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:i,collapsed:t.collapsed,collapsible:t.collapsible,collapsedByDefault:t.collapsedByDefault,availability:Mh(p),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:s,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath})}}#y(t,r,n,i){t=t.trim();let o=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(ao(t));if(o!=null){let s=Kke.getSubpackageId(o),a=this.#p.get(`${this.apiDefinitionId}:${s}`),c=this.createTagDescriptionPageId(o,t);this.#s.has(s)&&this.taskContext.logger.error(nfi(t)),this.#s.add(s),this.#a.set(a,[s]);let l=sY(o)?o.urlSlug:"",u=n.apply({urlSlug:l});return{id:a,type:"apiPackage",collapsed:void 0,children:[],title:sY(o)?o.displayName??yP(o.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,...this.#g(c),overviewPageId:c,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(i),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#v({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,n,i)}#v(t,r,n,i){let o=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.endpoints.get(Fb.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(o!=null){let l=this.#e.getEndpointId(o);if(l==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let u=t.slug!=null?n.append(t.slug):n.apply(o);return{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",collapsed:void 0,method:o.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(o.availability)??Mh(i),isResponseStream:o.response?.type.type==="stream",title:t.title??o.name??Wk(o.path.parts),slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#R(o.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let s=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.webSockets.get(Fb.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(s!=null){let l=this.#e.getWebSocketId(s);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${s.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",collapsed:void 0,webSocketId:l,title:t.title??s.name??Wk(s.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(s)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(s.availability)??Mh(i),playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.webhooks.get(Fb.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Vt.V1.WebhookId(t.endpoint));if(a!=null){let l=this.#e.getWebhookId(a);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"webhook",collapsed:void 0,webhookId:l,method:a.method,title:t.title??a.name??(0,fNu.default)("/",...a.path),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(a.availability)??Mh(i),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=this.#e.api.rootPackage.graphqlOperations?.find(l=>l.id===t.endpoint||l.name===t.endpoint);if(c!=null){let l=Fb.GraphQlOperationId(c.id);if(this.#o.has(l)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${l}`);return}this.#o.add(l);let u=t.slug!=null?n.append(t.slug):n.append(c.name??c.id);return this.#k({id:this.#p.get(`${this.apiDefinitionId}:${l}`),operationType:c.operationType,graphqlOperationId:Fb.GraphQlOperationId(c.id),title:t.title??c.displayName??c.name??c.id,slug:u.get(),availability:t.availability??i,icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#R(t.playground),viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags})}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#x(t,r,n,i){let o=t.operation.trim().split(/\s+/,2);if(o.length!==2){this.taskContext.logger.error(`Invalid operation format in the API Reference layout: ${t.operation}. Expected format: "OPERATION_TYPE operationName" (e.g., "QUERY account")`);return}let[s,a]=o;if(!a){this.taskContext.logger.error(`Invalid operation format in the API Reference layout: ${t.operation}. Expected format: "OPERATION_TYPE operationName" (e.g., "QUERY account")`);return}let c=this.#e.api.rootPackage.graphqlOperations??[],l=c.filter(f=>{if(f.operationType!==s)return!1;if(a.includes(".")){if(f.id===a||f.name===a)return!0;let m=a.split("."),g=m[m.length-1],A=m.slice(0,-1).join(".");if(f.name===g||f.id===g)return f.id.startsWith(A+".")||this.#u.get(en.GraphQlOperationId(f.id))===A}else return f.name===a||f.id===a;return!1});if(!a.includes(".")){let f=c.filter(m=>m.operationType===s&&(m.name===a||m.id===a));if(f.length>1){let m=f.map(g=>{let A=this.#u.get(en.GraphQlOperationId(g.id));if(A)return`"${s} ${A}.${a}"`;let b=g.id.split("_");if(b.length>=3){let I=b[0];return`"${s} ${I}.${a}"`}return`"${s} ${g.id}"`}).join(", ");this.taskContext.logger.warn(`Ambiguous operation reference: "${t.operation}". Found ${f.length} operations with name "${a}". Using first match: "${m.split(", ")[0]}". Please use the full namespaced format for clarity. Available options: ${m}`)}}let u=l[0];if(u==null){this.taskContext.logger.error(`GraphQL operation not found in the API Reference layout: ${t.operation}`);return}let p=Fb.GraphQlOperationId(u.id);if(this.#o.has(p)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${p}`);return}this.#o.add(p);let d=t.slug!=null?n.append(t.slug):n.append(u.name??u.id);return this.#k({id:this.#p.get(`${this.apiDefinitionId}:${p}`),operationType:u.operationType,graphqlOperationId:Fb.GraphQlOperationId(u.id),title:t.title??u.displayName??u.name??u.id,slug:d.get(),availability:t.availability??i,hidden:this.hideChildren||t.hidden,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags})}#w(t,r){return iNu({left:t,right:r,findEndpointById:n=>this.#e.endpoints.get(n),stringifyEndpointPathParts:n=>Wk(n.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#A(t,r){return Xms({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(n,i,o)=>this.#N(n,i,o),mergeAndFilterChildren:this.#w.bind(this)})}#O(t,r,n){let i=[];if(t.endpoints.forEach(o=>{if(o.protocol?.type==="grpc"){let s=this.#e.getGrpcId(o);if(s==null){this.taskContext.logger.error(`Expected Grpc ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);return}if(this.#i.has(s))return;let a=r.apply(o);i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"grpc",collapsed:void 0,grpcId:s,title:o.name??Wk(o.path.parts),method:o.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:Mh(n),slug:a.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let s=this.#e.getEndpointId(o);if(s==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);return}if(this.#t.has(s))return;let a=r.apply(o);i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"endpoint",collapsed:void 0,method:o.method,endpointId:s,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),isResponseStream:o.response?.type.type==="stream",title:o.name??Wk(o.path.parts),slug:a.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(o=>{let s=this.#e.getWebSocketId(o);if(s==null){this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);return}this.#r.has(s)||i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"webSocket",collapsed:void 0,webSocketId:s,title:o.name??Wk(o.path.parts),slug:r.apply(o).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(o=>{let s=this.#e.getWebhookId(o);if(s==null){this.taskContext.logger.error(`Expected Webhook ID for ${o.id}. Got undefined.`);return}this.#n.has(s)||i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"webhook",collapsed:void 0,webhookId:s,method:o.method,title:o.name??yP(o.id),slug:r.apply(o).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(o=>{if(this.#s.has(o))return;let s=this.#e.getSubpackageByIdOrLocator(o);if(s==null){this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`);return}let a=sY(s)?r.apply(s):r,c=this.#N(o,a,n),l=this.createTagDescriptionPageId(s),u=this.#e.subpackages.get(Fb.SubpackageId(o)),p=u?Array.from(u.endpoints.values()).some(d=>{let f=this.#e.getEndpointId(d);return f!=null&&this.#t.has(f)}):!1;(c.length>0||l!=null&&p)&&i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",collapsed:void 0,children:c,title:sY(s)?s.displayName??yP(s.name):this.apiSection.title,slug:a.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:l,...this.#g(l),collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.graphqlOperations!=null&&t.graphqlOperations.length>0){let o=this.#P(t.graphqlOperations,r,n);i.push(...o)}if(t===this.#e.api.rootPackage){let o=this.#S(r,n);if(o!=null&&i.push(o),this.apiSection.types){let s=this.#Q(r,n);s!=null&&i.push(s)}}return i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((o,s)=>{let a=o.type==="endpointPair"?o.nonStream.title:o.title,c=s.type==="endpointPair"?s.nonStream.title:s.title;return a.localeCompare(c)})),this.apiSection.sortByAvailability!=null&&(i=aNu(i,this.apiSection.sortByAvailability)),i}#P(t,r,n){let i={},o={};for(let l of t){let u=Fb.GraphQlOperationId(l.id);if(this.#o.has(u))continue;this.#o.add(u);let p=this.#u.get(en.GraphQlOperationId(l.id)),d=l.operationType;p!=null?(i[p]==null&&(i[p]={}),i[p][d]==null&&(i[p][d]=[]),i[p][d].push(l)):(o[d]==null&&(o[d]=[]),o[d].push(l))}let s=[],a=["QUERY","MUTATION","SUBSCRIPTION"],c={QUERY:"Queries",MUTATION:"Mutations",SUBSCRIPTION:"Subscriptions"};for(let[l,u]of Object.entries(i)){let p=r.append(Tu(l)),d=[];for(let m of a){let g=u[m];if(g==null||g.length===0)continue;let A=c[m],b=p.append(Tu(A)),I=this.#F(g,b,n,m),C={id:this.#p.get(`${this.apiDefinitionId}:graphql:${l}:${m}`),type:"apiPackage",collapsed:void 0,children:I,title:A,slug:b.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};d.push(C)}let f={id:this.#p.get(`${this.apiDefinitionId}:graphql:namespace:${l}`),type:"apiPackage",collapsed:void 0,children:d,title:yP(l),slug:p.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};s.push(f)}for(let l of a){let u=o[l];if(u==null||u.length===0)continue;let p=c[l],d=r.append(Tu(p)),f=this.#F(u,d,n,l),m={id:this.#p.get(`${this.apiDefinitionId}:graphql:${l}`),type:"apiPackage",collapsed:void 0,children:f,title:p,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};s.push(m)}return s}#S(t,r){let n=new Map;for(let[s,a]of Object.entries(this.#m)){let c=en.TypeId(s);if(this.#e.api.types[c]==null)continue;let l=n.get(a);l!=null?l.push(c):n.set(a,[c])}if(n.size===0)return;let i=t.append(OYh),o=[];for(let{category:s,title:a,urlSlug:c}of TYh){let l=n.get(s);if(l==null||l.length===0)continue;let u=i.append(c),p=l.map(d=>this.#j(d,s,u,r)).filter(gs).sort((d,f)=>d.title.localeCompare(f.title));p.length!==0&&o.push({id:this.#p.get(`${this.apiDefinitionId}:graphql:types:${s}`),type:"apiPackage",collapsed:void 0,children:p,title:a,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}if(o.length!==0)return{id:this.#p.get(`${this.apiDefinitionId}:graphql:types`),type:"apiPackage",collapsed:void 0,children:o,title:kYh,slug:i.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#B(){let t=this.#e.api,r=new Set,n=[],i=o=>{r.has(o)||(r.add(o),n.push(o))};for(let o of[t.rootPackage,...Object.values(t.subpackages)])o.endpoints.forEach(s=>Vt.ApiTypeIdVisitor.visitEndpointDefinition(s,i)),o.websockets.forEach(s=>Vt.ApiTypeIdVisitor.visitWebSocketChannel(s,i)),o.webhooks.forEach(s=>Vt.ApiTypeIdVisitor.visitWebhookDefinition(s,i)),o.graphqlOperations?.forEach(s=>Vt.ApiTypeIdVisitor.visitGraphQlOperation(s,i));for(let o=n.shift();o!=null;o=n.shift()){let s=t.types[o];s!=null&&Vt.ApiTypeIdVisitor.visitTypeDefinition(s,i)}return r}#Q(t,r){let n=this.#B(),i=Object.keys(this.#m).length>0,o=t.append(i?BYh:PYh),s=new Set,a=Object.keys(this.#e.api.types).map(c=>en.TypeId(c)).filter(c=>!n.has(c)&&this.#m[c]==null&&!this.#h.has(c)).sort((c,l)=>{let u=this.#e.api.types[c]?.displayName??this.#e.api.types[c]?.name??c,p=this.#e.api.types[l]?.displayName??this.#e.api.types[l]?.name??l;return u.localeCompare(p,"en")||c.localeCompare(l,"en")}).map(c=>this.#D(c,o,s,r)).filter(gs);if(a.length!==0)return{id:this.#p.get(`${this.apiDefinitionId}:types`),type:"apiPackage",collapsed:void 0,children:a,title:i?RYh:DYh,slug:o.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#D(t,r,n,i){let o=this.#e.api.types[t];if(o==null)return;let s=o.displayName??o.name??t,a=Tu(s),c=a;for(let l=2;n.has(c);l++)c=`${a}-${l}`;return n.add(c),{id:this.#p.get(`${this.apiDefinitionId}:apiType:${t}`),type:"apiType",collapsed:void 0,typeId:Vt.TypeId(t),title:s,slug:r.append(c).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#j(t,r,n,i){let o=this.#e.api.types[t];if(o==null)return;let s=o.displayName??o.name??t;return{id:this.#p.get(`${this.apiDefinitionId}:graphqlType:${t}`),type:"graphqlType",collapsed:void 0,typeId:Vt.TypeId(t),typeCategory:r,title:s,slug:n.append(Tu(s)).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#k({id:t,operationType:r,graphqlOperationId:n,graphqlOperationIds:i,title:o,slug:s,availability:a,hidden:c,icon:l,playground:u,viewers:p,orphaned:d,featureFlags:f}){return{id:t,type:"graphql",collapsed:void 0,operationType:r,graphqlOperationId:n,graphqlOperationIds:i,apiDefinitionId:this.apiDefinitionId,availability:Mh(a),title:o,slug:s,icon:l,hidden:c,playground:u,authed:void 0,viewers:p,orphaned:d,featureFlags:f}}#F(t,r,n,i){let o=i==="QUERY",s=new Map,a=[];for(let u of t){let p=ths(u)?.[0];if(o&&p!=null){let d=s.get(p);d!=null?d.push(u):(s.set(p,[u]),a.push({type:"group",parentField:p}))}else a.push({type:"flat",operation:u})}let c=new Map;for(let u of a)if(u.type==="flat"){let p=pNu(u.operation);s.has(p)&&ths(u.operation)==null&&c.set(p,u.operation)}let l=[];for(let u of a)if(u.type==="flat"){let p=pNu(u.operation);if(c.has(p))continue;let d=ths(u.operation),f=r;if(d!=null&&d.length>0)for(let m of d)f=f.append(Tu(m));f=f.append(Tu(p)),l.push(this.#k({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${u.operation.id}`),operationType:u.operation.operationType,graphqlOperationId:Fb.GraphQlOperationId(u.operation.id),title:u.operation.displayName??u.operation.name??u.operation.id,slug:f.get(),availability:n,hidden:this.hideChildren}))}else{let p=s.get(u.parentField)??[],f=c.get(u.parentField)??p[0];if(f==null)continue;let m=r.append(Tu(u.parentField));l.push(this.#k({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${f.id}`),operationType:f.operationType,graphqlOperationId:Fb.GraphQlOperationId(f.id),graphqlOperationIds:p.map(g=>Fb.GraphQlOperationId(g.id)),title:u.parentField,slug:m.get(),availability:n,hidden:this.hideChildren}))}return l}#N(t,r,n){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.debug(rfi(t||"unknown",[])),[]):this.#O(i,r,n)}#R(t){return G2u(t)}mergeEndpointPairs(t){return ifi({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>Wk(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t,void 0,{code:T.Code.InternalError})}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}}});function FYh(e){return mNu.default.createHash("sha256").update(e).digest("hex")}var mNu,ofi,hNu=h(()=>{"use strict";sm();Bt();mNu=Ae(require("crypto"),1);ofi=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),FYh(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),n=0;for(;this.#t.has(r);)if(r=this.#r(t),n++,n>100)throw new T({message:`Infinite loop detected for id: ${t}`,code:T.Code.ReferenceError});return r}get(t){return Vt.V1.NodeId(this.#n(t))}}});function gNu(e){let t=new Set;for(let[r,n]of Object.entries(e.types))n.inline===!0&&t.add(en.TypeId(r));return t}var ANu=h(()=>{"use strict";sm()});async function yNu({absolutePathToFernFolder:e}){let t=[];for(let r of NYh){let n=Re(e,r);if(await Ut(n)){let i=await UFt(n);t.push(...i.map(Zt.of))}}return t}var NYh,bNu=h(()=>{"use strict";tr();NYh=[be.of(".well-known/skills"),be.of(".well-known/agent-skills")]});function ENu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0,cliSdk:e.cli!=null?{package:typeof e.cli=="string"?e.cli:e.cli.package,version:typeof e.cli=="string"?void 0:e.cli.version}:void 0}}var INu=h(()=>{"use strict"});function sfi(e){return typeof e=="string"?e:e.name}function Jke(e){if(e!=null)return typeof e=="string"?e:e.originalName}var Pxt=h(()=>{"use strict";sc()});function vNu({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];return CNu({scheme:n,playgroundConfig:t,context:r})}}function CNu({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:jr(e.password),usernameName:jr(e.username),description:e.docs,playgroundDescription:e.playgroundDocs,passwordAlwaysEmpty:e.passwordOmit};case"bearer":return{type:"bearerAuth",tokenName:jr(e.token),description:e.docs,playgroundDescription:e.playgroundDocs};case"header":return{type:"header",headerWireValue:cr(e.name),nameOverride:jr(sfi(e.name)),prefix:e.prefix,description:e.docs,playgroundDescription:e.playgroundDocs};case"oauth":{let n=e.configuration;if(n.type!=="clientCredentials")return{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs};let i=n.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(o=>jr(o.name)).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:en.EndpointId(n.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:i,headerName:n.tokenHeader,tokenPrefix:n.tokenPrefix,description:e.docs,playgroundDescription:e.playgroundDocs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let n=e.tokenEndpoint.authenticatedRequestHeaders.find(o=>o.headerName.toLowerCase()==="authorization");if(n)return n.responseProperty.propertyPath!=null&&n.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:cr(n.responseProperty.property.name),description:e.docs,playgroundDescription:e.playgroundDocs};let i=e.tokenEndpoint.authenticatedRequestHeaders[0];return i?{type:"header",headerWireValue:i.headerName,prefix:i.valuePrefix,nameOverride:void 0,description:e.docs,playgroundDescription:e.playgroundDocs}:{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs}}default:Ye(e)}}function xNu({auth:e,playgroundConfig:t,context:r}){let n={};for(let i of e.schemes){let o=CNu({scheme:i,playgroundConfig:t,context:r});o!=null&&(n[en.AuthSchemeId(i.key)]=o)}return n}var SNu=h(()=>{"use strict";mt();sm();Pxt()});function wNu(e,t){return e._visit({alias:r=>({type:"alias",value:uf(r.aliasOf)}),enum:r=>({type:"enum",default:r.default!=null?cr(r.default.name):void 0,values:r.values.map(n=>({description:n.docs??void 0,value:cr(n.name),availability:cE(n.availability)}))}),object:r=>({type:"object",extends:r.extends.map(n=>en.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),availability:cE(n.availability),propertyAccess:n.propertyAccess,...n.xml!=null?{xml:GYh(n.xml)}:{}})),extraProperties:VYh(r.extraProperties),...t!=null?{xml:{name:t.name,namespace:t.namespace,prefix:t.prefix}}:{}}),union:r=>{let n=r.baseProperties.map(i=>({key:en.PropertyKey(cr(i.name)),valueType:uf(i.valueType,i.defaultValue),availability:cE(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:cr(r.discriminant),variants:r.types.map(i=>({description:i.docs??void 0,discriminantValue:cr(i.discriminantValue),displayName:i.displayName,availability:i.availability!=null?cE(i.availability):void 0,additionalProperties:$t.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:o=>({extends:[en.TypeId(o.typeId)],properties:n,extraProperties:void 0}),singleProperty:o=>({extends:[],properties:[{key:en.PropertyKey(cr(o.name)),valueType:uf(o.type),description:void 0,availability:void 0,propertyAccess:void 0},...n],extraProperties:void 0}),noProperties:()=>({extends:[],properties:n,extraProperties:void 0}),_other:()=>{throw new T({message:"Unknown SingleUnionTypeProperties: "+i.shape.propertiesType,code:T.Code.InternalError})}})}))}},undiscriminatedUnion:r=>({type:"undiscriminatedUnion",variants:r.members.map(n=>({typeName:n.type.type==="named"?jr(n.type.name):void 0,description:n.docs??void 0,type:uf(n.type),availability:void 0,displayName:n.type.type==="named"?n.type.displayName:void 0}))}),_other:()=>{throw new T({message:"Unknown Type shape: "+e.type,code:T.Code.InternalError})}})}function uf(e,t){return e._visit({container:r=>$t.types.ContainerType._visit(r,{list:n=>({type:"list",itemType:uf(n),minItems:void 0,maxItems:void 0}),map:({keyType:n,valueType:i})=>({type:"map",keyType:uf(n),valueType:uf(i),minProperties:void 0,maxProperties:void 0}),optional:n=>({type:"optional",itemType:uf(n),defaultValue:t}),nullable:n=>({type:"nullable",itemType:uf(n)}),set:n=>({type:"set",itemType:uf(n),minItems:void 0,maxItems:void 0}),literal:n=>$t.types.Literal._visit(n,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new T({message:"Unknown literal type: "+n.type,code:T.Code.InternalError})}}),_other:()=>{throw new T({message:"Unknown container reference: "+r.type,code:T.Code.InternalError})}}),named:r=>({type:"id",value:en.TypeId(r.typeId),default:void 0}),primitive:r=>({type:"primitive",value:$t.types.PrimitiveTypeV1._visit(r.v1,{integer:()=>zYh(r.v2),float:()=>QYh(r.v2),double:()=>MYh(r.v2),string:()=>jYh(r.v2),long:()=>LYh(r.v2),boolean:()=>({type:"boolean",default:r.v2?.type==="boolean"?r.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:r.v2?.type==="bigInteger"?r.v2.default:void 0}),uint:()=>_Yh(r.v2),uint64:()=>UYh(r.v2),dateTimeRfc2822:()=>({type:"datetime",default:void 0}),_other:()=>{throw new T({message:"Unknown primitive: "+r.v1,code:T.Code.InternalError})}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new T({message:"Unknown Type reference: "+e.type,code:T.Code.InternalError})}})}function jYh(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function zYh(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="integer"?e.default:void 0}}function QYh(e){return{type:"scalar",name:"float",description:void 0,default:e!=null&&e.type==="float"?e.default:void 0}}function MYh(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="double"?e.default:void 0}}function LYh(e){let t=e!=null&&e.type==="long"?e.validation:void 0;return{type:"long",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="long"?e.default:void 0}}function _Yh(e){let t=e!=null&&e.type==="uint"?e.validation:void 0;return{type:"uint",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint"?e.default:void 0}}function UYh(e){let t=e!=null&&e.type==="uint64"?e.validation:void 0;return{type:"uint64",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint64"?e.default:void 0}}function VYh(e){return typeof e=="boolean"?e?Hr.unknown():void 0:typeof e=="string"?{type:"id",value:en.TypeId(e),default:void 0}:uf(e)}function GYh(e){if(e!=null)return{kind:qYh(e.kind),name:e.name,wrapped:e.wrapped,listSeparator:e.listSeparator}}function qYh(e){switch(e){case"ATTRIBUTE":return"attribute";case"TEXT":return"text";case"ELEMENT":return"element";default:Ye(e)}}var rhs=h(()=>{"use strict";mt();sm();zn();Bt();nhs();Pxt()});function shs(e,t,r,n,i={}){let o=e.service!=null?t.services[e.service]:void 0,s=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,a=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:o!=null?HYh(o,t,i):[],webhooks:s!=null?WYh(s):[],websockets:a!=null?[JYh(a,t)]:[],types:[...e.types.map(l=>en.TypeId(l)),...Object.keys(n??{}).map(l=>en.TypeId(l))],subpackages:e.subpackages.map(l=>en.SubpackageId(l)),pointsTo:e.navigationConfig!=null?en.SubpackageId(e.navigationConfig.pointsTo):void 0,graphqlOperations:r?Object.values(r):[]}}function WYh(e){return e.map(t=>{let r=[];if(t.v2Examples!=null){for(let[n,i]of Object.entries(t.v2Examples.userSpecifiedExamples))r.push({name:i.name??n,payload:i.payload});for(let[n,i]of Object.entries(t.v2Examples.autogeneratedExamples))r.push({name:i.name??n,payload:i.payload})}else r.push(...t.examples?.map(n=>({name:Jke(n.name),payload:n.payload.jsonExample}))??[]);return{description:t.docs??void 0,availability:cE(t.availability),id:en.WebhookId(jr(t.name)),path:[],method:t.method,name:t.displayName??Qze(jr(t.name)),headers:t.headers.map(n=>({description:n.docs??void 0,key:cr(n.name),type:uf(n.valueType,n.defaultValue),availability:cE(n.availability)})),payload:aXh(t.payload,t.fileUploadPayload),examples:r,responses:t.responses?.map(ohs).filter(gs)}})}function HYh(e,t,r){let n=[];for(let i of e.endpoints){let o=i.autogeneratedExamples[0],s=[];if(i.v2Examples!=null){let c,l=i.v2Examples.userSpecifiedExamples,u=i.v2Examples.autogeneratedExamples,p=Object.values(l).map(f=>f.response?.statusCode).filter((f,m,g)=>g.indexOf(f)!==m).length>0;for(let[f,m]of Object.entries(l))c=ONu({shouldUseExampleName:m.displayName!=null||p,exampleName:m.displayName??f,example:m,irEndpoint:i,irService:e,ir:t}),c!=null&&s.push(c);let d=Object.values(u).map(f=>f.response?.statusCode).filter((f,m,g)=>g.indexOf(f)!==m).length>0;for(let[f,m]of Object.entries(u))c=ONu({shouldUseExampleName:d,exampleName:m.displayName??f,example:m,irEndpoint:i,irService:e,ir:t}),c!=null&&s.push(c)}else if(i.userSpecifiedExamples.length>0)s.push(...i.userSpecifiedExamples.map(c=>ihs({userSpecifiedExample:c,...o!=null&&{autogeneratedExample:o},irEndpoint:i,ir:t})).filter(gs));else if(o!=null){let c=ihs({autogeneratedExample:o,irEndpoint:i,ir:t});c!=null&&s.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=Dat({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let l=ihs({autogeneratedExample:c,irEndpoint:i,ir:t});if(l!=null){let u={...l,responseBodyV3:{type:"filename",value:"<bytes>"}};s.push(u)}}}s.push(...oXh({irEndpoint:i,ir:t,examples:s}));let a={slug:void 0,availability:cE(i.availability??e.availability),auth:i.auth,authV2:YYh(i.security),multiAuth:XYh(i.security,t.auth,r.showScopes??!1),description:i.docs??void 0,method:rXh(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?en.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ZYh({environmentsConfig:t.environments,endpoint:i}):void 0,id:en.EndpointId(jr(i.name)),originalEndpointId:i.id,name:i.displayName??Qze(jr(i.name)),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:en.PropertyKey(jr(c.name)),type:uf(c.valueType),availability:void 0,explode:c.explode})),parts:[...Bxt(i.basePath),...Bxt(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:en.PropertyKey(jr(c.name)),type:uf(c.valueType),availability:void 0,explode:c.explode})),parts:[...t.basePath!=null?Bxt(t.basePath):[],...Bxt(e.basePath),...Bxt(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability),explode:c.explode})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability)})),responseHeaders:i.responseHeaders?.map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability)})),request:i.requestBody!=null?TNu(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(TNu).filter(gs)},response:i.response!=null?ohs(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(ohs).filter(gs)},errors:void 0,errorsV2:nXh(i.errors,t),examples:s,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:c=>({type:"openrpc",methodName:i.id,paramStructure:eXh(c.paramStructure)}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground,subtitle:i.subtitle??void 0};KYh(a,i),n.push(a)}return n}function KYh(e,t){let r=t.v2Examples?.userSpecifiedExamples;if(r==null||Object.keys(r).length===0)return;let n=e;n.v2Examples={userSpecifiedExamples:r,autogeneratedExamples:{}}}function JYh(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let n=Object.entries(e.v2Examples.userSpecifiedExamples),i=Object.entries(e.v2Examples.autogeneratedExamples),o=n.length>0?n[0]:i[0];if(o!=null){let[s,a]=o;r.push({name:s,description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(c=>({type:en.WebSocketMessageId(c.type),body:c.body}))??[]})}}else r=e.examples.map(n=>({name:Jke(n.name),description:n.docs,path:n.url,pathParameters:n.pathParameters.reduce((i,o)=>(i[en.PropertyKey(jr(o.name))]=o.value.jsonExample,i),{}),queryParameters:n.queryParameters.reduce((i,o)=>(i[cr(o.name)]=o.value.jsonExample,i),{}),headers:n.headers.reduce((i,o)=>(i[cr(o.name)]=o.value.jsonExample,i),{}),messages:n.messages.map(i=>({type:en.WebSocketMessageId(i.type),body:i.body.jsonExample}))}));return{auth:e.auth,availability:cE(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?en.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?$Yh({environmentsConfig:t.environments,channel:e}):[],id:en.WebSocketId(jr(e.name)),name:e.displayName??Qze(jr(e.name)),path:{pathParameters:e.pathParameters.map(n=>({description:n.docs??void 0,key:en.PropertyKey(jr(n.name)),type:uf(n.valueType),availability:void 0,explode:n.explode})),parts:Bxt(e.path)},headers:e.headers.map(n=>({key:cr(n.name),type:uf(n.valueType,n.defaultValue),description:n.docs,availability:cE(n.availability)})),queryParameters:e.queryParameters.map(n=>({description:n.docs??void 0,key:cr(n.name),type:uf(n.valueType,n.defaultValue),availability:cE(n.availability),explode:n.explode})),messages:e.messages.map(n=>({type:en.WebSocketMessageId(n.type),displayName:n.displayName,origin:n.origin,body:lXh(n.body),description:n.docs,availability:cE(n.availability)})),examples:r,includeInApiExplorer:e.apiPlayground}}function YYh(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>en.AuthSchemeId(r))}function XYh(e,t,r){return e==null?t!=null&&t.requirement==="ANY"&&t.schemes.length>0?t.schemes.map(n=>({schemes:[en.AuthSchemeId(n.key)]})):void 0:e.length===0?[]:e.map(n=>{let i=Object.keys(n).map(s=>en.AuthSchemeId(s));if(!r)return{schemes:i};let o=Object.fromEntries(Object.entries(n).filter(([,s])=>s.length>0).map(([s,a])=>[en.AuthSchemeId(s),[...new Set(a)]]));return Object.keys(o).length>0?{schemes:i,scopes:o}:{schemes:i}})}function cE(e){if(e!=null)switch(e.status){case"DEPRECATED":return en.Availability.Deprecated;case"LEGACY":return en.Availability.Legacy;case"PRE_RELEASE":case"BETA":return en.Availability.Beta;case"GENERAL_AVAILABILITY":return en.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return en.Availability.Beta;case"ALPHA":return en.Availability.Alpha;case"PREVIEW":return en.Availability.Preview;default:Ye(e.status)}}function ZYh({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl,i=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(o=>({id:en.EnvironmentId(o.id),baseUrl:o.url,audiences:o.audiences}));case"multipleBaseUrls":if(i!=null)return i.flatMap(s=>r.environments.map(a=>{let c=a.urls[s];if(c==null)throw new T({message:`Encountered undefined server name "${s}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${a.id} to contain url for ${s}`,code:T.Code.ValidationError});return{id:en.EnvironmentId(s),baseUrl:c,audiences:a.audiences}})).filter((s,a,c)=>a===c.findIndex(l=>l.id===s.id&&l.baseUrl===s.baseUrl));if(n==null)throw new T({message:`Expected endpoint ${jr(t.name)} to have base url.`,code:T.Code.IrConversionError});return r.environments.map(o=>{let s=o.urls[n];if(s==null)throw new T({message:`Encountered undefined server name "${n}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${o.id} to contain url for ${n}`,code:T.Code.ValidationError});return{id:en.EnvironmentId(o.id),baseUrl:s,audiences:o.audiences}});default:Ye(r)}}function $Yh({environmentsConfig:e,channel:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:en.EnvironmentId(i.id),baseUrl:tXh(i.url,"wss"),audiences:i.audiences}));case"multipleBaseUrls":if(n==null)throw new T({message:`Expected channel ${jr(t.name)} to have base url.`,code:T.Code.IrConversionError});return r.environments.map(i=>{let o=i.urls[n];if(o==null)throw new T({message:`Encountered undefined server name ${o} at channel ${jr(t.name)} ${t.path.head}. Expected environment ${i.id} to contain url for ${n}`,code:T.Code.IrConversionError});return{id:en.EnvironmentId(i.id),baseUrl:o,audiences:i.audiences}});default:Ye(r)}}function eXh(e){switch(e){case"BY_NAME":return"by-name";case"BY_POSITION":return"by-position";case"EITHER":return"either";case void 0:return;default:Ye(e)}}function tXh(e,t){return e.replace(/^[^:]+/,t)}function rXh(e){return $t.http.HttpMethod._visit(e,{get:()=>en.HttpMethod.Get,post:()=>en.HttpMethod.Post,put:()=>en.HttpMethod.Put,patch:()=>en.HttpMethod.Patch,delete:()=>en.HttpMethod.Delete,head:()=>en.HttpMethod.Head,_other:()=>{throw new T({message:"Unknown http method: "+e,code:T.Code.InternalError})}})}function Bxt(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:en.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function TNu(e){let t=$t.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??gp.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>en.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),availability:cE(n.availability),propertyAccess:n.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??gp.APPLICATION_JSON,shape:{type:"reference",value:uf(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:jr(r.name),description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let o=i._visit({file:s=>({type:"file",key:en.PropertyKey(cr(s.key)),isOptional:s.isOptional,contentType:s.contentType,description:s.docs??void 0,availability:void 0}),fileArray:s=>({type:"fileArray",key:en.PropertyKey(cr(s.key)),isOptional:s.isOptional,contentType:s.contentType,description:s.docs??void 0,availability:void 0}),_other:()=>{}});if(o!=null)return{type:"file",value:o}},bodyProperty:i=>({type:"bodyProperty",key:en.PropertyKey(cr(i.name)),valueType:uf(i.valueType,i.defaultValue),contentType:i.contentType,description:i.docs??void 0,availability:cE(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(gs)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new T({message:"Unknown HttpRequestBody: "+e.type,code:T.Code.InternalError})}});return t!=null?{type:t,description:e.docs}:void 0}function ohs(e){let t=e.docs,r;return e.body!=null&&(r=$t.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:uf(n.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:uf(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:uf(n.payload)},terminator:n.terminator}},_other:()=>{throw new T({message:"Unknown HttpResponse: "+e.body,code:T.Code.InternalError})}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function nXh(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:uf(i.type)},statusCode:i.statusCode,isWildcard:i.isWildcardStatusCode===!0?!0:void 0,description:i.docs??void 0,name:i.displayName??jr(i.name.name),availability:void 0,examples:PNu(i,t),headers:i.headers!=null&&i.headers.length>0?i.headers.map(o=>({description:o.docs??void 0,key:cr(o.name),type:uf(o.valueType,o.defaultValue),availability:cE(o.availability)})):void 0})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let o=[{key:en.PropertyKey(cr(t.errorDiscriminationStrategy.discriminant)),valueType:{type:"literal",value:{type:"stringLiteral",value:jr(sfi(i.discriminantValue))}},description:i.docs,availability:void 0,propertyAccess:void 0}];i.type!=null&&o.push({key:en.PropertyKey(cr(t.errorDiscriminationStrategy.contentProperty)),valueType:uf(i.type),description:i.docs,availability:void 0,propertyAccess:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:o,extraProperties:void 0},statusCode:i.statusCode,isWildcard:i.isWildcardStatusCode===!0?!0:void 0,description:i.docs??void 0,availability:void 0,name:i.displayName??jr(i.name.name),examples:i.examples.map(s=>({name:Jke(s.name),responseBody:{type:"json",value:s.jsonExample},description:s.docs})),headers:i.headers!=null&&i.headers.length>0?i.headers.map(s=>({description:s.docs??void 0,key:cr(s.name),type:uf(s.valueType,s.defaultValue),availability:cE(s.availability)})):void 0})}}return r}function ahs(e){let t={};for(let r of e??[]){let n=Object.values(r.v2Examples?.userSpecifiedExamples??{})[0]??Object.values(r.v2Examples?.autogeneratedExamples??{})[0];n!==void 0&&(t[cr(r.name)]=n)}return Object.keys(t).length>0?t:void 0}function iXh({irEndpoint:e,ir:t,statusCode:r}){let n;for(let i of e.errors??[]){let o=t.errors[i.error.errorId];if(o!=null){if(o.isWildcardStatusCode!==!0&&o.statusCode===r)return o.headers;o.isWildcardStatusCode===!0&&Math.floor(o.statusCode/100)===Math.floor(r/100)&&(n=o)}}return n?.headers}function oXh({irEndpoint:e,ir:t,examples:r}){let n=r.find(s=>s.responseStatusCode<400)??r[0];if(n==null)return[];let i=new Set(r.map(s=>s.responseStatusCode)),o=[];for(let s of e.errors??[]){let a=t.errors[s.error.errorId];if(a==null||a.isWildcardStatusCode===!0||i.has(a.statusCode))continue;let c=ahs(a.headers);c!=null&&(o.push({...n,name:void 0,description:void 0,codeSamples:void 0,responseStatusCode:a.statusCode,responseBody:void 0,responseBodyV3:PNu(a,t)[0]?.responseBody,responseHeaders:c}),i.add(a.statusCode))}return o}function ONu({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:n,irService:i,ir:o}){if(r==null)return;let s=d=>{if(d.valueType.type==="container"&&d.valueType.container.type==="literal")return d.valueType.container.literal._visit({boolean:f=>`${f}`,string:f=>f,_other:()=>{}});if(d.valueType.type==="container"&&d.valueType.container.type==="optional"&&d.valueType.container.optional.type==="container"&&d.valueType.container.optional.container.type==="literal")return d.valueType.container.optional.container.literal._visit({boolean:f=>`${f}`,string:f=>f,_other:()=>{}})},a={};o.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)}),i.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)}),n.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)});let c=r.response?.body!=null?r.response.body.value:void 0,l=r.response?.statusCode??n.response?.statusCode??200,u=n.response?.statusCode??200,p=l>=400?iXh({irEndpoint:n,ir:o,statusCode:l}):l===u?n.responseHeaders:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let f={...r.request?.headers??{}};for(let[m,g]of Object.entries(a))(f[m]===null||f[m]===void 0)&&(f[m]=g);return f})(),requestBody:r.request?.requestBody,requestBodyV3:n.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:d=>{if(r.request==null)return;let f={};if(oi(r.request.requestBody)){let m=r.request.requestBody;for(let g of d.properties)g._visit({file:A=>{let b=m[cr(A.key)];if(A.type==="file")f[cr(A.key)]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(A.type==="fileArray"){let I=(Array.isArray(b)?b:[b]).filter(C=>typeof C=="string");f[cr(A.key)]={type:"filenames",value:I}}},bodyProperty:A=>{if(A.style==="exploded"){let b=m[cr(A.name)];f[cr(A.name)]={type:"exploded",value:Array.isArray(b)?b:[b]}}else f[cr(A.name)]={type:"json",value:m[cr(A.name)]}},_other:SU})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:l,responseBody:c??void 0,responseBodyV3:c!=null?r.response?.body?._visit({json:d=>({type:"json",value:d}),stream:d=>Array.isArray(d)&&d.length>0&&d.every(sXh)?{type:"sse",value:d}:{type:"stream",value:d},error:()=>{},_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+r.response?.body?.type,code:T.Code.InternalError})}}):void 0,responseHeaders:ahs(p),codeSamples:r.codeSamples?.map(d=>({name:d.name,description:d.docs??void 0,install:void 0,language:d.language,code:d.code})).filter(gs)}}function sXh(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function ihs({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(c=>{let l;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?l=c.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(l=c.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})),l!=null)return{name:c.name,value:{jsonExample:l,shape:$t.ExampleTypeReferenceShape.primitive($t.ExamplePrimitive.string({original:l}))}}}).filter(gs),o=e?.example??t?.example;if(o==null)return;let{codeSamples:s}=e??{codeSamples:[]},a=$t.http.ExampleResponse._visit(o.response,{ok:()=>r.responseHeaders,error:({error:c})=>n.errors[c.errorId]?.headers,_other:()=>r.responseHeaders});return{name:Jke(o.name),description:o.docs,path:o.url,pathParameters:[...o.rootPathParameters,...o.servicePathParameters,...o.endpointPathParameters].reduce((c,l)=>(c[en.PropertyKey(jr(l.name))]=l.value.jsonExample,c),{}),queryParameters:o.queryParameters.reduce((c,l)=>(c[cr(l.name)]=l.value.jsonExample,c),{}),headers:[...i,...o.serviceHeaders,...o.endpointHeaders].reduce((c,l)=>(c[cr(l.name)]=l.value.jsonExample,c),{}),requestBody:o.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>o.request!=null?{type:"json",value:o.request.jsonExample}:void 0,reference:()=>o.request!=null?{type:"json",value:o.request.jsonExample}:void 0,fileUpload:c=>{if(o.request==null)return;let l={};if(oi(o.request.jsonExample)){let u=o.request.jsonExample;for(let p of c.properties)p._visit({file:d=>{let f=u[cr(d.key)];if(d.type==="file")l[cr(d.key)]={type:"filename",value:typeof f=="string"?f:"<file1>"};else if(d.type==="fileArray"){let m=(Array.isArray(f)?f:[f]).filter(g=>typeof g=="string");l[cr(d.key)]={type:"filenames",value:m}}},bodyProperty:d=>{if(d.style==="exploded"){let f=u[cr(d.name)];l[cr(d.name)]={type:"exploded",value:Array.isArray(f)?f:[f]}}else l[cr(d.name)]={type:"json",value:u[cr(d.name)]}},_other:SU})}return{type:"form",value:l}},bytes:()=>{},_other:()=>{}}),responseStatusCode:$t.http.ExampleResponse._visit(o.response,{ok:c=>r.response?.statusCode??c._visit({body:l=>l!=null?200:204,stream:l=>l.length>0?200:204,sse:l=>l.length>0?200:204,_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+c.type,code:T.Code.InternalError})}}),error:({error:c})=>{let l=n.errors[c.errorId];if(l==null)throw new T({message:"Cannot find error "+c.errorId,code:T.Code.ResolutionError});return l.statusCode},_other:()=>{throw new T({message:"Unknown ExampleResponse: "+o.response.type,code:T.Code.InternalError})}}),responseBody:o.response._visit({ok:c=>c._visit({body:l=>l?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:o.response._visit({ok:c=>c._visit({body:l=>l!=null?{type:"json",value:l.jsonExample}:void 0,stream:l=>({type:"stream",value:l.map(u=>u.jsonExample)}),sse:l=>({type:"sse",value:l.map(({event:u,data:p})=>({event:u,data:p.jsonExample}))}),_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+c.type,code:T.Code.InternalError})}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new T({message:"Unknown ExampleResponse: "+o.response.type,code:T.Code.InternalError})}}),responseHeaders:ahs(a),codeSamples:s?.map(c=>B_._visit(c,{language:l=>({language:l.language,code:l.code,name:Jke(l.name),description:l.docs??void 0,install:l.install}),sdk:l=>({language:l.sdk,code:l.code,name:Jke(l.name),description:l.docs??void 0,install:void 0}),_other:()=>{}})).filter(gs)}}function aXh(e,t){return t!=null?{type:{type:"formData",name:jr(t.name),description:t.docs??void 0,availability:void 0,properties:t.properties.map(r=>r._visit({file:n=>{let i=n._visit({file:o=>({type:"file",key:en.PropertyKey(cr(o.key)),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:en.PropertyKey(cr(o.key)),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(i!=null)return{type:"file",value:i}},bodyProperty:n=>({type:"bodyProperty",key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),contentType:n.contentType,description:n.docs??void 0,availability:cE(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(gs)},description:t.docs??void 0}:cXh(e)}function cXh(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>en.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:en.PropertyKey(cr(t.name)),valueType:uf(t.valueType),availability:cE(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:uf(e.payloadType)},description:e.docs};default:Ye(e)}}function lXh(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>en.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:en.PropertyKey(cr(t.name)),valueType:uf(t.valueType),availability:cE(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:uf(e.bodyType)};default:Ye(e)}}function PNu(e,t){let r=e.v2Examples?.userSpecifiedExamples,n=e.v2Examples?.autogeneratedExamples,i=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([s,a])=>({name:s,responseBody:{type:"json",value:a},description:void 0}));if(n!=null&&Object.keys(n).length>0)return Object.entries(n).map(([s,a])=>({name:s,responseBody:{type:"json",value:a},description:void 0}));if(i.length>0)return i.map(s=>({name:Jke(s.name),responseBody:{type:"json",value:s.jsonExample},description:s.docs}));let o=uXh(e,t);return o!=null?[o]:[]}function uXh(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,n=t.types[r];if(n==null||n.shape.type!=="object")return;let i={},o=!1;for(let s of n.shape.properties){let a=cr(s.name),c=s.v2Examples;if(c?.userSpecifiedExamples!=null){let l=Object.values(c.userSpecifiedExamples);if(l.length>0){i[a]=l[0],o=!0;continue}}if(c?.autogeneratedExamples!=null){let l=Object.values(c.autogeneratedExamples);if(l.length>0){i[a]=l[0];continue}}}if(o)return{name:void 0,responseBody:{type:"json",value:i},description:void 0}}var nhs=h(()=>{"use strict";mt();sm();zn();sc();Bt();xo();rhs();Pxt()});function kO({ir:e,snippetsConfig:t,playgroundConfig:r,graphqlOperations:n={},graphqlTypes:i={},context:o,apiNameOverride:s,showScopes:a=!1}){let c={types:{},subpackages:{},rootPackage:shs(e.rootPackage,e,n,i,{showScopes:a}),apiName:s??jr(e.apiName),auth:vNu({auth:e.auth,playgroundConfig:r,context:o}),authSchemes:xNu({auth:e.auth,playgroundConfig:r,context:o}),snippetsConfiguration:t,globalHeaders:e.headers.map(l=>({availability:cE(l.availability),description:l.docs??void 0,key:cr(l.name),type:uf(l.valueType,l.defaultValue)})),navigation:void 0};for(let[l,u]of Object.entries(e.types))c.types[en.TypeId(l)]={description:u.docs??void 0,name:jr(u.name.name),shape:wNu(u.shape,u.encoding?.xml),availability:cE(u.availability),displayName:u.name.displayName,examples:pXh(u)};for(let[l,u]of Object.entries(i))c.types[en.TypeId(l)]=u;for(let[l,u]of Object.entries(e.subpackages)){let p=u.service!=null?e.services[u.service]:void 0;c.subpackages[en.SubpackageId(l)]={subpackageId:en.SubpackageId(l),displayName:p?.displayName??u.displayName,name:jr(u.name),description:u.docs??void 0,...shs(u,e,void 0,void 0,{showScopes:a})}}return c}function pXh(e){let r=[e.userProvidedExamples.map(n=>n.jsonExample),Object.values(e.v2Examples?.userSpecifiedExamples??{}),fXh(e),Object.values(e.v2Examples?.autogeneratedExamples??{})].find(n=>n.length>0);return r??void 0}function fXh(e){if(e.shape.type!=="object")return[];let t={};for(let i of e.shape.properties){let[o]=Object.values(i.v2Examples?.userSpecifiedExamples??{});o!==void 0&&(t[cr(i.name)]=o)}if(Object.keys(t).length===0)return[];let[r]=Object.values(e.v2Examples?.autogeneratedExamples??{});return[{...gr(r)?r:{},...t}]}var chs=h(()=>{"use strict";mt();sm();SNu();nhs();rhs();Pxt()});async function lhs({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:o,playgroundConfig:s,graphqlOperations:a={},graphqlTypes:c={}}){let l=Yg({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Qh(r,t)}),u=MF({token:n.value}),p=kO({ir:l,snippetsConfig:o,playgroundConfig:s,graphqlOperations:a,graphqlTypes:c,context:r});try{let d=await u.api.register.registerApiDefinition({orgId:en.OrgId(e),apiId:en.ApiId(jr(l.apiName)),definition:p});return r.logger.debug(`Registered API Definition ${d.apiDefinitionId}`),{id:d.apiDefinitionId,ir:l}}catch(d){return r.failAndThrow("Failed to register API",d,{code:T.Code.NetworkError})}}var BNu=h(()=>{"use strict";tN();sf();sm();lp();Bt();chs();Pxt()});var Qge=h(()=>{"use strict";chs();BNu()});function UJt({ir:e,apiDefinitionId:t,playgroundConfig:r,context:n,graphqlOperations:i={},graphqlTypes:o={}}){return aH(oH(kO({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,graphqlOperations:i,graphqlTypes:o,context:n}),Chr.ApiDefinitionId(t),dXh))}var dXh,uhs=h(()=>{"use strict";sm();Qge();dXh=new sH({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}})});async function hS({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&DNu.default.isAbsolute(e)&&t.add(e)}async function RNu({parsedDocsConfig:e}){let t=new Set;if(e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.metadata?.["og:dynamic:background-image"]!=null&&e.metadata["og:dynamic:background-image"].type==="filepath"&&t.add(e.metadata["og:dynamic:background-image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&t.add(n.image)}),(await phs({navigation:e.navigation})).forEach(n=>{t.add(n)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async n=>{n.type==="dropdown"&&n.links.map(async i=>{i.icon&&await hS({iconPath:i.icon,filepaths:t}),i.rightIcon&&await hS({iconPath:i.rightIcon,filepaths:t})}),n.type!=="github"&&(n.icon&&await hS({iconPath:n.icon,filepaths:t}),n.rightIcon&&await hS({iconPath:n.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(n=>{t.add(n.absolutePath)}),e.context7File!=null&&t.add(e.context7File),e.llmsTxtFile!=null&&t.add(e.llmsTxtFile),e.llmsFullTxtFile!=null&&t.add(e.llmsFullTxtFile),e.robotsTxtFile!=null&&t.add(e.robotsTxtFile),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async n=>{n.icon!=null&&await hS({iconPath:n.icon,filepaths:t})})),e.translationNavigationOverlays!=null)for(let n of Object.values(e.translationNavigationOverlays))await mXh({navbarLinks:n.navbarLinks,filepaths:t});return t}async function mXh({navbarLinks:e,filepaths:t}){e!=null&&await Promise.all(e.map(async r=>{if(r.type!=="github"){if(r.type==="dropdown"){await Promise.all(r.links.map(async n=>{n.icon!=null&&await hS({iconPath:n.icon,filepaths:t}),n.rightIcon!=null&&await hS({iconPath:n.rightIcon,filepaths:t})})),r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.rightIcon!=null&&await hS({iconPath:r.rightIcon,filepaths:t});return}r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.rightIcon!=null&&await hS({iconPath:r.rightIcon,filepaths:t})}}))}async function phs({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>S8e({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(n=>S8e({item:n,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&(await Promise.all([...r.child.menu??[],...si.flattenNestedTabVariants(r.child.variants).flatMap(n=>n.nestedVariants?.menu??[])].flatMap(n=>n.type==="group"?n.children:[n]).flatMap(n=>n.type==="link"&&n.icon!=null?[hS({iconPath:n.icon,filepaths:t})]:[])),await Promise.all(si.flattenNestedTabVariants(r.child.variants).flatMap(n=>{let i=[];return n.icon!=null&&i.push(hS({iconPath:n.icon,filepaths:t})),i.push(...n.layout.map(o=>S8e({item:o,filepaths:t}))),i})))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await S8e({item:r.landingPage,filepaths:t}),(await phs({navigation:r.navigation})).forEach(i=>t.add(i))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await S8e({item:r.landingPage,filepaths:t}),(await phs({navigation:r.navigation})).forEach(i=>t.add(i)))})),e.changelog!=null&&await S8e({item:e.changelog,filepaths:t});break}return t}async function S8e({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>S8e({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break}}var DNu,kNu=h(()=>{"use strict";qn();DNu=Ae(require("path"),1)});async function FNu(e,t,r){let n=new Array(e.length),i=0,o=!1,s,a=async()=>{for(;i<e.length&&!o;){let l=i++;try{n[l]=await r(e[l],l)}catch(u){o||(o=!0,s=u)}}},c=Math.min(Math.max(1,Math.floor(t)),e.length);if(await Promise.all(Array.from({length:c},a)),o)throw s;return n}var NNu=h(()=>{"use strict"});function hXh(e,t,r){return e.replace(/\[([^\]]*)\]\(([^)]+\.mdx?(?:#[^)]*)?)\)/g,(n,i,o)=>{let s=o.indexOf("#"),a=s>=0?o.substring(0,s):o,c=s>=0?o.substring(s):"",l=K5e({href:a,metadata:r,markdownFilesToPathName:t});return l!=null&&l.type==="replace"?`[${i}](${l.slug}${c})`:n})}function afi(e,t,r){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)afi(i,t,r);return}let n=e;for(let[i,o]of Object.entries(n))typeof o=="string"&&o.includes(".md")?n[i]=hXh(o,t,r):typeof o=="object"&&afi(o,t,r)}function w8e(e,t,r){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)w8e(i,t,r);return}let n=e;n.apiDefinitionId===t&&(n.apiDefinitionId=r);for(let i of Object.values(n))typeof i=="object"&&w8e(i,t,r)}var fhs=h(()=>{"use strict";W3()});async function jNu({navigation:e,apiWorkspaces:t,visitor:r,context:n}){AXh(e)?await Promise.all(e.map(async i=>{jK(i)?await Promise.all(i.layout.map(async o=>{await cfi({navigationItem:o,visitor:r,apiWorkspaces:t,context:n})})):si.isRawTabWithVariantLayouts(i)&&await Promise.all(si.flattenRawTabLayouts(i).flatMap(({layout:o})=>o.map(async s=>{await cfi({navigationItem:s,visitor:r,apiWorkspaces:t,context:n})})))})):await Promise.all(e.map(async i=>{await cfi({navigationItem:i,visitor:r,apiWorkspaces:t,context:n})}))}async function cfi({navigationItem:e,visitor:t,apiWorkspaces:r,context:n}){if(await DU(e,{alphabetized:xt,sortByAvailability:xt,showScopes:xt,api:xt,apiName:xt,specs:xt,audiences:xt,displayErrors:xt,tagDescriptionPages:xt,snippets:xt,summary:xt,title:xt,layout:xt,collapsed:xt,icon:xt,slug:xt,hidden:xt,skipSlug:xt,paginated:xt,types:xt,playground:xt,flattened:xt,path:xt,page:xt,featureFlag:xt,openrpc:xt,postman:xt,contents:async i=>{i!=null&&await Promise.all(i.map(async o=>{await cfi({navigationItem:o,visitor:t,apiWorkspaces:r,context:n})}))},viewers:xt,orphaned:xt,availability:xt}),gXh(e)){let i=r.find(o=>o.workspaceName===e.apiName);i!=null&&await t.apiSection?.({config:e,workspace:i,context:n})}}function gXh(e){return e.api!=null}function AXh(e){return e[0]?.tab!=null}var zNu=h(()=>{"use strict";qn();mt()});function YN(e){return Yh(e)?e:`https://${e}`}var dhs=h(()=>{"use strict";mt()});function lfi(){let e=process.env.FERN_DOCS_API_REGISTRATION_CONCURRENCY?.trim();return e!=null&&/^[1-9]\d*$/.test(e)?Number(e):yXh}function vXh(e,t){let r=new WeakMap,n=(i,o)=>{if(Array.isArray(i)){for(let a of i)n(a,o);return}if(i==null||typeof i!="object"||r.has(i))return;let s="profile"in i&&typeof i.profile=="string"?i.profile:o;r.set(i,s);for(let a of Object.values(i))n(a,s)};for(let i of e)n(i,t);return r}function mhs(e){return typeof e=="string"?[e]:Array.isArray(e)?e.flatMap(mhs):e!=null&&typeof e=="object"?Object.values(e).flatMap(mhs):[]}function CXh(e){return new Set(e.filter(gs).flatMap(t=>Array.from(t.matchAll(IXh),r=>r[1])).filter(gs))}function xXh(e){if(e!=null)return{schema:e.schema,...e.name==null?{}:{name:e.name},...e.applyTo==null?{}:{"apply-to":e.applyTo},...e.ensure==null?{}:{ensure:e.ensure.map(t=>({"status-code":t.statusCode,...t.methods==null?{}:{methods:t.methods}}))}}}function SXh(e,t){let r=e?.launch;if(e?.github==null)return{url:void 0,launch:r};let{owner:n,repo:i,branch:o="main",host:s="https://github.com"}=e.github;return{url:`${YN(s)}/${n}/${i}/blob/${o}/fern/${t}?plain=1`,launch:r}}function wXh(e){return e==null||typeof e=="string"?e:{style:e.style,alignment:e.alignment?.toUpperCase(),placement:e.placement?.toUpperCase()}}function TXh(e){if(e!=null)return{enabled:e.enabled,order:e.order,hide:e.hide,labels:e.labels,"show-products":e.showProducts}}function OXh(e){return e==null||e.light==null&&e.dark==null?{}:{"code-blocks":{light:e.light,dark:e.dark}}}function PXh(e){let t=e.findIndex(n=>n.default===!0);if(t!==-1)return t;let r=e.findIndex(n=>n.hidden!==!0);return r===-1?0:r}function BXh(e){switch(e){case"beta":return Vt.V1.NavigationV1Availability.Beta;case"deprecated":return Vt.V1.NavigationV1Availability.Deprecated;case"ga":return Vt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Vt.V1.NavigationV1Availability.Stable;case"alpha":return Vt.V1.NavigationV1Availability.Alpha;case"preview":return Vt.V1.NavigationV1Availability.Preview;case"legacy":return Vt.V1.NavigationV1Availability.Legacy;default:Ye(e)}}function VNu(e){return e.flatMap(t=>{switch(t.type){case"page":case"link":return[t];case"section":case"package":{let r=VNu(t.contents);return r.length===0&&t.overviewAbsolutePath==null?[]:[{type:"section",title:t.title??(t.type==="package"?t.package:""),referencedSubpackages:[],overviewAbsolutePath:t.overviewAbsolutePath,contents:r,slug:t.slug??(t.type==="package"?Tu(t.package):void 0),hidden:t.hidden,icon:t.icon,skipUrlSlug:t.skipUrlSlug,collapsed:t.type==="section"?t.collapsed:void 0,collapsible:t.type==="section"?t.collapsible:void 0,collapsedByDefault:t.type==="section"?t.collapsedByDefault:void 0,availability:t.availability,playground:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}]}case"item":case"endpoint":case"operation":return[];default:Ye(t)}})}var MNu,LNu,_Nu,Dxt,Mge,UNu,yXh,bXh,QNu,EXh,IXh,XN,GNu=h(()=>{"use strict";vc();tN();qn();mt();W3();sm();tr();PWo();lp();sc();Id();qms();Bt();MNu=require("crypto"),LNu=Ae(sNt(),1),_Nu=Ae(aNt(),1),Dxt=require("fs"),Mge=require("fs/promises"),UNu=Ae(kQ(),1);Ko();xo();dNu();Yms();hNu();Qms();ANu();Mms();bNu();tfi();INu();uhs();kNu();NNu();fhs();zNu();dhs();LNu.default.extend(_Nu.default);yXh=4;bXh=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),QNu=0,EXh=async({ir:e})=>(QNu++,`${r4o(e.apiName)}-${QNu}`),IXh=/\$\\?\{(\w+)\\?\}/g;XN=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;onApiRegistrationQueued;onNavigationTreeBuilt;targetAudiences;docsVisibility;buildTranslatedApiDefinitions;buildRefVersions;skipApiReferences;cliVersion;cliName;refWorkspacesByFernFolder=new Map;markdownFilesToPathName={};constructor({domain:t,docsWorkspace:r,ossWorkspaces:n,apiWorkspaces:i,taskContext:o,editThisPage:s,uploadFiles:a=bXh,registerApi:c=EXh,onApiRegistrationQueued:l,onNavigationTreeBuilt:u,targetAudiences:p,docsVisibility:d="public",buildTranslatedApiDefinitions:f=!1,buildRefVersions:m=!0,skipApiReferences:g=!1,cliVersion:A,cliName:b="fern"}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=n,this.apiWorkspaces=i,this.taskContext=o,this.editThisPage=s,this.uploadFiles=a,this.registerApi=c,this.onApiRegistrationQueued=l,this.onNavigationTreeBuilt=u,this.targetAudiences=p,this.docsVisibility=d,this.buildTranslatedApiDefinitions=f,this.buildRefVersions=m,this.skipApiReferences=g,this.cliVersion=A,this.cliName=b}#e=ofi.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let n=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(n)})}:t}getRawProductAudiences(t){let n=this.docsWorkspace.config.products?.find(i=>i.displayName===t);return Q5t(n?.audiences)}getRawVersionAudiences(t){let n=this.docsWorkspace.config.versions?.find(i=>i.displayName===t);return Q5t(n?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new T({message:"parsedDocsConfig is not set",code:T.Code.InternalError});return this._parsedDocsConfig}getTranslationPages(){return this._parsedDocsConfig?.translationPages}getTranslationNavigationOverlays(){return this._parsedDocsConfig?.translationNavigationOverlays}getCollectedFileIds(){return this.collectedFileIds}getDocsWorkspacePath(){return this.docsWorkspace.absoluteFilePath}getSkippedApiDefinitions(){return this.skippedApiDefinitions}getTranslatedApiSpecs(){return this.translatedApiSpecs}getMarkdownFilesToPathName(){return this.markdownFilesToPathName}getDocsTranslationsConfig(){let t=this.parsedDocsConfig.translations;if(t==null||t.length===0)return;let r=t.map(i=>si.DocsYmlSchemas.normalizeTranslationConfig(i)),n=r.find(i=>i.default===!0)??r[0];if(n!=null)return{defaultLocale:n.lang,translations:r.map(i=>i.lang)}}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;markdownFilesToAvailability=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];pendingApiRegistrations=[];pendingApiCounter=0;skippedApiCounter=0;skippedApiDefinitions={};translatedApiSpecs=new Map;async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let n=performance.now();this._parsedDocsConfig=await k4e({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig,buildRefVersions:this.buildRefVersions});let i=performance.now()-n,o=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${i.toFixed(0)}ms: ${o} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[be.of(Nt)]=RO(rr);let s=this.parsedDocsConfig.experimental?.openapiParserV3,a=s!=null&&!s;if(this.docsWorkspace.config.navigation!=null&&a&&!this.skipApiReferences){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let Nt=performance.now();await jNu({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:ye})=>{(await ye.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0,docsVisibility:this.docsVisibility})).changelog?.files.forEach(Xe=>{let dt=go(this.docsWorkspace.absoluteFilePath,Xe.absoluteFilepath);this.parsedDocsConfig.pages[dt]=Xe.contents,this.rawMarkdownFiles[be.of(dt)]=RO(Xe.contents)})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let rr=performance.now()-Nt;this.taskContext.logger.debug(`Visited navigation AST in ${rr.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let c=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let l=performance.now()-c;this.taskContext.logger.debug(`Built markdown file maps in ${l.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),p=new Set,d=Object.entries(this.parsedDocsConfig.pages),f=[];for(let[,Nt]of d)f.push(...Upi(Nt));let m=Date.now(),g=await Vpi(f,this.taskContext);if(g.size>0){let Nt=new Set(f).size;this.taskContext.logger.info(`Prefetched ${Nt} external code URLs in ${Date.now()-m}ms`)}for(let[Nt,rr]of d){let ye=await qk({markdown:rr,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext});for(let dt of ye.referencedFiles)p.has(dt.absoluteFilePath)||(p.add(dt.absoluteFilePath),this.referencedMarkdownFiles.push(dt));let ge=await G3({markdown:ye.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext,urlCache:g}),Xe=q3({markdown:ge,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext});this.parsedDocsConfig.pages[be.of(Nt)]=Xe}let A=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${A.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let b=performance.now(),I=await RNu({parsedDocsConfig:this.parsedDocsConfig}),C=performance.now()-b;this.taskContext.logger.debug(`Collected ${I.size} files in ${C.toFixed(0)}ms`);let x=await yNu({absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});x.length>0&&(this.taskContext.logger.debug(`Collected ${x.length} well-known agent skills files`),x.forEach(Nt=>I.add(Nt))),this.taskContext.logger.debug("Parsing image paths from markdown files...");let S=performance.now();for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:ye,markdown:ge}=tY(rr,{absolutePathToMarkdownFile:this.resolveFilepath(Nt),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[be.of(Nt)]=ge;for(let Xe of ye)I.add(Xe)}catch(ye){throw this.taskContext.logger.error(`Failed to parse ${Nt}: ${rn(ye)}`),new T({message:`Failed to parse markdown file ${Nt}: ${rn(ye)}`,code:T.Code.ParseError})}let P=performance.now()-S;this.taskContext.logger.debug(`Parsed image paths in ${P.toFixed(0)}ms`);let D=Array.from(I).map(Nt=>({absoluteFilePath:Nt,relativeFilePath:this.toRelativeFilepath(Nt)}));this.taskContext.logger.info(`Uploading ${D.length} files...`);let R=performance.now(),O=await this.uploadFiles(D),j=performance.now()-R;this.taskContext.logger.info(`Uploaded ${O.length} files in ${j.toFixed(0)}ms`),O.forEach(Nt=>{this.collectedFileIds.set(Nt.absoluteFilePath,Nt.fileId)}),this.resolveTranslationOverlayNavbarLinkIcons(),this.taskContext.logger.debug("Building navigation tree...");let Y=performance.now(),ee=await this.toRootNode(),te=performance.now()-Y;this.taskContext.logger.debug(`Built navigation tree in ${te.toFixed(0)}ms`),this.onNavigationTreeBuilt?.(),this.taskContext.logger.debug("Getting fully qualified path names...");let ce=performance.now(),le=await this.getMarkdownFilesToFullyQualifiedPathNames(ee);this.markdownFilesToPathName=le;let ae=performance.now()-ce;if(this.taskContext.logger.debug(`Got path names in ${ae.toFixed(0)}ms`),this.pendingApiRegistrations.length>0){this.taskContext.logger.debug(`Processing ${this.pendingApiRegistrations.length} deferred API registrations...`);let Nt=performance.now(),rr=this.pendingApiRegistrations,ye=[],ge=new Map;for(let ut of rr){this.resolveLinksInIrDocs(ut.ir,le);let Ue=ut.workspace?.getSources().map(ot=>[ot.absoluteFilePath,ot.absoluteFilePathToOverrides]),ze=(0,MNu.createHash)("sha256").update(JSON.stringify({ir:ut.ir,snippetsConfig:ut.snippetsConfig,playgroundConfig:ut.playgroundConfig,apiName:ut.apiName,workspace:Ue,graphqlOperations:ut.graphqlOperations,graphqlTypes:ut.graphqlTypes,showScopes:ut.showScopes})).digest("hex");ye.push(ze),ge.has(ze)||ge.set(ze,ut)}let Xe=[...ge.entries()],dt=await FNu(Xe,lfi(),async([,ut])=>await this.registerApi({ir:ut.ir,snippetsConfig:ut.snippetsConfig,playgroundConfig:ut.playgroundConfig,apiName:ut.apiName,workspace:ut.workspace,graphqlOperations:ut.graphqlOperations,graphqlTypes:ut.graphqlTypes,showScopes:ut.showScopes})),Ce=new Map(Xe.map(([ut],Ue)=>[ut,dt[Ue]]));for(let[ut,Ue]of rr.entries()){let ze=ye[ut],ot=ze!=null?Ce.get(ze):void 0;if(ot==null)throw new Error(`Registering API ${Ue.apiName??Ue.tempApiDefinitionId} returned no definition id`);if(w8e(Ue.apiReferenceNode,Ue.tempApiDefinitionId,ot),Ue.translatedIrsByLocale!=null)for(let[bt,ir]of Ue.translatedIrsByLocale){this.resolveLinksInIrDocs(ir,le);let Tn=this.translatedApiSpecs.get(bt);Tn==null&&(Tn=new Map,this.translatedApiSpecs.set(bt,Tn)),Tn.set(ot,{ir,snippetsConfig:Ue.snippetsConfig,playgroundConfig:Ue.playgroundConfig,apiName:Ue.apiName,graphqlOperations:Ue.graphqlOperations,graphqlTypes:Ue.graphqlTypes,showScopes:Ue.showScopes,workspace:Ue.workspace})}}let we=performance.now()-Nt;this.taskContext.logger.debug(`Processed deferred API registrations in ${we.toFixed(0)}ms`),this.pendingApiRegistrations=[]}this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let he=performance.now();for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))try{this.parsedDocsConfig.pages[be.of(Nt)]=M3(rr,this.collectedFileIds,le,{absolutePathToMarkdownFile:this.resolveFilepath(Nt),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext)}catch(ye){throw new T({message:`Failed to replace image paths in markdown file ${Nt}: ${rn(ye)}`,code:T.Code.ParseError})}let xe=performance.now()-he;this.taskContext.logger.debug(`Replaced image paths in ${xe.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let Te={};Object.entries(this.parsedDocsConfig.pages).forEach(([Nt,rr])=>{let{url:ye,launch:ge}=SXh(this.editThisPage,Nt),Xe=this.rawMarkdownFiles[be.of(Nt)];Te[JS.PageId(Nt)]={markdown:RO(rr),editThisPageUrl:ye?JS.Url(ye):void 0,editThisPageLaunch:ge,rawMarkdown:Xe}}),this.taskContext.logger.debug("Converting docs configuration...");let pe=performance.now(),{root:ue,...Pe}=await this.convertDocsConfiguration(ee),Ie=this.profileScope(this.parsedDocsConfig.profile).forNode({texts:[...mhs(Pe),ue?.title]}),je={...Pe,root:ue!=null?{...ue,...Ie}:ue},_e=performance.now()-pe;this.taskContext.logger.debug(`Converted docs configuration in ${_e.toFixed(0)}ms`);let at={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let Nt=performance.now(),rr=await Ypi({absolutePathToDocsWorkspace:this.docsWorkspace.absoluteFilePath,mdxComponents:this._parsedDocsConfig.experimental.mdxComponents});at=Object.fromEntries(await Promise.all(rr.map(async ge=>{let Xe=this.toRelativeFilepath(ge),dt=(await(0,Mge.readFile)(ge)).toString();return[Xe,await this.bundleJsFileContents(ge,dt)]})));let ye=performance.now()-Nt;this.taskContext.logger.debug(`Processed ${rr.length} MDX component files in ${ye.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let Nt of this.referencedMarkdownFiles)at[Nt.relativeFilePath]=Nt.content}if(this._parsedDocsConfig.header!=null){let Nt=this.toRelativeFilepath(this._parsedDocsConfig.header),rr=(await(0,Mge.readFile)(this._parsedDocsConfig.header)).toString();at[Nt]=await this.bundleJsFileContents(this._parsedDocsConfig.header,rr),this.taskContext.logger.debug(`Added custom header component: ${Nt}`)}if(this._parsedDocsConfig.footer!=null){let Nt=this.toRelativeFilepath(this._parsedDocsConfig.footer),rr=(await(0,Mge.readFile)(this._parsedDocsConfig.footer)).toString();at[Nt]=await this.bundleJsFileContents(this._parsedDocsConfig.footer,rr),this.taskContext.logger.debug(`Added custom footer component: ${Nt}`)}let Ct=performance.now()-t,Et=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${Ct.toFixed(0)}ms, Memory delta: RSS=${((Et.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:je,pages:Te,jsFiles:at}}resolveFilepath(t){if(t!=null)return Rn(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return go(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,n]of Object.entries(t)){let i=(0,UNu.default)(n),o=this.resolveFilepath(r),s=i.data.slug;if(typeof s=="string"&&s.trim().length>0){let p=s.trim();nxt(p)?this.markdownFilesToFullSlugs.set(o,p):this.taskContext.logger.warn(`Ignoring absolute URL slug "${p}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let a=i.data["sidebar-title"];typeof a=="string"&&a.trim().length>0&&this.markdownFilesToSidebarTitle.set(o,a.trim());let c=i.data.noindex;typeof c=="boolean"&&this.markdownFilesToNoIndex.set(o,c);let l=i.data.tags;typeof l=="string"?this.markdownFilesToTags.set(o,l.split(",").map(p=>p.trim()).filter(p=>p.length>0)):Array.isArray(l)&&this.markdownFilesToTags.set(o,l);let u=i.data.availability;if(typeof u=="string"){let p=this.parseAvailabilityFromFrontmatter(u);p!=null&&this.markdownFilesToAvailability.set(o,p)}}}parseAvailabilityFromFrontmatter(t){switch(t.toLowerCase().trim()){case"stable":return"stable";case"generally-available":return"generally-available";case"in-development":return"in-development";case"pre-release":return"pre-release";case"deprecated":return"deprecated";case"beta":return"beta";default:this.taskContext.logger.warn(`Invalid availability value "${t}" in frontmatter. Valid values are: stable, generally-available, in-development, pre-release, deprecated, beta`);return}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},n=Vt.migrate.FernNavigationV1ToLatest.create().root(t),i=new Set;Vt.traverseDF(n,a=>{a.type==="version"&&!a.default&&i.add(a.slug)});let o=a=>{let c=a.split("/");return c.some((l,u)=>i.has(c.slice(0,u+1).join("/")))};return Vt.NodeCollector.collect(n).slugMap.forEach((a,c)=>{if(a==null||!Vt.isPage(a))return;let l=Vt.getPageId(a);if(l==null)return;let u=Re(this.docsWorkspace.absoluteFilePath,be.of(l)),p=r[u];(p==null||o(p)&&!o(c))&&(r[u]=c)}),r}getDocsBasePath(){return new URL(YN(this.domain)).pathname}async convertDocsConfiguration(t){let r=this.parsedDocsConfig.integrations!=null||this.parsedDocsConfig.context7File!=null?{...this.parsedDocsConfig.integrations,context7:this.getFileId(this.parsedDocsConfig.context7File)}:void 0;return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location?.filter(i=>i==="slack"||i==="docs"),datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title})),maskPii:this.parsedDocsConfig.aiChatConfig.maskPii,disclaimer:this.parsedDocsConfig.aiChatConfig.disclaimer,buttonText:this.parsedDocsConfig.aiChatConfig.buttonText}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?JS.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(o=>({...o,url:JS.Url(o.url),icon:this.resolveIconFileId(o.icon),rightIcon:this.resolveIconFileId(o.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:JS.Url(i.url)}:{...i,url:JS.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.convertDocsSettings(),css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),agents:this.parsedDocsConfig.agents!=null||this.parsedDocsConfig.llmsTxtFile!=null||this.parsedDocsConfig.llmsFullTxtFile!=null||this.parsedDocsConfig.robotsTxtFile!=null||this.parsedDocsConfig.experimental?.robotsTxtOnInstanceUrl===!0?{...this.parsedDocsConfig.agents,llmsTxt:this.getFileId(this.parsedDocsConfig.llmsTxtFile),llmsFullTxt:this.getFileId(this.parsedDocsConfig.llmsFullTxtFile),robotsTxt:this.getFileId(this.parsedDocsConfig.robotsTxtFile),robotsTxtOnInstanceUrl:this.parsedDocsConfig.experimental?.robotsTxtOnInstanceUrl}:void 0,metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,remotePaths:this.parsedDocsConfig.remotePaths,integrations:r,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:JS.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,translations:this.getDocsTranslationsConfig(),analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch,embedding:this.parsedDocsConfig.settings?.embedding!=null?{allowedOrigins:this.parsedDocsConfig.settings.embedding.allowedOrigins}:void 0,pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:wXh(this.parsedDocsConfig.theme.tabs),"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher,"site-switcher":TXh(this.parsedDocsConfig.theme.siteSwitcher),...OXh(this.parsedDocsConfig.theme.codeBlocks)}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:this.parsedDocsConfig.header?this.toRelativeFilepath(this.parsedDocsConfig.header):void 0,footer:this.parsedDocsConfig.footer?this.toRelativeFilepath(this.parsedDocsConfig.footer):void 0}}async bundleJsFileContents(t,r){try{return await Jpi({absoluteFilePath:t,contents:r,context:this.taskContext})??r}catch(n){throw new T({message:`Failed to bundle third-party imports in ${t}: ${rn(n)}`,code:T.Code.ParseError})}}async resolveApiWorkspaces(t){if(t==null)return{apiWorkspaces:this.apiWorkspaces,ossWorkspaces:this.ossWorkspaces};let r=t.absolutePathToFernFolder,n=this.refWorkspacesByFernFolder.get(r);if(n!=null)return n;if(this.cliVersion==null)throw new T({message:`Cannot load API definitions for version '${t.displayVersion}' (ref '${t.ref}'): the CLI version is unavailable in this context.`,code:T.Code.InternalError});let i=this.cliVersion,o=(async()=>{let s=await $pi({cliName:this.cliName,fernDirectory:r,context:this.taskContext,cliVersion:i,commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),a=s.filter(c=>c instanceof Il);return{apiWorkspaces:s,ossWorkspaces:a}})();return this.refWorkspacesByFernFolder.set(r,o),o}getFernWorkspaceForApiSection(t,r){if(t.apiName!=null){let i=r.find(o=>o.workspaceName===t.apiName);if(i!=null)return i}else if(r.length===1&&r[0]!=null)return r[0];let n=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
1863
|
+
${i.description}`;return this.#d.set(s,c),this.markdownFilesToNoIndex.set(s,!1),this.markdownFilesToTags.set(s,[n]),a}#b(t,r,n,i){r=this.#e.resolveSubpackage(r);let o=r!=null?Kke.getSubpackageId(r):void 0;return t.map(s=>GX(s)._visit({link:a=>({id:this.#p.get(a.url),type:"link",collapsed:void 0,title:a.text,icon:this.resolveIconFileId(a.icon),url:Vt.Url(a.url),target:a.target}),page:a=>this.#E(a,n,i),package:a=>this.#C(a,n,i),section:a=>this.#I(a,n,i),item:({value:a})=>this.#y(a,o,n,i),endpoint:a=>this.#v(a,o,n,i),operation:a=>this.#x(a,o,n,i)})).filter(gs)}#E(t,r,n){return{...lNu({page:{...t,availability:t.availability??n},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#p,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)}),...this.profileVars.forNode({texts:[t.title],absolutePath:t.absolutePath,pageProfile:t.profile})}}#C(t,r,n){let i=t.overviewAbsolutePath!=null?Vt.V1.PageId(Oxt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,s=t.availability??n,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let c=Kke.getSubpackageId(a),l=i??this.createTagDescriptionPageId(a,t.package),u=this.#p.get(l??`${this.apiDefinitionId}:${c}`);this.#s.has(c)&&this.taskContext.logger.warn(nfi(t.package)),this.#s.add(c),this.#a.set(u,[c]);let p=t.slug??(sY(a)?a.urlSlug:this.apiSection.slug??Tu(this.apiSection.title)),d=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:p}),f=this.#b(t.contents,a,d,s);return{id:u,type:"apiPackage",collapsed:void 0,children:f,title:t.title??(sY(a)?a.displayName??yP(a.name):this.apiSection.title),slug:d.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:l,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(s),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...i!=null?this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath}):this.#g(l)}}else{this.taskContext.logger.warn(rfi(t.package,this.#e.subpackageLocators));let c=t.slug??Tu(t.package),l=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),u=this.#b(t.contents,void 0,l,s);return{id:this.#p.get(i??`${this.apiDefinitionId}:${Tu(t.package)}`),type:"apiPackage",collapsed:void 0,children:u,title:t.title??t.package,slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:i,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(s),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath})}}}#I(t,r,n){let i=t.overviewAbsolutePath!=null?Vt.V1.PageId(Oxt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,s=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,a=this.#p.get(i??o??r.get()),c=t.referencedSubpackages.map(f=>{let m=this.#e.getSubpackageByIdOrLocator(f),g=m!=null?Kke.getSubpackageId(m):void 0;if(g===void 0){this.taskContext.logger.error(rfi(f,this.#e.subpackageLocators));return}return{subpackageId:g,locator:f}}).filter(f=>f!=null).filter(gs);this.#a.set(a,c.map(f=>f.subpackageId)),c.forEach(f=>{this.#s.has(f.subpackageId)&&this.taskContext.logger.error(nfi(f.locator)),this.#s.add(f.subpackageId)});let l=t.slug??Tu(t.title),u=r.apply({fullSlug:o?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),p=t.availability??n,d=this.#b(t.contents,void 0,u,p);return{id:a,type:"apiPackage",children:d,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:i,collapsed:t.collapsed,collapsible:t.collapsible,collapsedByDefault:t.collapsedByDefault,availability:Mh(p),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:s,playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,...this.profileVars.forNode({texts:[t.title],absolutePath:t.overviewAbsolutePath})}}#y(t,r,n,i){t=t.trim();let o=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(ao(t));if(o!=null){let s=Kke.getSubpackageId(o),a=this.#p.get(`${this.apiDefinitionId}:${s}`),c=this.createTagDescriptionPageId(o,t);this.#s.has(s)&&this.taskContext.logger.error(nfi(t)),this.#s.add(s),this.#a.set(a,[s]);let l=sY(o)?o.urlSlug:"",u=n.apply({urlSlug:l});return{id:a,type:"apiPackage",collapsed:void 0,children:[],title:sY(o)?o.displayName??yP(o.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,...this.#g(c),overviewPageId:c,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(i),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#v({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,n,i)}#v(t,r,n,i){let o=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.endpoints.get(Fb.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(o!=null){let l=this.#e.getEndpointId(o);if(l==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let u=t.slug!=null?n.append(t.slug):n.apply(o);return{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",collapsed:void 0,method:o.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(o.availability)??Mh(i),isResponseStream:o.response?.type.type==="stream",title:t.title??o.name??Wk(o.path.parts),slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#R(o.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let s=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.webSockets.get(Fb.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(s!=null){let l=this.#e.getWebSocketId(s);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${s.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",collapsed:void 0,webSocketId:l,title:t.title??s.name??Wk(s.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(s)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(s.availability)??Mh(i),playground:this.#R(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(Fb.SubpackageId(r))?.webhooks.get(Fb.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Vt.V1.WebhookId(t.endpoint));if(a!=null){let l=this.#e.getWebhookId(a);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#p.get(`${this.apiDefinitionId}:${l}`),type:"webhook",collapsed:void 0,webhookId:l,method:a.method,title:t.title??a.name??(0,fNu.default)("/",...a.path),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Mh(t.availability)??Vt.V1.convertAvailability(a.availability)??Mh(i),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=this.#e.api.rootPackage.graphqlOperations?.find(l=>l.id===t.endpoint||l.name===t.endpoint);if(c!=null){let l=Fb.GraphQlOperationId(c.id);if(this.#o.has(l)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${l}`);return}this.#o.add(l);let u=t.slug!=null?n.append(t.slug):n.append(c.name??c.id);return this.#k({id:this.#p.get(`${this.apiDefinitionId}:${l}`),operationType:c.operationType,graphqlOperationId:Fb.GraphQlOperationId(c.id),title:t.title??c.displayName??c.name??c.id,slug:u.get(),availability:t.availability??i,icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#R(t.playground),viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags})}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#x(t,r,n,i){let o=t.operation.trim().split(/\s+/,2);if(o.length!==2){this.taskContext.logger.error(`Invalid operation format in the API Reference layout: ${t.operation}. Expected format: "OPERATION_TYPE operationName" (e.g., "QUERY account")`);return}let[s,a]=o;if(!a){this.taskContext.logger.error(`Invalid operation format in the API Reference layout: ${t.operation}. Expected format: "OPERATION_TYPE operationName" (e.g., "QUERY account")`);return}let c=this.#e.api.rootPackage.graphqlOperations??[],l=c.filter(f=>{if(f.operationType!==s)return!1;if(a.includes(".")){if(f.id===a||f.name===a)return!0;let m=a.split("."),g=m[m.length-1],A=m.slice(0,-1).join(".");if(f.name===g||f.id===g)return f.id.startsWith(A+".")||this.#u.get(en.GraphQlOperationId(f.id))===A}else return f.name===a||f.id===a;return!1});if(!a.includes(".")){let f=c.filter(m=>m.operationType===s&&(m.name===a||m.id===a));if(f.length>1){let m=f.map(g=>{let A=this.#u.get(en.GraphQlOperationId(g.id));if(A)return`"${s} ${A}.${a}"`;let b=g.id.split("_");if(b.length>=3){let I=b[0];return`"${s} ${I}.${a}"`}return`"${s} ${g.id}"`}).join(", ");this.taskContext.logger.warn(`Ambiguous operation reference: "${t.operation}". Found ${f.length} operations with name "${a}". Using first match: "${m.split(", ")[0]}". Please use the full namespaced format for clarity. Available options: ${m}`)}}let u=l[0];if(u==null){this.taskContext.logger.error(`GraphQL operation not found in the API Reference layout: ${t.operation}`);return}let p=Fb.GraphQlOperationId(u.id);if(this.#o.has(p)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${p}`);return}this.#o.add(p);let d=t.slug!=null?n.append(t.slug):n.append(u.name??u.id);return this.#k({id:this.#p.get(`${this.apiDefinitionId}:${p}`),operationType:u.operationType,graphqlOperationId:Fb.GraphQlOperationId(u.id),title:t.title??u.displayName??u.name??u.id,slug:d.get(),availability:t.availability??i,hidden:this.hideChildren||t.hidden,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags})}#w(t,r){return iNu({left:t,right:r,findEndpointById:n=>this.#e.endpoints.get(n),stringifyEndpointPathParts:n=>Wk(n.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#A(t,r){return Xms({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(n,i,o)=>this.#N(n,i,o),mergeAndFilterChildren:this.#w.bind(this)})}#O(t,r,n){let i=[];if(t.endpoints.forEach(o=>{if(o.protocol?.type==="grpc"){let s=this.#e.getGrpcId(o);if(s==null){this.taskContext.logger.error(`Expected Grpc ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);return}if(this.#i.has(s))return;let a=r.apply(o);i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"grpc",collapsed:void 0,grpcId:s,title:o.name??Wk(o.path.parts),method:o.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:Mh(n),slug:a.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let s=this.#e.getEndpointId(o);if(s==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${o.id} at path: ${efi(o.method,o.path.parts)}. Got undefined.`);return}if(this.#t.has(s))return;let a=r.apply(o);i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"endpoint",collapsed:void 0,method:o.method,endpointId:s,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),isResponseStream:o.response?.type.type==="stream",title:o.name??Wk(o.path.parts),slug:a.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(o=>{let s=this.#e.getWebSocketId(o);if(s==null){this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);return}this.#r.has(s)||i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"webSocket",collapsed:void 0,webSocketId:s,title:o.name??Wk(o.path.parts),slug:r.apply(o).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(o=>{let s=this.#e.getWebhookId(o);if(s==null){this.taskContext.logger.error(`Expected Webhook ID for ${o.id}. Got undefined.`);return}this.#n.has(s)||i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${s}`),type:"webhook",collapsed:void 0,webhookId:s,method:o.method,title:o.name??yP(o.id),slug:r.apply(o).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(n),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(o=>{if(this.#s.has(o))return;let s=this.#e.getSubpackageByIdOrLocator(o);if(s==null){this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`);return}let a=sY(s)?r.apply(s):r,c=this.#N(o,a,n),l=this.createTagDescriptionPageId(s),u=this.#e.subpackages.get(Fb.SubpackageId(o)),p=u?Array.from(u.endpoints.values()).some(d=>{let f=this.#e.getEndpointId(d);return f!=null&&this.#t.has(f)}):!1;(c.length>0||l!=null&&p)&&i.push({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",collapsed:void 0,children:c,title:sY(s)?s.displayName??yP(s.name):this.apiSection.title,slug:a.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:l,...this.#g(l),collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.graphqlOperations!=null&&t.graphqlOperations.length>0){let o=this.#P(t.graphqlOperations,r,n);i.push(...o)}if(t===this.#e.api.rootPackage){let o=this.#S(r,n);if(o!=null&&i.push(o),this.apiSection.types){let s=this.#Q(r,n);s!=null&&i.push(s)}}return i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((o,s)=>{let a=o.type==="endpointPair"?o.nonStream.title:o.title,c=s.type==="endpointPair"?s.nonStream.title:s.title;return a.localeCompare(c)})),this.apiSection.sortByAvailability!=null&&(i=aNu(i,this.apiSection.sortByAvailability)),i}#P(t,r,n){let i={},o={};for(let l of t){let u=Fb.GraphQlOperationId(l.id);if(this.#o.has(u))continue;this.#o.add(u);let p=this.#u.get(en.GraphQlOperationId(l.id)),d=l.operationType;p!=null?(i[p]==null&&(i[p]={}),i[p][d]==null&&(i[p][d]=[]),i[p][d].push(l)):(o[d]==null&&(o[d]=[]),o[d].push(l))}let s=[],a=["QUERY","MUTATION","SUBSCRIPTION"],c={QUERY:"Queries",MUTATION:"Mutations",SUBSCRIPTION:"Subscriptions"};for(let[l,u]of Object.entries(i)){let p=r.append(Tu(l)),d=[];for(let m of a){let g=u[m];if(g==null||g.length===0)continue;let A=c[m],b=p.append(Tu(A)),I=this.#F(g,b,n,m),C={id:this.#p.get(`${this.apiDefinitionId}:graphql:${l}:${m}`),type:"apiPackage",collapsed:void 0,children:I,title:A,slug:b.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};d.push(C)}let f={id:this.#p.get(`${this.apiDefinitionId}:graphql:namespace:${l}`),type:"apiPackage",collapsed:void 0,children:d,title:yP(l),slug:p.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};s.push(f)}for(let l of a){let u=o[l];if(u==null||u.length===0)continue;let p=c[l],d=r.append(Tu(p)),f=this.#F(u,d,n,l),m={id:this.#p.get(`${this.apiDefinitionId}:graphql:${l}`),type:"apiPackage",collapsed:void 0,children:f,title:p,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(n),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};s.push(m)}return s}#S(t,r){let n=new Map;for(let[s,a]of Object.entries(this.#m)){let c=en.TypeId(s);if(this.#e.api.types[c]==null)continue;let l=n.get(a);l!=null?l.push(c):n.set(a,[c])}if(n.size===0)return;let i=t.append(OYh),o=[];for(let{category:s,title:a,urlSlug:c}of TYh){let l=n.get(s);if(l==null||l.length===0)continue;let u=i.append(c),p=l.map(d=>this.#j(d,s,u,r)).filter(gs).sort((d,f)=>d.title.localeCompare(f.title));p.length!==0&&o.push({id:this.#p.get(`${this.apiDefinitionId}:graphql:types:${s}`),type:"apiPackage",collapsed:void 0,children:p,title:a,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}if(o.length!==0)return{id:this.#p.get(`${this.apiDefinitionId}:graphql:types`),type:"apiPackage",collapsed:void 0,children:o,title:kYh,slug:i.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#B(){let t=this.#e.api,r=new Set,n=[],i=o=>{r.has(o)||(r.add(o),n.push(o))};for(let o of[t.rootPackage,...Object.values(t.subpackages)])o.endpoints.forEach(s=>Vt.ApiTypeIdVisitor.visitEndpointDefinition(s,i)),o.websockets.forEach(s=>Vt.ApiTypeIdVisitor.visitWebSocketChannel(s,i)),o.webhooks.forEach(s=>Vt.ApiTypeIdVisitor.visitWebhookDefinition(s,i)),o.graphqlOperations?.forEach(s=>Vt.ApiTypeIdVisitor.visitGraphQlOperation(s,i));for(let o=n.shift();o!=null;o=n.shift()){let s=t.types[o];s!=null&&Vt.ApiTypeIdVisitor.visitTypeDefinition(s,i)}return r}#Q(t,r){let n=this.#B(),i=Object.keys(this.#m).length>0,o=t.append(i?BYh:PYh),s=new Set,a=Object.keys(this.#e.api.types).map(c=>en.TypeId(c)).filter(c=>!n.has(c)&&this.#m[c]==null&&!this.#h.has(c)).sort((c,l)=>{let u=this.#e.api.types[c]?.displayName??this.#e.api.types[c]?.name??c,p=this.#e.api.types[l]?.displayName??this.#e.api.types[l]?.name??l;return u.localeCompare(p,"en")||c.localeCompare(l,"en")}).map(c=>this.#D(c,o,s,r)).filter(gs);if(a.length!==0)return{id:this.#p.get(`${this.apiDefinitionId}:types`),type:"apiPackage",collapsed:void 0,children:a,title:i?RYh:DYh,slug:o.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,collapsible:void 0,collapsedByDefault:void 0,availability:Mh(r),apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#D(t,r,n,i){let o=this.#e.api.types[t];if(o==null)return;let s=o.displayName??o.name??t,a=Tu(s),c=a;for(let l=2;n.has(c);l++)c=`${a}-${l}`;return n.add(c),{id:this.#p.get(`${this.apiDefinitionId}:apiType:${t}`),type:"apiType",collapsed:void 0,typeId:Vt.TypeId(t),title:s,slug:r.append(c).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#j(t,r,n,i){let o=this.#e.api.types[t];if(o==null)return;let s=o.displayName??o.name??t;return{id:this.#p.get(`${this.apiDefinitionId}:graphqlType:${t}`),type:"graphqlType",collapsed:void 0,typeId:Vt.TypeId(t),typeCategory:r,title:s,slug:n.append(Tu(s)).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Vt.V1.convertAvailability(o.availability)??Mh(i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}#k({id:t,operationType:r,graphqlOperationId:n,graphqlOperationIds:i,title:o,slug:s,availability:a,hidden:c,icon:l,playground:u,viewers:p,orphaned:d,featureFlags:f}){return{id:t,type:"graphql",collapsed:void 0,operationType:r,graphqlOperationId:n,graphqlOperationIds:i,apiDefinitionId:this.apiDefinitionId,availability:Mh(a),title:o,slug:s,icon:l,hidden:c,playground:u,authed:void 0,viewers:p,orphaned:d,featureFlags:f}}#F(t,r,n,i){let o=i==="QUERY",s=new Map,a=[];for(let u of t){let p=ths(u)?.[0];if(o&&p!=null){let d=s.get(p);d!=null?d.push(u):(s.set(p,[u]),a.push({type:"group",parentField:p}))}else a.push({type:"flat",operation:u})}let c=new Map;for(let u of a)if(u.type==="flat"){let p=pNu(u.operation);s.has(p)&&ths(u.operation)==null&&c.set(p,u.operation)}let l=[];for(let u of a)if(u.type==="flat"){let p=pNu(u.operation);if(c.has(p))continue;let d=ths(u.operation),f=r;if(d!=null&&d.length>0)for(let m of d)f=f.append(Tu(m));f=f.append(Tu(p)),l.push(this.#k({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${u.operation.id}`),operationType:u.operation.operationType,graphqlOperationId:Fb.GraphQlOperationId(u.operation.id),title:u.operation.displayName??u.operation.name??u.operation.id,slug:f.get(),availability:n,hidden:this.hideChildren}))}else{let p=s.get(u.parentField)??[],f=c.get(u.parentField)??p[0];if(f==null)continue;let m=r.append(Tu(u.parentField));l.push(this.#k({id:Vt.V1.NodeId(`${this.apiDefinitionId}:${f.id}`),operationType:f.operationType,graphqlOperationId:Fb.GraphQlOperationId(f.id),graphqlOperationIds:p.map(g=>Fb.GraphQlOperationId(g.id)),title:u.parentField,slug:m.get(),availability:n,hidden:this.hideChildren}))}return l}#N(t,r,n){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.debug(rfi(t||"unknown",[])),[]):this.#O(i,r,n)}#R(t){return G2u(t)}mergeEndpointPairs(t){return ifi({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>Wk(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t,void 0,{code:T.Code.InternalError})}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}}});function FYh(e){return mNu.default.createHash("sha256").update(e).digest("hex")}var mNu,ofi,hNu=h(()=>{"use strict";sm();Bt();mNu=Ae(require("crypto"),1);ofi=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),FYh(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),n=0;for(;this.#t.has(r);)if(r=this.#r(t),n++,n>100)throw new T({message:`Infinite loop detected for id: ${t}`,code:T.Code.ReferenceError});return r}get(t){return Vt.V1.NodeId(this.#n(t))}}});function gNu(e){let t=new Set;for(let[r,n]of Object.entries(e.types))n.inline===!0&&t.add(en.TypeId(r));return t}var ANu=h(()=>{"use strict";sm()});async function yNu({absolutePathToFernFolder:e}){let t=[];for(let r of NYh){let n=Re(e,r);if(await Ut(n)){let i=await UFt(n);t.push(...i.map(Zt.of))}}return t}var NYh,bNu=h(()=>{"use strict";tr();NYh=[be.of(".well-known/skills"),be.of(".well-known/agent-skills")]});function ENu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0,cliSdk:e.cli!=null?{package:typeof e.cli=="string"?e.cli:e.cli.package,version:typeof e.cli=="string"?void 0:e.cli.version}:void 0}}var INu=h(()=>{"use strict"});function sfi(e){return typeof e=="string"?e:e.name}function Jke(e){if(e!=null)return typeof e=="string"?e:e.originalName}var Pxt=h(()=>{"use strict";sc()});function vNu({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];return CNu({scheme:n,playgroundConfig:t,context:r})}}function CNu({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:jr(e.password),usernameName:jr(e.username),description:e.docs,playgroundDescription:e.playgroundDocs,passwordAlwaysEmpty:e.passwordOmit};case"bearer":return{type:"bearerAuth",tokenName:jr(e.token),description:e.docs,playgroundDescription:e.playgroundDocs};case"header":return{type:"header",headerWireValue:cr(e.name),nameOverride:jr(sfi(e.name)),prefix:e.prefix,description:e.docs,playgroundDescription:e.playgroundDocs};case"oauth":{let n=e.configuration;if(n.type!=="clientCredentials")return{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs};let i=n.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(o=>jr(o.name)).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:en.EndpointId(n.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:i,headerName:n.tokenHeader,tokenPrefix:n.tokenPrefix,description:e.docs,playgroundDescription:e.playgroundDocs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let n=e.tokenEndpoint.authenticatedRequestHeaders.find(o=>o.headerName.toLowerCase()==="authorization");if(n)return n.responseProperty.propertyPath!=null&&n.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:cr(n.responseProperty.property.name),description:e.docs,playgroundDescription:e.playgroundDocs};let i=e.tokenEndpoint.authenticatedRequestHeaders[0];return i?{type:"header",headerWireValue:i.headerName,prefix:i.valuePrefix,nameOverride:void 0,description:e.docs,playgroundDescription:e.playgroundDocs}:{type:"bearerAuth",tokenName:"token",description:e.docs,playgroundDescription:e.playgroundDocs}}default:Ye(e)}}function xNu({auth:e,playgroundConfig:t,context:r}){let n={};for(let i of e.schemes){let o=CNu({scheme:i,playgroundConfig:t,context:r});o!=null&&(n[en.AuthSchemeId(i.key)]=o)}return n}var SNu=h(()=>{"use strict";mt();sm();Pxt()});function wNu(e,t){return e._visit({alias:r=>({type:"alias",value:uf(r.aliasOf)}),enum:r=>({type:"enum",default:r.default!=null?cr(r.default.name):void 0,values:r.values.map(n=>({description:n.docs??void 0,value:cr(n.name),availability:cE(n.availability)}))}),object:r=>({type:"object",extends:r.extends.map(n=>en.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),availability:cE(n.availability),propertyAccess:n.propertyAccess,...n.xml!=null?{xml:GYh(n.xml)}:{}})),extraProperties:VYh(r.extraProperties),...t!=null?{xml:{name:t.name,namespace:t.namespace,prefix:t.prefix}}:{}}),union:r=>{let n=r.baseProperties.map(i=>({key:en.PropertyKey(cr(i.name)),valueType:uf(i.valueType,i.defaultValue),availability:cE(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:cr(r.discriminant),variants:r.types.map(i=>({description:i.docs??void 0,discriminantValue:cr(i.discriminantValue),displayName:i.displayName,availability:i.availability!=null?cE(i.availability):void 0,additionalProperties:$t.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:o=>({extends:[en.TypeId(o.typeId)],properties:n,extraProperties:void 0}),singleProperty:o=>({extends:[],properties:[{key:en.PropertyKey(cr(o.name)),valueType:uf(o.type),description:void 0,availability:void 0,propertyAccess:void 0},...n],extraProperties:void 0}),noProperties:()=>({extends:[],properties:n,extraProperties:void 0}),_other:()=>{throw new T({message:"Unknown SingleUnionTypeProperties: "+i.shape.propertiesType,code:T.Code.InternalError})}})}))}},undiscriminatedUnion:r=>({type:"undiscriminatedUnion",variants:r.members.map(n=>({typeName:n.type.type==="named"?jr(n.type.name):void 0,description:n.docs??void 0,type:uf(n.type),availability:void 0,displayName:n.type.type==="named"?n.type.displayName:void 0}))}),_other:()=>{throw new T({message:"Unknown Type shape: "+e.type,code:T.Code.InternalError})}})}function uf(e,t){return e._visit({container:r=>$t.types.ContainerType._visit(r,{list:n=>({type:"list",itemType:uf(n),minItems:void 0,maxItems:void 0}),map:({keyType:n,valueType:i})=>({type:"map",keyType:uf(n),valueType:uf(i),minProperties:void 0,maxProperties:void 0}),optional:n=>({type:"optional",itemType:uf(n),defaultValue:t}),nullable:n=>({type:"nullable",itemType:uf(n)}),set:n=>({type:"set",itemType:uf(n),minItems:void 0,maxItems:void 0}),literal:n=>$t.types.Literal._visit(n,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new T({message:"Unknown literal type: "+n.type,code:T.Code.InternalError})}}),_other:()=>{throw new T({message:"Unknown container reference: "+r.type,code:T.Code.InternalError})}}),named:r=>({type:"id",value:en.TypeId(r.typeId),default:void 0}),primitive:r=>({type:"primitive",value:$t.types.PrimitiveTypeV1._visit(r.v1,{integer:()=>zYh(r.v2),float:()=>QYh(r.v2),double:()=>MYh(r.v2),string:()=>jYh(r.v2),long:()=>LYh(r.v2),boolean:()=>({type:"boolean",default:r.v2?.type==="boolean"?r.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:r.v2?.type==="bigInteger"?r.v2.default:void 0}),uint:()=>_Yh(r.v2),uint64:()=>UYh(r.v2),dateTimeRfc2822:()=>({type:"datetime",default:void 0}),_other:()=>{throw new T({message:"Unknown primitive: "+r.v1,code:T.Code.InternalError})}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new T({message:"Unknown Type reference: "+e.type,code:T.Code.InternalError})}})}function jYh(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function zYh(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="integer"?e.default:void 0}}function QYh(e){return{type:"scalar",name:"float",description:void 0,default:e!=null&&e.type==="float"?e.default:void 0}}function MYh(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="double"?e.default:void 0}}function LYh(e){let t=e!=null&&e.type==="long"?e.validation:void 0;return{type:"long",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="long"?e.default:void 0}}function _Yh(e){let t=e!=null&&e.type==="uint"?e.validation:void 0;return{type:"uint",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint"?e.default:void 0}}function UYh(e){let t=e!=null&&e.type==="uint64"?e.validation:void 0;return{type:"uint64",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint64"?e.default:void 0}}function VYh(e){return typeof e=="boolean"?e?Hr.unknown():void 0:typeof e=="string"?{type:"id",value:en.TypeId(e),default:void 0}:uf(e)}function GYh(e){if(e!=null)return{kind:qYh(e.kind),name:e.name,wrapped:e.wrapped,listSeparator:e.listSeparator}}function qYh(e){switch(e){case"ATTRIBUTE":return"attribute";case"TEXT":return"text";case"ELEMENT":return"element";default:Ye(e)}}var rhs=h(()=>{"use strict";mt();sm();zn();Bt();nhs();Pxt()});function shs(e,t,r,n,i={}){let o=e.service!=null?t.services[e.service]:void 0,s=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,a=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:o!=null?HYh(o,t,i):[],webhooks:s!=null?WYh(s):[],websockets:a!=null?[JYh(a,t)]:[],types:[...e.types.map(l=>en.TypeId(l)),...Object.keys(n??{}).map(l=>en.TypeId(l))],subpackages:e.subpackages.map(l=>en.SubpackageId(l)),pointsTo:e.navigationConfig!=null?en.SubpackageId(e.navigationConfig.pointsTo):void 0,graphqlOperations:r?Object.values(r):[]}}function WYh(e){return e.map(t=>{let r=[];if(t.v2Examples!=null){for(let[n,i]of Object.entries(t.v2Examples.userSpecifiedExamples))r.push({name:i.name??n,payload:i.payload});for(let[n,i]of Object.entries(t.v2Examples.autogeneratedExamples))r.push({name:i.name??n,payload:i.payload})}else r.push(...t.examples?.map(n=>({name:Jke(n.name),payload:n.payload.jsonExample}))??[]);return{description:t.docs??void 0,availability:cE(t.availability),id:en.WebhookId(jr(t.name)),path:[],method:t.method,name:t.displayName??Qze(jr(t.name)),headers:t.headers.map(n=>({description:n.docs??void 0,key:cr(n.name),type:uf(n.valueType,n.defaultValue),availability:cE(n.availability)})),payload:aXh(t.payload,t.fileUploadPayload),examples:r,responses:t.responses?.map(ohs).filter(gs)}})}function HYh(e,t,r){let n=[];for(let i of e.endpoints){let o=i.autogeneratedExamples[0],s=[];if(i.v2Examples!=null){let c,l=i.v2Examples.userSpecifiedExamples,u=i.v2Examples.autogeneratedExamples,p=Object.values(l).map(f=>f.response?.statusCode).filter((f,m,g)=>g.indexOf(f)!==m).length>0;for(let[f,m]of Object.entries(l))c=ONu({shouldUseExampleName:m.displayName!=null||p,exampleName:m.displayName??f,example:m,irEndpoint:i,irService:e,ir:t}),c!=null&&s.push(c);let d=Object.values(u).map(f=>f.response?.statusCode).filter((f,m,g)=>g.indexOf(f)!==m).length>0;for(let[f,m]of Object.entries(u))c=ONu({shouldUseExampleName:d,exampleName:m.displayName??f,example:m,irEndpoint:i,irService:e,ir:t}),c!=null&&s.push(c)}else if(i.userSpecifiedExamples.length>0)s.push(...i.userSpecifiedExamples.map(c=>ihs({userSpecifiedExample:c,...o!=null&&{autogeneratedExample:o},irEndpoint:i,ir:t})).filter(gs));else if(o!=null){let c=ihs({autogeneratedExample:o,irEndpoint:i,ir:t});c!=null&&s.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=Dat({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let l=ihs({autogeneratedExample:c,irEndpoint:i,ir:t});if(l!=null){let u={...l,responseBodyV3:{type:"filename",value:"<bytes>"}};s.push(u)}}}s.push(...oXh({irEndpoint:i,ir:t,examples:s}));let a={slug:void 0,availability:cE(i.availability??e.availability),auth:i.auth,authV2:YYh(i.security),multiAuth:XYh(i.security,t.auth,r.showScopes??!1),description:i.docs??void 0,method:rXh(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?en.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ZYh({environmentsConfig:t.environments,endpoint:i}):void 0,id:en.EndpointId(jr(i.name)),originalEndpointId:i.id,name:i.displayName??Qze(jr(i.name)),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:en.PropertyKey(jr(c.name)),type:uf(c.valueType),availability:void 0,explode:c.explode})),parts:[...Bxt(i.basePath),...Bxt(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:en.PropertyKey(jr(c.name)),type:uf(c.valueType),availability:void 0,explode:c.explode})),parts:[...t.basePath!=null?Bxt(t.basePath):[],...Bxt(e.basePath),...Bxt(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability),explode:c.explode})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability)})),responseHeaders:i.responseHeaders?.map(c=>({description:c.docs??void 0,key:cr(c.name),type:uf(c.valueType,c.defaultValue),availability:cE(c.availability)})),request:i.requestBody!=null?TNu(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(TNu).filter(gs)},response:i.response!=null?ohs(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(ohs).filter(gs)},errors:void 0,errorsV2:nXh(i.errors,t),examples:s,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:c=>({type:"openrpc",methodName:i.id,paramStructure:eXh(c.paramStructure)}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground,subtitle:i.subtitle??void 0};KYh(a,i),n.push(a)}return n}function KYh(e,t){let r=t.v2Examples?.userSpecifiedExamples;if(r==null||Object.keys(r).length===0)return;let n=e;n.v2Examples={userSpecifiedExamples:r,autogeneratedExamples:{}}}function JYh(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let n=Object.entries(e.v2Examples.userSpecifiedExamples),i=Object.entries(e.v2Examples.autogeneratedExamples),o=n.length>0?n[0]:i[0];if(o!=null){let[s,a]=o;r.push({name:s,description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(c=>({type:en.WebSocketMessageId(c.type),body:c.body}))??[]})}}else r=e.examples.map(n=>({name:Jke(n.name),description:n.docs,path:n.url,pathParameters:n.pathParameters.reduce((i,o)=>(i[en.PropertyKey(jr(o.name))]=o.value.jsonExample,i),{}),queryParameters:n.queryParameters.reduce((i,o)=>(i[cr(o.name)]=o.value.jsonExample,i),{}),headers:n.headers.reduce((i,o)=>(i[cr(o.name)]=o.value.jsonExample,i),{}),messages:n.messages.map(i=>({type:en.WebSocketMessageId(i.type),body:i.body.jsonExample}))}));return{auth:e.auth,availability:cE(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?en.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?$Yh({environmentsConfig:t.environments,channel:e}):[],id:en.WebSocketId(jr(e.name)),name:e.displayName??Qze(jr(e.name)),path:{pathParameters:e.pathParameters.map(n=>({description:n.docs??void 0,key:en.PropertyKey(jr(n.name)),type:uf(n.valueType),availability:void 0,explode:n.explode})),parts:Bxt(e.path)},headers:e.headers.map(n=>({key:cr(n.name),type:uf(n.valueType,n.defaultValue),description:n.docs,availability:cE(n.availability)})),queryParameters:e.queryParameters.map(n=>({description:n.docs??void 0,key:cr(n.name),type:uf(n.valueType,n.defaultValue),availability:cE(n.availability),explode:n.explode})),messages:e.messages.map(n=>({type:en.WebSocketMessageId(n.type),displayName:n.displayName,origin:n.origin,body:lXh(n.body),description:n.docs,availability:cE(n.availability)})),examples:r,includeInApiExplorer:e.apiPlayground}}function YYh(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>en.AuthSchemeId(r))}function XYh(e,t,r){return e==null?t!=null&&t.requirement==="ANY"&&t.schemes.length>0?t.schemes.map(n=>({schemes:[en.AuthSchemeId(n.key)]})):void 0:e.length===0?[]:e.map(n=>{let i=Object.keys(n).map(s=>en.AuthSchemeId(s));if(!r)return{schemes:i};let o=Object.fromEntries(Object.entries(n).filter(([,s])=>s.length>0).map(([s,a])=>[en.AuthSchemeId(s),[...new Set(a)]]));return Object.keys(o).length>0?{schemes:i,scopes:o}:{schemes:i}})}function cE(e){if(e!=null)switch(e.status){case"DEPRECATED":return en.Availability.Deprecated;case"LEGACY":return en.Availability.Legacy;case"PRE_RELEASE":case"BETA":return en.Availability.Beta;case"GENERAL_AVAILABILITY":return en.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return en.Availability.Beta;case"ALPHA":return en.Availability.Alpha;case"PREVIEW":return en.Availability.Preview;default:Ye(e.status)}}function ZYh({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl,i=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(o=>({id:en.EnvironmentId(o.id),baseUrl:o.url,audiences:o.audiences}));case"multipleBaseUrls":if(i!=null)return i.flatMap(s=>r.environments.map(a=>{let c=a.urls[s];if(c==null)throw new T({message:`Encountered undefined server name "${s}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${a.id} to contain url for ${s}`,code:T.Code.ValidationError});return{id:en.EnvironmentId(s),baseUrl:c,audiences:a.audiences}})).filter((s,a,c)=>a===c.findIndex(l=>l.id===s.id&&l.baseUrl===s.baseUrl));if(n==null)throw new T({message:`Expected endpoint ${jr(t.name)} to have base url.`,code:T.Code.IrConversionError});return r.environments.map(o=>{let s=o.urls[n];if(s==null)throw new T({message:`Encountered undefined server name "${n}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${o.id} to contain url for ${n}`,code:T.Code.ValidationError});return{id:en.EnvironmentId(o.id),baseUrl:s,audiences:o.audiences}});default:Ye(r)}}function $Yh({environmentsConfig:e,channel:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:en.EnvironmentId(i.id),baseUrl:tXh(i.url,"wss"),audiences:i.audiences}));case"multipleBaseUrls":if(n==null)throw new T({message:`Expected channel ${jr(t.name)} to have base url.`,code:T.Code.IrConversionError});return r.environments.map(i=>{let o=i.urls[n];if(o==null)throw new T({message:`Encountered undefined server name ${o} at channel ${jr(t.name)} ${t.path.head}. Expected environment ${i.id} to contain url for ${n}`,code:T.Code.IrConversionError});return{id:en.EnvironmentId(i.id),baseUrl:o,audiences:i.audiences}});default:Ye(r)}}function eXh(e){switch(e){case"BY_NAME":return"by-name";case"BY_POSITION":return"by-position";case"EITHER":return"either";case void 0:return;default:Ye(e)}}function tXh(e,t){return e.replace(/^[^:]+/,t)}function rXh(e){return $t.http.HttpMethod._visit(e,{get:()=>en.HttpMethod.Get,post:()=>en.HttpMethod.Post,put:()=>en.HttpMethod.Put,patch:()=>en.HttpMethod.Patch,delete:()=>en.HttpMethod.Delete,head:()=>en.HttpMethod.Head,_other:()=>{throw new T({message:"Unknown http method: "+e,code:T.Code.InternalError})}})}function Bxt(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:en.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function TNu(e){let t=$t.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??gp.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>en.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),availability:cE(n.availability),propertyAccess:n.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??gp.APPLICATION_JSON,shape:{type:"reference",value:uf(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:jr(r.name),description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let o=i._visit({file:s=>({type:"file",key:en.PropertyKey(cr(s.key)),isOptional:s.isOptional,contentType:s.contentType,description:s.docs??void 0,availability:void 0}),fileArray:s=>({type:"fileArray",key:en.PropertyKey(cr(s.key)),isOptional:s.isOptional,contentType:s.contentType,description:s.docs??void 0,availability:void 0}),_other:()=>{}});if(o!=null)return{type:"file",value:o}},bodyProperty:i=>({type:"bodyProperty",key:en.PropertyKey(cr(i.name)),valueType:uf(i.valueType,i.defaultValue),contentType:i.contentType,description:i.docs??void 0,availability:cE(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(gs)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new T({message:"Unknown HttpRequestBody: "+e.type,code:T.Code.InternalError})}});return t!=null?{type:t,description:e.docs}:void 0}function ohs(e){let t=e.docs,r;return e.body!=null&&(r=$t.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:uf(n.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:uf(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:uf(n.payload)},terminator:n.terminator}},_other:()=>{throw new T({message:"Unknown HttpResponse: "+e.body,code:T.Code.InternalError})}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function nXh(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:uf(i.type)},statusCode:i.statusCode,isWildcard:i.isWildcardStatusCode===!0?!0:void 0,description:i.docs??void 0,name:i.displayName??jr(i.name.name),availability:void 0,examples:PNu(i,t),headers:i.headers!=null&&i.headers.length>0?i.headers.map(o=>({description:o.docs??void 0,key:cr(o.name),type:uf(o.valueType,o.defaultValue),availability:cE(o.availability)})):void 0})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let o=[{key:en.PropertyKey(cr(t.errorDiscriminationStrategy.discriminant)),valueType:{type:"literal",value:{type:"stringLiteral",value:jr(sfi(i.discriminantValue))}},description:i.docs,availability:void 0,propertyAccess:void 0}];i.type!=null&&o.push({key:en.PropertyKey(cr(t.errorDiscriminationStrategy.contentProperty)),valueType:uf(i.type),description:i.docs,availability:void 0,propertyAccess:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:o,extraProperties:void 0},statusCode:i.statusCode,isWildcard:i.isWildcardStatusCode===!0?!0:void 0,description:i.docs??void 0,availability:void 0,name:i.displayName??jr(i.name.name),examples:i.examples.map(s=>({name:Jke(s.name),responseBody:{type:"json",value:s.jsonExample},description:s.docs})),headers:i.headers!=null&&i.headers.length>0?i.headers.map(s=>({description:s.docs??void 0,key:cr(s.name),type:uf(s.valueType,s.defaultValue),availability:cE(s.availability)})):void 0})}}return r}function ahs(e){let t={};for(let r of e??[]){let n=Object.values(r.v2Examples?.userSpecifiedExamples??{})[0]??Object.values(r.v2Examples?.autogeneratedExamples??{})[0];n!==void 0&&(t[cr(r.name)]=n)}return Object.keys(t).length>0?t:void 0}function iXh({irEndpoint:e,ir:t,statusCode:r}){let n;for(let i of e.errors??[]){let o=t.errors[i.error.errorId];if(o!=null){if(o.isWildcardStatusCode!==!0&&o.statusCode===r)return o.headers;o.isWildcardStatusCode===!0&&Math.floor(o.statusCode/100)===Math.floor(r/100)&&(n=o)}}return n?.headers}function oXh({irEndpoint:e,ir:t,examples:r}){let n=r.find(s=>s.responseStatusCode<400)??r[0];if(n==null)return[];let i=new Set(r.map(s=>s.responseStatusCode)),o=[];for(let s of e.errors??[]){let a=t.errors[s.error.errorId];if(a==null||a.isWildcardStatusCode===!0||i.has(a.statusCode))continue;let c=ahs(a.headers);c!=null&&(o.push({...n,name:void 0,description:void 0,codeSamples:void 0,responseStatusCode:a.statusCode,responseBody:void 0,responseBodyV3:PNu(a,t)[0]?.responseBody,responseHeaders:c}),i.add(a.statusCode))}return o}function ONu({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:n,irService:i,ir:o}){if(r==null)return;let s=d=>{if(d.valueType.type==="container"&&d.valueType.container.type==="literal")return d.valueType.container.literal._visit({boolean:f=>`${f}`,string:f=>f,_other:()=>{}});if(d.valueType.type==="container"&&d.valueType.container.type==="optional"&&d.valueType.container.optional.type==="container"&&d.valueType.container.optional.container.type==="literal")return d.valueType.container.optional.container.literal._visit({boolean:f=>`${f}`,string:f=>f,_other:()=>{}})},a={};o.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)}),i.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)}),n.headers.forEach(d=>{let f=s(d);f!=null&&(a[cr(d.name)]=f)});let c=r.response?.body!=null?r.response.body.value:void 0,l=r.response?.statusCode??n.response?.statusCode??200,u=n.response?.statusCode??200,p=l>=400?iXh({irEndpoint:n,ir:o,statusCode:l}):l===u?n.responseHeaders:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let f={...r.request?.headers??{}};for(let[m,g]of Object.entries(a))(f[m]===null||f[m]===void 0)&&(f[m]=g);return f})(),requestBody:r.request?.requestBody,requestBodyV3:n.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:d=>{if(r.request==null)return;let f={};if(oi(r.request.requestBody)){let m=r.request.requestBody;for(let g of d.properties)g._visit({file:A=>{let b=m[cr(A.key)];if(A.type==="file")f[cr(A.key)]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(A.type==="fileArray"){let I=(Array.isArray(b)?b:[b]).filter(C=>typeof C=="string");f[cr(A.key)]={type:"filenames",value:I}}},bodyProperty:A=>{if(A.style==="exploded"){let b=m[cr(A.name)];f[cr(A.name)]={type:"exploded",value:Array.isArray(b)?b:[b]}}else f[cr(A.name)]={type:"json",value:m[cr(A.name)]}},_other:SU})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:l,responseBody:c??void 0,responseBodyV3:c!=null?r.response?.body?._visit({json:d=>({type:"json",value:d}),stream:d=>Array.isArray(d)&&d.length>0&&d.every(sXh)?{type:"sse",value:d}:{type:"stream",value:d},error:()=>{},_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+r.response?.body?.type,code:T.Code.InternalError})}}):void 0,responseHeaders:ahs(p),codeSamples:r.codeSamples?.map(d=>({name:d.name,description:d.docs??void 0,install:void 0,language:d.language,code:d.code})).filter(gs)}}function sXh(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function ihs({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(c=>{let l;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?l=c.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(l=c.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})),l!=null)return{name:c.name,value:{jsonExample:l,shape:$t.ExampleTypeReferenceShape.primitive($t.ExamplePrimitive.string({original:l}))}}}).filter(gs),o=e?.example??t?.example;if(o==null)return;let{codeSamples:s}=e??{codeSamples:[]},a=$t.http.ExampleResponse._visit(o.response,{ok:()=>r.responseHeaders,error:({error:c})=>n.errors[c.errorId]?.headers,_other:()=>r.responseHeaders});return{name:Jke(o.name),description:o.docs,path:o.url,pathParameters:[...o.rootPathParameters,...o.servicePathParameters,...o.endpointPathParameters].reduce((c,l)=>(c[en.PropertyKey(jr(l.name))]=l.value.jsonExample,c),{}),queryParameters:o.queryParameters.reduce((c,l)=>(c[cr(l.name)]=l.value.jsonExample,c),{}),headers:[...i,...o.serviceHeaders,...o.endpointHeaders].reduce((c,l)=>(c[cr(l.name)]=l.value.jsonExample,c),{}),requestBody:o.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>o.request!=null?{type:"json",value:o.request.jsonExample}:void 0,reference:()=>o.request!=null?{type:"json",value:o.request.jsonExample}:void 0,fileUpload:c=>{if(o.request==null)return;let l={};if(oi(o.request.jsonExample)){let u=o.request.jsonExample;for(let p of c.properties)p._visit({file:d=>{let f=u[cr(d.key)];if(d.type==="file")l[cr(d.key)]={type:"filename",value:typeof f=="string"?f:"<file1>"};else if(d.type==="fileArray"){let m=(Array.isArray(f)?f:[f]).filter(g=>typeof g=="string");l[cr(d.key)]={type:"filenames",value:m}}},bodyProperty:d=>{if(d.style==="exploded"){let f=u[cr(d.name)];l[cr(d.name)]={type:"exploded",value:Array.isArray(f)?f:[f]}}else l[cr(d.name)]={type:"json",value:u[cr(d.name)]}},_other:SU})}return{type:"form",value:l}},bytes:()=>{},_other:()=>{}}),responseStatusCode:$t.http.ExampleResponse._visit(o.response,{ok:c=>r.response?.statusCode??c._visit({body:l=>l!=null?200:204,stream:l=>l.length>0?200:204,sse:l=>l.length>0?200:204,_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+c.type,code:T.Code.InternalError})}}),error:({error:c})=>{let l=n.errors[c.errorId];if(l==null)throw new T({message:"Cannot find error "+c.errorId,code:T.Code.ResolutionError});return l.statusCode},_other:()=>{throw new T({message:"Unknown ExampleResponse: "+o.response.type,code:T.Code.InternalError})}}),responseBody:o.response._visit({ok:c=>c._visit({body:l=>l?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:o.response._visit({ok:c=>c._visit({body:l=>l!=null?{type:"json",value:l.jsonExample}:void 0,stream:l=>({type:"stream",value:l.map(u=>u.jsonExample)}),sse:l=>({type:"sse",value:l.map(({event:u,data:p})=>({event:u,data:p.jsonExample}))}),_other:()=>{throw new T({message:"Unknown ExampleResponseBody: "+c.type,code:T.Code.InternalError})}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new T({message:"Unknown ExampleResponse: "+o.response.type,code:T.Code.InternalError})}}),responseHeaders:ahs(a),codeSamples:s?.map(c=>B_._visit(c,{language:l=>({language:l.language,code:l.code,name:Jke(l.name),description:l.docs??void 0,install:l.install}),sdk:l=>({language:l.sdk,code:l.code,name:Jke(l.name),description:l.docs??void 0,install:void 0}),_other:()=>{}})).filter(gs)}}function aXh(e,t){return t!=null?{type:{type:"formData",name:jr(t.name),description:t.docs??void 0,availability:void 0,properties:t.properties.map(r=>r._visit({file:n=>{let i=n._visit({file:o=>({type:"file",key:en.PropertyKey(cr(o.key)),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:en.PropertyKey(cr(o.key)),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(i!=null)return{type:"file",value:i}},bodyProperty:n=>({type:"bodyProperty",key:en.PropertyKey(cr(n.name)),valueType:uf(n.valueType,n.defaultValue),contentType:n.contentType,description:n.docs??void 0,availability:cE(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(gs)},description:t.docs??void 0}:cXh(e)}function cXh(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>en.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:en.PropertyKey(cr(t.name)),valueType:uf(t.valueType),availability:cE(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:uf(e.payloadType)},description:e.docs};default:Ye(e)}}function lXh(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>en.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:en.PropertyKey(cr(t.name)),valueType:uf(t.valueType),availability:cE(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:uf(e.bodyType)};default:Ye(e)}}function PNu(e,t){let r=e.v2Examples?.userSpecifiedExamples,n=e.v2Examples?.autogeneratedExamples,i=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([s,a])=>({name:s,responseBody:{type:"json",value:a},description:void 0}));if(n!=null&&Object.keys(n).length>0)return Object.entries(n).map(([s,a])=>({name:s,responseBody:{type:"json",value:a},description:void 0}));if(i.length>0)return i.map(s=>({name:Jke(s.name),responseBody:{type:"json",value:s.jsonExample},description:s.docs}));let o=uXh(e,t);return o!=null?[o]:[]}function uXh(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,n=t.types[r];if(n==null||n.shape.type!=="object")return;let i={},o=!1;for(let s of n.shape.properties){let a=cr(s.name),c=s.v2Examples;if(c?.userSpecifiedExamples!=null){let l=Object.values(c.userSpecifiedExamples);if(l.length>0){i[a]=l[0],o=!0;continue}}if(c?.autogeneratedExamples!=null){let l=Object.values(c.autogeneratedExamples);if(l.length>0){i[a]=l[0];continue}}}if(o)return{name:void 0,responseBody:{type:"json",value:i},description:void 0}}var nhs=h(()=>{"use strict";mt();sm();zn();sc();Bt();xo();rhs();Pxt()});function kO({ir:e,snippetsConfig:t,playgroundConfig:r,graphqlOperations:n={},graphqlTypes:i={},context:o,apiNameOverride:s,showScopes:a=!1}){let c={types:{},subpackages:{},rootPackage:shs(e.rootPackage,e,n,i,{showScopes:a}),apiName:s??jr(e.apiName),specVersion:e.specVersion,auth:vNu({auth:e.auth,playgroundConfig:r,context:o}),authSchemes:xNu({auth:e.auth,playgroundConfig:r,context:o}),snippetsConfiguration:t,globalHeaders:e.headers.map(l=>({availability:cE(l.availability),description:l.docs??void 0,key:cr(l.name),type:uf(l.valueType,l.defaultValue)})),navigation:void 0};for(let[l,u]of Object.entries(e.types))c.types[en.TypeId(l)]={description:u.docs??void 0,name:jr(u.name.name),shape:wNu(u.shape,u.encoding?.xml),availability:cE(u.availability),displayName:u.name.displayName,examples:pXh(u)};for(let[l,u]of Object.entries(i))c.types[en.TypeId(l)]=u;for(let[l,u]of Object.entries(e.subpackages)){let p=u.service!=null?e.services[u.service]:void 0;c.subpackages[en.SubpackageId(l)]={subpackageId:en.SubpackageId(l),displayName:p?.displayName??u.displayName,name:jr(u.name),description:u.docs??void 0,...shs(u,e,void 0,void 0,{showScopes:a})}}return c}function pXh(e){let r=[e.userProvidedExamples.map(n=>n.jsonExample),Object.values(e.v2Examples?.userSpecifiedExamples??{}),fXh(e),Object.values(e.v2Examples?.autogeneratedExamples??{})].find(n=>n.length>0);return r??void 0}function fXh(e){if(e.shape.type!=="object")return[];let t={};for(let i of e.shape.properties){let[o]=Object.values(i.v2Examples?.userSpecifiedExamples??{});o!==void 0&&(t[cr(i.name)]=o)}if(Object.keys(t).length===0)return[];let[r]=Object.values(e.v2Examples?.autogeneratedExamples??{});return[{...gr(r)?r:{},...t}]}var chs=h(()=>{"use strict";mt();sm();SNu();nhs();rhs();Pxt()});async function lhs({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:o,playgroundConfig:s,graphqlOperations:a={},graphqlTypes:c={}}){let l=Yg({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Qh(r,t)}),u=MF({token:n.value}),p=kO({ir:l,snippetsConfig:o,playgroundConfig:s,graphqlOperations:a,graphqlTypes:c,context:r});try{let d=await u.api.register.registerApiDefinition({orgId:en.OrgId(e),apiId:en.ApiId(jr(l.apiName)),definition:p});return r.logger.debug(`Registered API Definition ${d.apiDefinitionId}`),{id:d.apiDefinitionId,ir:l}}catch(d){return r.failAndThrow("Failed to register API",d,{code:T.Code.NetworkError})}}var BNu=h(()=>{"use strict";tN();sf();sm();lp();Bt();chs();Pxt()});var Qge=h(()=>{"use strict";chs();BNu()});function UJt({ir:e,apiDefinitionId:t,playgroundConfig:r,context:n,graphqlOperations:i={},graphqlTypes:o={}}){return aH(oH(kO({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,graphqlOperations:i,graphqlTypes:o,context:n}),Chr.ApiDefinitionId(t),dXh))}var dXh,uhs=h(()=>{"use strict";sm();Qge();dXh=new sH({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}})});async function hS({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&DNu.default.isAbsolute(e)&&t.add(e)}async function RNu({parsedDocsConfig:e}){let t=new Set;if(e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.metadata?.["og:dynamic:background-image"]!=null&&e.metadata["og:dynamic:background-image"].type==="filepath"&&t.add(e.metadata["og:dynamic:background-image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{t.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&t.add(n.image)}),(await phs({navigation:e.navigation})).forEach(n=>{t.add(n)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async n=>{n.type==="dropdown"&&n.links.map(async i=>{i.icon&&await hS({iconPath:i.icon,filepaths:t}),i.rightIcon&&await hS({iconPath:i.rightIcon,filepaths:t})}),n.type!=="github"&&(n.icon&&await hS({iconPath:n.icon,filepaths:t}),n.rightIcon&&await hS({iconPath:n.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(n=>{t.add(n.absolutePath)}),e.context7File!=null&&t.add(e.context7File),e.llmsTxtFile!=null&&t.add(e.llmsTxtFile),e.llmsFullTxtFile!=null&&t.add(e.llmsFullTxtFile),e.robotsTxtFile!=null&&t.add(e.robotsTxtFile),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async n=>{n.icon!=null&&await hS({iconPath:n.icon,filepaths:t})})),e.translationNavigationOverlays!=null)for(let n of Object.values(e.translationNavigationOverlays))await mXh({navbarLinks:n.navbarLinks,filepaths:t});return t}async function mXh({navbarLinks:e,filepaths:t}){e!=null&&await Promise.all(e.map(async r=>{if(r.type!=="github"){if(r.type==="dropdown"){await Promise.all(r.links.map(async n=>{n.icon!=null&&await hS({iconPath:n.icon,filepaths:t}),n.rightIcon!=null&&await hS({iconPath:n.rightIcon,filepaths:t})})),r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.rightIcon!=null&&await hS({iconPath:r.rightIcon,filepaths:t});return}r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.rightIcon!=null&&await hS({iconPath:r.rightIcon,filepaths:t})}}))}async function phs({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>S8e({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(n=>S8e({item:n,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&(await Promise.all([...r.child.menu??[],...si.flattenNestedTabVariants(r.child.variants).flatMap(n=>n.nestedVariants?.menu??[])].flatMap(n=>n.type==="group"?n.children:[n]).flatMap(n=>n.type==="link"&&n.icon!=null?[hS({iconPath:n.icon,filepaths:t})]:[])),await Promise.all(si.flattenNestedTabVariants(r.child.variants).flatMap(n=>{let i=[];return n.icon!=null&&i.push(hS({iconPath:n.icon,filepaths:t})),i.push(...n.layout.map(o=>S8e({item:o,filepaths:t}))),i})))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await S8e({item:r.landingPage,filepaths:t}),(await phs({navigation:r.navigation})).forEach(i=>t.add(i))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await hS({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await S8e({item:r.landingPage,filepaths:t}),(await phs({navigation:r.navigation})).forEach(i=>t.add(i)))})),e.changelog!=null&&await S8e({item:e.changelog,filepaths:t});break}return t}async function S8e({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>S8e({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await hS({iconPath:e.icon,filepaths:t});break}}var DNu,kNu=h(()=>{"use strict";qn();DNu=Ae(require("path"),1)});async function FNu(e,t,r){let n=new Array(e.length),i=0,o=!1,s,a=async()=>{for(;i<e.length&&!o;){let l=i++;try{n[l]=await r(e[l],l)}catch(u){o||(o=!0,s=u)}}},c=Math.min(Math.max(1,Math.floor(t)),e.length);if(await Promise.all(Array.from({length:c},a)),o)throw s;return n}var NNu=h(()=>{"use strict"});function hXh(e,t,r){return e.replace(/\[([^\]]*)\]\(([^)]+\.mdx?(?:#[^)]*)?)\)/g,(n,i,o)=>{let s=o.indexOf("#"),a=s>=0?o.substring(0,s):o,c=s>=0?o.substring(s):"",l=K5e({href:a,metadata:r,markdownFilesToPathName:t});return l!=null&&l.type==="replace"?`[${i}](${l.slug}${c})`:n})}function afi(e,t,r){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)afi(i,t,r);return}let n=e;for(let[i,o]of Object.entries(n))typeof o=="string"&&o.includes(".md")?n[i]=hXh(o,t,r):typeof o=="object"&&afi(o,t,r)}function w8e(e,t,r){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)w8e(i,t,r);return}let n=e;n.apiDefinitionId===t&&(n.apiDefinitionId=r);for(let i of Object.values(n))typeof i=="object"&&w8e(i,t,r)}var fhs=h(()=>{"use strict";W3()});async function jNu({navigation:e,apiWorkspaces:t,visitor:r,context:n}){AXh(e)?await Promise.all(e.map(async i=>{jK(i)?await Promise.all(i.layout.map(async o=>{await cfi({navigationItem:o,visitor:r,apiWorkspaces:t,context:n})})):si.isRawTabWithVariantLayouts(i)&&await Promise.all(si.flattenRawTabLayouts(i).flatMap(({layout:o})=>o.map(async s=>{await cfi({navigationItem:s,visitor:r,apiWorkspaces:t,context:n})})))})):await Promise.all(e.map(async i=>{await cfi({navigationItem:i,visitor:r,apiWorkspaces:t,context:n})}))}async function cfi({navigationItem:e,visitor:t,apiWorkspaces:r,context:n}){if(await DU(e,{alphabetized:xt,sortByAvailability:xt,showScopes:xt,api:xt,apiName:xt,specs:xt,audiences:xt,displayErrors:xt,tagDescriptionPages:xt,snippets:xt,summary:xt,title:xt,layout:xt,collapsed:xt,icon:xt,slug:xt,hidden:xt,skipSlug:xt,paginated:xt,types:xt,playground:xt,flattened:xt,path:xt,page:xt,featureFlag:xt,openrpc:xt,postman:xt,contents:async i=>{i!=null&&await Promise.all(i.map(async o=>{await cfi({navigationItem:o,visitor:t,apiWorkspaces:r,context:n})}))},viewers:xt,orphaned:xt,availability:xt}),gXh(e)){let i=r.find(o=>o.workspaceName===e.apiName);i!=null&&await t.apiSection?.({config:e,workspace:i,context:n})}}function gXh(e){return e.api!=null}function AXh(e){return e[0]?.tab!=null}var zNu=h(()=>{"use strict";qn();mt()});function YN(e){return Yh(e)?e:`https://${e}`}var dhs=h(()=>{"use strict";mt()});function lfi(){let e=process.env.FERN_DOCS_API_REGISTRATION_CONCURRENCY?.trim();return e!=null&&/^[1-9]\d*$/.test(e)?Number(e):yXh}function vXh(e,t){let r=new WeakMap,n=(i,o)=>{if(Array.isArray(i)){for(let a of i)n(a,o);return}if(i==null||typeof i!="object"||r.has(i))return;let s="profile"in i&&typeof i.profile=="string"?i.profile:o;r.set(i,s);for(let a of Object.values(i))n(a,s)};for(let i of e)n(i,t);return r}function mhs(e){return typeof e=="string"?[e]:Array.isArray(e)?e.flatMap(mhs):e!=null&&typeof e=="object"?Object.values(e).flatMap(mhs):[]}function CXh(e){return new Set(e.filter(gs).flatMap(t=>Array.from(t.matchAll(IXh),r=>r[1])).filter(gs))}function xXh(e){if(e!=null)return{schema:e.schema,...e.name==null?{}:{name:e.name},...e.applyTo==null?{}:{"apply-to":e.applyTo},...e.ensure==null?{}:{ensure:e.ensure.map(t=>({"status-code":t.statusCode,...t.methods==null?{}:{methods:t.methods}}))}}}function SXh(e,t){let r=e?.launch;if(e?.github==null)return{url:void 0,launch:r};let{owner:n,repo:i,branch:o="main",host:s="https://github.com"}=e.github;return{url:`${YN(s)}/${n}/${i}/blob/${o}/fern/${t}?plain=1`,launch:r}}function wXh(e){return e==null||typeof e=="string"?e:{style:e.style,alignment:e.alignment?.toUpperCase(),placement:e.placement?.toUpperCase()}}function TXh(e){if(e!=null)return{enabled:e.enabled,order:e.order,hide:e.hide,labels:e.labels,"show-products":e.showProducts}}function OXh(e){return e==null||e.light==null&&e.dark==null?{}:{"code-blocks":{light:e.light,dark:e.dark}}}function PXh(e){let t=e.findIndex(n=>n.default===!0);if(t!==-1)return t;let r=e.findIndex(n=>n.hidden!==!0);return r===-1?0:r}function BXh(e){switch(e){case"beta":return Vt.V1.NavigationV1Availability.Beta;case"deprecated":return Vt.V1.NavigationV1Availability.Deprecated;case"ga":return Vt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Vt.V1.NavigationV1Availability.Stable;case"alpha":return Vt.V1.NavigationV1Availability.Alpha;case"preview":return Vt.V1.NavigationV1Availability.Preview;case"legacy":return Vt.V1.NavigationV1Availability.Legacy;default:Ye(e)}}function VNu(e){return e.flatMap(t=>{switch(t.type){case"page":case"link":return[t];case"section":case"package":{let r=VNu(t.contents);return r.length===0&&t.overviewAbsolutePath==null?[]:[{type:"section",title:t.title??(t.type==="package"?t.package:""),referencedSubpackages:[],overviewAbsolutePath:t.overviewAbsolutePath,contents:r,slug:t.slug??(t.type==="package"?Tu(t.package):void 0),hidden:t.hidden,icon:t.icon,skipUrlSlug:t.skipUrlSlug,collapsed:t.type==="section"?t.collapsed:void 0,collapsible:t.type==="section"?t.collapsible:void 0,collapsedByDefault:t.type==="section"?t.collapsedByDefault:void 0,availability:t.availability,playground:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}]}case"item":case"endpoint":case"operation":return[];default:Ye(t)}})}var MNu,LNu,_Nu,Dxt,Mge,UNu,yXh,bXh,QNu,EXh,IXh,XN,GNu=h(()=>{"use strict";vc();tN();qn();mt();W3();sm();tr();PWo();lp();sc();Id();qms();Bt();MNu=require("crypto"),LNu=Ae(sNt(),1),_Nu=Ae(aNt(),1),Dxt=require("fs"),Mge=require("fs/promises"),UNu=Ae(kQ(),1);Ko();xo();dNu();Yms();hNu();Qms();ANu();Mms();bNu();tfi();INu();uhs();kNu();NNu();fhs();zNu();dhs();LNu.default.extend(_Nu.default);yXh=4;bXh=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),QNu=0,EXh=async({ir:e})=>(QNu++,`${r4o(e.apiName)}-${QNu}`),IXh=/\$\\?\{(\w+)\\?\}/g;XN=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;onApiRegistrationQueued;onNavigationTreeBuilt;targetAudiences;docsVisibility;buildTranslatedApiDefinitions;buildRefVersions;skipApiReferences;cliVersion;cliName;refWorkspacesByFernFolder=new Map;markdownFilesToPathName={};constructor({domain:t,docsWorkspace:r,ossWorkspaces:n,apiWorkspaces:i,taskContext:o,editThisPage:s,uploadFiles:a=bXh,registerApi:c=EXh,onApiRegistrationQueued:l,onNavigationTreeBuilt:u,targetAudiences:p,docsVisibility:d="public",buildTranslatedApiDefinitions:f=!1,buildRefVersions:m=!0,skipApiReferences:g=!1,cliVersion:A,cliName:b="fern"}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=n,this.apiWorkspaces=i,this.taskContext=o,this.editThisPage=s,this.uploadFiles=a,this.registerApi=c,this.onApiRegistrationQueued=l,this.onNavigationTreeBuilt=u,this.targetAudiences=p,this.docsVisibility=d,this.buildTranslatedApiDefinitions=f,this.buildRefVersions=m,this.skipApiReferences=g,this.cliVersion=A,this.cliName=b}#e=ofi.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let n=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(n)})}:t}getRawProductAudiences(t){let n=this.docsWorkspace.config.products?.find(i=>i.displayName===t);return Q5t(n?.audiences)}getRawVersionAudiences(t){let n=this.docsWorkspace.config.versions?.find(i=>i.displayName===t);return Q5t(n?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new T({message:"parsedDocsConfig is not set",code:T.Code.InternalError});return this._parsedDocsConfig}getTranslationPages(){return this._parsedDocsConfig?.translationPages}getTranslationNavigationOverlays(){return this._parsedDocsConfig?.translationNavigationOverlays}getCollectedFileIds(){return this.collectedFileIds}getDocsWorkspacePath(){return this.docsWorkspace.absoluteFilePath}getSkippedApiDefinitions(){return this.skippedApiDefinitions}getTranslatedApiSpecs(){return this.translatedApiSpecs}getMarkdownFilesToPathName(){return this.markdownFilesToPathName}getDocsTranslationsConfig(){let t=this.parsedDocsConfig.translations;if(t==null||t.length===0)return;let r=t.map(i=>si.DocsYmlSchemas.normalizeTranslationConfig(i)),n=r.find(i=>i.default===!0)??r[0];if(n!=null)return{defaultLocale:n.lang,translations:r.map(i=>i.lang)}}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;markdownFilesToAvailability=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];pendingApiRegistrations=[];pendingApiCounter=0;skippedApiCounter=0;skippedApiDefinitions={};translatedApiSpecs=new Map;async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let n=performance.now();this._parsedDocsConfig=await k4e({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig,buildRefVersions:this.buildRefVersions});let i=performance.now()-n,o=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${i.toFixed(0)}ms: ${o} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[be.of(Nt)]=RO(rr);let s=this.parsedDocsConfig.experimental?.openapiParserV3,a=s!=null&&!s;if(this.docsWorkspace.config.navigation!=null&&a&&!this.skipApiReferences){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let Nt=performance.now();await jNu({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:ye})=>{(await ye.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0,docsVisibility:this.docsVisibility})).changelog?.files.forEach(Xe=>{let dt=go(this.docsWorkspace.absoluteFilePath,Xe.absoluteFilepath);this.parsedDocsConfig.pages[dt]=Xe.contents,this.rawMarkdownFiles[be.of(dt)]=RO(Xe.contents)})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let rr=performance.now()-Nt;this.taskContext.logger.debug(`Visited navigation AST in ${rr.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let c=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let l=performance.now()-c;this.taskContext.logger.debug(`Built markdown file maps in ${l.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),p=new Set,d=Object.entries(this.parsedDocsConfig.pages),f=[];for(let[,Nt]of d)f.push(...Upi(Nt));let m=Date.now(),g=await Vpi(f,this.taskContext);if(g.size>0){let Nt=new Set(f).size;this.taskContext.logger.info(`Prefetched ${Nt} external code URLs in ${Date.now()-m}ms`)}for(let[Nt,rr]of d){let ye=await qk({markdown:rr,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext});for(let dt of ye.referencedFiles)p.has(dt.absoluteFilePath)||(p.add(dt.absoluteFilePath),this.referencedMarkdownFiles.push(dt));let ge=await G3({markdown:ye.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext,urlCache:g}),Xe=q3({markdown:ge,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(Nt),context:this.taskContext});this.parsedDocsConfig.pages[be.of(Nt)]=Xe}let A=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${A.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let b=performance.now(),I=await RNu({parsedDocsConfig:this.parsedDocsConfig}),C=performance.now()-b;this.taskContext.logger.debug(`Collected ${I.size} files in ${C.toFixed(0)}ms`);let x=await yNu({absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});x.length>0&&(this.taskContext.logger.debug(`Collected ${x.length} well-known agent skills files`),x.forEach(Nt=>I.add(Nt))),this.taskContext.logger.debug("Parsing image paths from markdown files...");let S=performance.now();for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:ye,markdown:ge}=tY(rr,{absolutePathToMarkdownFile:this.resolveFilepath(Nt),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[be.of(Nt)]=ge;for(let Xe of ye)I.add(Xe)}catch(ye){throw this.taskContext.logger.error(`Failed to parse ${Nt}: ${rn(ye)}`),new T({message:`Failed to parse markdown file ${Nt}: ${rn(ye)}`,code:T.Code.ParseError})}let P=performance.now()-S;this.taskContext.logger.debug(`Parsed image paths in ${P.toFixed(0)}ms`);let D=Array.from(I).map(Nt=>({absoluteFilePath:Nt,relativeFilePath:this.toRelativeFilepath(Nt)}));this.taskContext.logger.info(`Uploading ${D.length} files...`);let R=performance.now(),O=await this.uploadFiles(D),j=performance.now()-R;this.taskContext.logger.info(`Uploaded ${O.length} files in ${j.toFixed(0)}ms`),O.forEach(Nt=>{this.collectedFileIds.set(Nt.absoluteFilePath,Nt.fileId)}),this.resolveTranslationOverlayNavbarLinkIcons(),this.taskContext.logger.debug("Building navigation tree...");let Y=performance.now(),ee=await this.toRootNode(),te=performance.now()-Y;this.taskContext.logger.debug(`Built navigation tree in ${te.toFixed(0)}ms`),this.onNavigationTreeBuilt?.(),this.taskContext.logger.debug("Getting fully qualified path names...");let ce=performance.now(),le=await this.getMarkdownFilesToFullyQualifiedPathNames(ee);this.markdownFilesToPathName=le;let ae=performance.now()-ce;if(this.taskContext.logger.debug(`Got path names in ${ae.toFixed(0)}ms`),this.pendingApiRegistrations.length>0){this.taskContext.logger.debug(`Processing ${this.pendingApiRegistrations.length} deferred API registrations...`);let Nt=performance.now(),rr=this.pendingApiRegistrations,ye=[],ge=new Map;for(let ut of rr){this.resolveLinksInIrDocs(ut.ir,le);let Ue=ut.workspace?.getSources().map(ot=>[ot.absoluteFilePath,ot.absoluteFilePathToOverrides]),ze=(0,MNu.createHash)("sha256").update(JSON.stringify({ir:ut.ir,snippetsConfig:ut.snippetsConfig,playgroundConfig:ut.playgroundConfig,apiName:ut.apiName,workspace:Ue,graphqlOperations:ut.graphqlOperations,graphqlTypes:ut.graphqlTypes,showScopes:ut.showScopes})).digest("hex");ye.push(ze),ge.has(ze)||ge.set(ze,ut)}let Xe=[...ge.entries()],dt=await FNu(Xe,lfi(),async([,ut])=>await this.registerApi({ir:ut.ir,snippetsConfig:ut.snippetsConfig,playgroundConfig:ut.playgroundConfig,apiName:ut.apiName,workspace:ut.workspace,graphqlOperations:ut.graphqlOperations,graphqlTypes:ut.graphqlTypes,showScopes:ut.showScopes})),Ce=new Map(Xe.map(([ut],Ue)=>[ut,dt[Ue]]));for(let[ut,Ue]of rr.entries()){let ze=ye[ut],ot=ze!=null?Ce.get(ze):void 0;if(ot==null)throw new Error(`Registering API ${Ue.apiName??Ue.tempApiDefinitionId} returned no definition id`);if(w8e(Ue.apiReferenceNode,Ue.tempApiDefinitionId,ot),Ue.translatedIrsByLocale!=null)for(let[bt,ir]of Ue.translatedIrsByLocale){this.resolveLinksInIrDocs(ir,le);let Tn=this.translatedApiSpecs.get(bt);Tn==null&&(Tn=new Map,this.translatedApiSpecs.set(bt,Tn)),Tn.set(ot,{ir,snippetsConfig:Ue.snippetsConfig,playgroundConfig:Ue.playgroundConfig,apiName:Ue.apiName,graphqlOperations:Ue.graphqlOperations,graphqlTypes:Ue.graphqlTypes,showScopes:Ue.showScopes,workspace:Ue.workspace})}}let we=performance.now()-Nt;this.taskContext.logger.debug(`Processed deferred API registrations in ${we.toFixed(0)}ms`),this.pendingApiRegistrations=[]}this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let he=performance.now();for(let[Nt,rr]of Object.entries(this.parsedDocsConfig.pages))try{this.parsedDocsConfig.pages[be.of(Nt)]=M3(rr,this.collectedFileIds,le,{absolutePathToMarkdownFile:this.resolveFilepath(Nt),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext)}catch(ye){throw new T({message:`Failed to replace image paths in markdown file ${Nt}: ${rn(ye)}`,code:T.Code.ParseError})}let xe=performance.now()-he;this.taskContext.logger.debug(`Replaced image paths in ${xe.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let Te={};Object.entries(this.parsedDocsConfig.pages).forEach(([Nt,rr])=>{let{url:ye,launch:ge}=SXh(this.editThisPage,Nt),Xe=this.rawMarkdownFiles[be.of(Nt)];Te[JS.PageId(Nt)]={markdown:RO(rr),editThisPageUrl:ye?JS.Url(ye):void 0,editThisPageLaunch:ge,rawMarkdown:Xe}}),this.taskContext.logger.debug("Converting docs configuration...");let pe=performance.now(),{root:ue,...Pe}=await this.convertDocsConfiguration(ee),Ie=this.profileScope(this.parsedDocsConfig.profile).forNode({texts:[...mhs(Pe),ue?.title]}),je={...Pe,root:ue!=null?{...ue,...Ie}:ue},_e=performance.now()-pe;this.taskContext.logger.debug(`Converted docs configuration in ${_e.toFixed(0)}ms`);let at={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let Nt=performance.now(),rr=await Ypi({absolutePathToDocsWorkspace:this.docsWorkspace.absoluteFilePath,mdxComponents:this._parsedDocsConfig.experimental.mdxComponents});at=Object.fromEntries(await Promise.all(rr.map(async ge=>{let Xe=this.toRelativeFilepath(ge),dt=(await(0,Mge.readFile)(ge)).toString();return[Xe,await this.bundleJsFileContents(ge,dt)]})));let ye=performance.now()-Nt;this.taskContext.logger.debug(`Processed ${rr.length} MDX component files in ${ye.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let Nt of this.referencedMarkdownFiles)at[Nt.relativeFilePath]=Nt.content}if(this._parsedDocsConfig.header!=null){let Nt=this.toRelativeFilepath(this._parsedDocsConfig.header),rr=(await(0,Mge.readFile)(this._parsedDocsConfig.header)).toString();at[Nt]=await this.bundleJsFileContents(this._parsedDocsConfig.header,rr),this.taskContext.logger.debug(`Added custom header component: ${Nt}`)}if(this._parsedDocsConfig.footer!=null){let Nt=this.toRelativeFilepath(this._parsedDocsConfig.footer),rr=(await(0,Mge.readFile)(this._parsedDocsConfig.footer)).toString();at[Nt]=await this.bundleJsFileContents(this._parsedDocsConfig.footer,rr),this.taskContext.logger.debug(`Added custom footer component: ${Nt}`)}let Ct=performance.now()-t,Et=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${Ct.toFixed(0)}ms, Memory delta: RSS=${((Et.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:je,pages:Te,jsFiles:at}}resolveFilepath(t){if(t!=null)return Rn(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return go(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,n]of Object.entries(t)){let i=(0,UNu.default)(n),o=this.resolveFilepath(r),s=i.data.slug;if(typeof s=="string"&&s.trim().length>0){let p=s.trim();nxt(p)?this.markdownFilesToFullSlugs.set(o,p):this.taskContext.logger.warn(`Ignoring absolute URL slug "${p}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let a=i.data["sidebar-title"];typeof a=="string"&&a.trim().length>0&&this.markdownFilesToSidebarTitle.set(o,a.trim());let c=i.data.noindex;typeof c=="boolean"&&this.markdownFilesToNoIndex.set(o,c);let l=i.data.tags;typeof l=="string"?this.markdownFilesToTags.set(o,l.split(",").map(p=>p.trim()).filter(p=>p.length>0)):Array.isArray(l)&&this.markdownFilesToTags.set(o,l);let u=i.data.availability;if(typeof u=="string"){let p=this.parseAvailabilityFromFrontmatter(u);p!=null&&this.markdownFilesToAvailability.set(o,p)}}}parseAvailabilityFromFrontmatter(t){switch(t.toLowerCase().trim()){case"stable":return"stable";case"generally-available":return"generally-available";case"in-development":return"in-development";case"pre-release":return"pre-release";case"deprecated":return"deprecated";case"beta":return"beta";default:this.taskContext.logger.warn(`Invalid availability value "${t}" in frontmatter. Valid values are: stable, generally-available, in-development, pre-release, deprecated, beta`);return}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},n=Vt.migrate.FernNavigationV1ToLatest.create().root(t),i=new Set;Vt.traverseDF(n,a=>{a.type==="version"&&!a.default&&i.add(a.slug)});let o=a=>{let c=a.split("/");return c.some((l,u)=>i.has(c.slice(0,u+1).join("/")))};return Vt.NodeCollector.collect(n).slugMap.forEach((a,c)=>{if(a==null||!Vt.isPage(a))return;let l=Vt.getPageId(a);if(l==null)return;let u=Re(this.docsWorkspace.absoluteFilePath,be.of(l)),p=r[u];(p==null||o(p)&&!o(c))&&(r[u]=c)}),r}getDocsBasePath(){return new URL(YN(this.domain)).pathname}async convertDocsConfiguration(t){let r=this.parsedDocsConfig.integrations!=null||this.parsedDocsConfig.context7File!=null?{...this.parsedDocsConfig.integrations,context7:this.getFileId(this.parsedDocsConfig.context7File)}:void 0;return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location?.filter(i=>i==="slack"||i==="docs"),datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title})),maskPii:this.parsedDocsConfig.aiChatConfig.maskPii,disclaimer:this.parsedDocsConfig.aiChatConfig.disclaimer,buttonText:this.parsedDocsConfig.aiChatConfig.buttonText}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?JS.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(o=>({...o,url:JS.Url(o.url),icon:this.resolveIconFileId(o.icon),rightIcon:this.resolveIconFileId(o.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:JS.Url(i.url)}:{...i,url:JS.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.convertDocsSettings(),css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),agents:this.parsedDocsConfig.agents!=null||this.parsedDocsConfig.llmsTxtFile!=null||this.parsedDocsConfig.llmsFullTxtFile!=null||this.parsedDocsConfig.robotsTxtFile!=null||this.parsedDocsConfig.experimental?.robotsTxtOnInstanceUrl===!0?{...this.parsedDocsConfig.agents,llmsTxt:this.getFileId(this.parsedDocsConfig.llmsTxtFile),llmsFullTxt:this.getFileId(this.parsedDocsConfig.llmsFullTxtFile),robotsTxt:this.getFileId(this.parsedDocsConfig.robotsTxtFile),robotsTxtOnInstanceUrl:this.parsedDocsConfig.experimental?.robotsTxtOnInstanceUrl}:void 0,metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,remotePaths:this.parsedDocsConfig.remotePaths,integrations:r,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:JS.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,translations:this.getDocsTranslationsConfig(),analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch,embedding:this.parsedDocsConfig.settings?.embedding!=null?{allowedOrigins:this.parsedDocsConfig.settings.embedding.allowedOrigins}:void 0,pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:wXh(this.parsedDocsConfig.theme.tabs),"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher,"site-switcher":TXh(this.parsedDocsConfig.theme.siteSwitcher),...OXh(this.parsedDocsConfig.theme.codeBlocks)}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:this.parsedDocsConfig.header?this.toRelativeFilepath(this.parsedDocsConfig.header):void 0,footer:this.parsedDocsConfig.footer?this.toRelativeFilepath(this.parsedDocsConfig.footer):void 0}}async bundleJsFileContents(t,r){try{return await Jpi({absoluteFilePath:t,contents:r,context:this.taskContext})??r}catch(n){throw new T({message:`Failed to bundle third-party imports in ${t}: ${rn(n)}`,code:T.Code.ParseError})}}async resolveApiWorkspaces(t){if(t==null)return{apiWorkspaces:this.apiWorkspaces,ossWorkspaces:this.ossWorkspaces};let r=t.absolutePathToFernFolder,n=this.refWorkspacesByFernFolder.get(r);if(n!=null)return n;if(this.cliVersion==null)throw new T({message:`Cannot load API definitions for version '${t.displayVersion}' (ref '${t.ref}'): the CLI version is unavailable in this context.`,code:T.Code.InternalError});let i=this.cliVersion,o=(async()=>{let s=await $pi({cliName:this.cliName,fernDirectory:r,context:this.taskContext,cliVersion:i,commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),a=s.filter(c=>c instanceof Il);return{apiWorkspaces:s,ossWorkspaces:a}})();return this.refWorkspacesByFernFolder.set(r,o),o}getFernWorkspaceForApiSection(t,r){if(t.apiName!=null){let i=r.find(o=>o.workspaceName===t.apiName);if(i!=null)return i}else if(r.length===1&&r[0]!=null)return r[0];let n=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
1864
1864
|
A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
1865
1865
|
Learn more about project structure:
|
|
1866
1866
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
@@ -3495,7 +3495,7 @@ ${tsu.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&YHo(th
|
|
|
3495
3495
|
`).length),this}updateBottomBar(t){return Lqt(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+`
|
|
3496
3496
|
`}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&&Wen(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var qd=Ae(v3(),1),Eau=Ae(Aqt(),1);var Stn=Ae(v3(),1),yau=Ae(Aqt(),1),wtn=function(e,t,r){return typeof e[t]!="function"?(0,Stn.of)(e):(0,Stn.from)((0,yau.default)(e[t])(r).then(n=>(e[t]=n,e)))};var bau={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}},Qut=class extends vVe{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,qd.from)(t):(0,qd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,qd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,qd.from)([t]),this.process=n.pipe((0,qd.concatMap)(this.processQuestion.bind(this)),(0,qd.publish)()),this.process.connect(),this.process.pipe((0,qd.reduce)((i,o)=>(bau.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,qd.defer)(()=>(0,qd.of)(t).pipe((0,qd.concatMap)(this.setDefaultType.bind(this)),(0,qd.concatMap)(this.filterIfRunnable.bind(this)),(0,qd.concatMap)(()=>wtn(t,"message",this.answers)),(0,qd.concatMap)(()=>wtn(t,"default",this.answers)),(0,qd.concatMap)(()=>wtn(t,"choices",this.answers)),(0,qd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,qd.defer)(()=>(0,qd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,qd.defer)(()=>(0,qd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&bau.get(this.answers,t.name)!==void 0)return qd.EMPTY;if(t.when===!1)return qd.EMPTY;if(typeof t.when!="function")return(0,qd.of)(t);let{answers:r}=this;return(0,qd.defer)(()=>(0,qd.from)((0,Eau.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,qd.filter)(n=>n!=null)))}};function Iau(e){let t=function(r,n){let i;try{i=new Qut(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",Uqt),this.registerPrompt("input",AVe),this.registerPrompt("number",Vqt),this.registerPrompt("confirm",Gqt),this.registerPrompt("rawlist",qqt),this.registerPrompt("expand",Wqt),this.registerPrompt("checkbox",Hqt),this.registerPrompt("password",Kqt),this.registerPrompt("editor",rWt)},t.restoreDefaultPrompts(),t}var yJo=Iau();function _gh(e,t){yJo.registerPrompt(e,t)}function Ugh(){yJo.restoreDefaultPrompts()}var Vgh={prompt:yJo,ui:{BottomBar:nWt,Prompt:Qut},createPromptModule:Iau,registerPrompt:_gh,restoreDefaultPrompts:Ugh,Separator:$Q},bo=Vgh;var Ggh=["prod","pre-prod","beta","dev","local"];function qgh(e){return Ggh.some(t=>t===e)}function gJ(e="prod"){let t=e?.trim();return t!=null&&qgh(t)?t:"local"}function Ttn(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var Mut=require("path");function Cau(){let e=Wgh();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Wgh(e=process.argv[1]?(0,Mut.dirname)(process.argv[1]):process.cwd(),t=Mut.sep==="\\"){let r=t?vau(e):e;return n=>{if(!n)return;let i=t?vau(n):n,{dir:o,base:s,ext:a}=Mut.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let u=o.slice(r.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function vau(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var LT={};ne(LT,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>qtn,DOMExceptionCoercer:()=>NJo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>dWt,ErrorCoercer:()=>lWt,ErrorEventCoercer:()=>jJo,ErrorPropertiesBuilder:()=>cWt,EventCoercer:()=>zJo,ExceptionStepsBuffer:()=>_Jo,ObjectCoercer:()=>pWt,PrimitiveCoercer:()=>fWt,PromiseRejectionEventCoercer:()=>QJo,ReduceableCache:()=>MJo,StringCoercer:()=>uWt,chromeStackLineParser:()=>DJo,createDefaultStackParser:()=>FJo,createStackParser:()=>pcu,geckoStackLineParser:()=>RJo,getInjectedReleaseId:()=>syh,getUtf8ByteLength:()=>dcu,nodeStackLineParser:()=>ocu,opera10StackLineParser:()=>rcu,opera11StackLineParser:()=>ncu,resolveExceptionStepsConfig:()=>LJo,reverseAndStripFrames:()=>ucu,stripReservedExceptionStepFields:()=>nyh,winjsStackLineParser:()=>tcu});var tM=(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.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_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.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function kwe(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n}})??"null"}var Hgh=Array.isArray,Sau=Object.prototype,guC=Sau.hasOwnProperty,Otn=Sau.toString,x3=Hgh||function(e){return Otn.call(e)==="[object Array]"};var iWt=e=>e===Object(e)&&!x3(e);var mhe=e=>e===void 0,wR=e=>Otn.call(e)=="[object String]",bJo=e=>wR(e)&&e.trim().length===0,EJo=e=>e===null,AJ=e=>mhe(e)||EJo(e),Lut=e=>Otn.call(e)=="[object Number]"&&e===e;var wau=e=>Otn.call(e)==="[object Boolean]";function Ptn(e){return e===null||typeof e!="object"}function CVe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Fwe(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Pau(e,Error)}}function Tau(e){return CVe(e,"ErrorEvent")}function _ut(e){return"u">typeof Event&&Pau(e,Event)}function Oau(e){return CVe(e,"Object")}function Pau(e,t){try{return e instanceof t}catch{return!1}}var Kgh=["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","pinterestbot","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"],Btn=new Map,Jgh=256;function Ygh(e,t){let r="";for(let n=0;n<t.length;n++){let i=t[n];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var Bau=function(e,t=[]){if(!e)return!1;let r=Ygh(e,t),n=Btn.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=Kgh.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return Btn.size>=Jgh&&Btn.clear(),Btn.set(r,o),o};function oWt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Lut(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),oWt(i??r,t,r,n))}var Xgh=864e5,Zgh=1,$gh=10;function Dau(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??Zgh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??$gh}}var Dtn=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=oWt(t.bucketSize,0,100,t._logger),this._refillRate=oWt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=oWt(t.refillInterval,0,Xgh,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 Rtn="0123456789abcdef",ktn=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+=Rtn.charAt(this.bytes[r]>>>4),t+=Rtn.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+=Rtn.charAt(this.bytes[r]>>>4),t+=Rtn.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}},IJo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??eAh()}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 ktn.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,ktn.ofInner(t)}},eAh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Rau,Z2=()=>tAh().toString(),tAh=()=>(Rau||(Rau=new IJo)).generate();var Ftn=class{add(t){let r=Z2(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:t},t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length}getPromises(t=[],r=this.nextId){let n=new Set(t);return Object.values(this.promiseByIds).filter(i=>i.id<=r&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function rAh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var kau=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>kau(`${e} ${o}`,t,r)}},nAh=e=>e();function Fau(e,t=nAh){return kau(e,t,rAh())}var Vut="Mobile",jtn="iOS",Uut="Android",Mau="Tablet",DuC=Uut+" "+Mau;var oAh="Apple",RuC=oAh+" Watch",Lau="Safari",ztn="BlackBerry",_au="Samsung",sAh=_au+"Browser",aAh=_au+" Internet",Qtn="Chrome",cAh=Qtn+" OS",lAh=Qtn+" "+jtn,Uau="Internet Explorer",uAh=Uau+" "+Vut,xJo="Opera",kuC=xJo+" Mini",Vau="Edge",pAh="Microsoft "+Vau,SJo="Firefox",fAh=SJo+" "+jtn,wJo="Nintendo",TJo="PlayStation",Ntn="Xbox",dAh=Uut+" "+Vut,mAh=Vut+" "+Lau,sWt="Windows",hAh=sWt+" Phone";var Gau="Generic",FuC=Gau+" "+Vut.toLowerCase(),NuC=Gau+" "+Mau.toLowerCase(),gAh="Konqueror",AAh="Oculus Browser",Nau="Vivaldi",yAh="Yandex",jau="Whale",bAh="DuckDuckGo",EAh="Pale Moon",zau="Waterfox",Qau="Brave",qau="Claude",Wau="Codex",Hau="ChatGPT",IAh="Google Search App",$b="(\\d+(\\.\\d+)?)",vJo=new RegExp("Version/"+$b),CJo=new RegExp("("+qau+"|"+Wau+"|"+Hau+")\\/"+$b);var juC=new RegExp(Ntn,"i"),zuC=new RegExp(TJo+" \\w+","i"),QuC=new RegExp(wJo+" \\w+","i"),vAh=new RegExp(ztn+"|PlayBook|BB10","i"),CAh={"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 MuC={[uAh]:[new RegExp("rv:"+$b)],[pAh]:[new RegExp(Vau+"?\\/"+$b)],[Qtn]:[new RegExp("("+Qtn+"|CrMo)\\/"+$b)],[lAh]:[new RegExp("CriOS\\/"+$b)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$b)],[Lau]:[vJo],[mAh]:[vJo],[xJo]:[new RegExp("("+xJo+"|OPR)\\/"+$b)],[SJo]:[new RegExp(SJo+"\\/"+$b)],[fAh]:[new RegExp("FxiOS\\/"+$b)],[gAh]:[new RegExp("Konqueror[:/]?"+$b,"i")],[ztn]:[new RegExp(ztn+" "+$b),vJo],[dAh]:[new RegExp("android\\s"+$b,"i")],[aAh]:[new RegExp(sAh+"\\/"+$b)],[AAh]:[new RegExp("OculusBrowser\\/"+$b)],[Nau]:[new RegExp(Nau+"\\/"+$b)],[yAh]:[new RegExp("YaBrowser\\/"+$b)],[jau]:[new RegExp(jau+"\\/"+$b)],[Qau]:[new RegExp(Qau+"\\/"+$b)],[qau]:[CJo],[Wau]:[CJo],[Hau]:[CJo],[bAh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+$b)],[EAh]:[new RegExp("PaleMoon\\/"+$b)],[zau]:[new RegExp(zau+"\\/"+$b)],[IAh]:[new RegExp("GSA\\/"+$b)],[Uau]:[new RegExp("(rv:|MSIE )"+$b)],Mozilla:[new RegExp("rv:"+$b)]};var LuC=[[new RegExp(Ntn+"; "+Ntn+" (.*?)[);]","i"),e=>[Ntn,e&&e[1]||""]],[new RegExp(wJo,"i"),[wJo,""]],[new RegExp(TJo,"i"),[TJo,""]],[vAh,[ztn,""]],[new RegExp(sWt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[hAh,""];if(new RegExp(Vut).test(t)&&!/IEMobile\b/.test(t))return[sWt+" "+Vut,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=CAh[n]||"";return/arm/i.test(t)&&(i="RT"),[sWt,i]}return[sWt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[jtn,t.join(".")]}return[jtn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=mhe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Uut+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Uut+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Uut,t.join(".")]}return[Uut,""]}],[/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/,[cAh,""]],[/Linux|debian/i,["Linux",""]]];var Mtn="[Circular]",Ltn="[Truncated]",T8="[Unserializable]",Kau="[Function]",VuC=Date.prototype.getTime,GuC=Date.prototype.toISOString;function Qre(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="\uFFFD"}else t+=n>=56320&&n<=57343?"\uFFFD":e[r]}return t}function hhe(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let n of r){let i;try{i=t[n]}catch{i=T8}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function OJo(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let s=1e3*Math.min(Number(n),300);return s>0?s:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let i=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(i)-t;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var xVe=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),i=Math.min(t.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+i;return}this._until=Math.max(this._until,Math.min(n+i,this._installedAt+3e5))}remainingMs(){let t=Date.now();if(t<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-t));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Jau="utf8",xAh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function SAh(e){return typeof e=="string"&&xAh.test(e)}function SVe(e,t){return SAh(e)?e:t()}function Gut(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Yau(e){return e?.replace(/\/+$/,"")}async function Xau(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 PJo(){return new Date().toISOString()}function $2(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function Nwe(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=$2(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var Zau=e=>e&&typeof e.then=="function";function aWt(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var _tn,$au,Utn;function ecu(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Utn&&r.length===$au||($au=r.length,Utn=r.reduce((n,i)=>{_tn||(_tn={});let o=_tn[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,u=t[i];if(l&&u){n[l]=u,_tn[i]=[l,u];break}}}return n},{})),Utn}var BJo=50,wAh=1e3,TAh=100,OAh=4,cWt=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&&x3(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;if(t.stack!=""&&t.stack!=null)try{i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...t,cause:n,stack:i,errors:t.errors?.map(o=>this.parseStacktrace(o,r))}}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=[],i=(o,s,a)=>{let c=n.length,l=s===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:s},u={type:o.type,value:o.value,mechanism:l};o.stack&&(u.stacktrace={type:"raw",frames:o.stack}),n.push(u),o.cause&&i(o.cause,c,"cause");for(let p of o.errors??[])i(p,c,"member")};return i(t),n}buildParsingContext(t){return{chunkIdMap:ecu(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(Fwe(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<TAh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return x3(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(t,r,n=0){let i=0,o=0,s=!1,a=new Set,c=[],l={},u=(f,m,g=0)=>{let A=p(m,g),b=A.apply;if(A.apply=D=>{c.push(f);try{return b(D)}finally{c.pop()}},g>OAh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=BJo||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let C=this.getAggregateErrors(f);s||=!!C;let x;try{if(x=this.applyCoercers(f,A),!x)throw l}catch(D){if(D===l){g===0&&i--;return}if(!s)throw D;x=this.coerceFallback(A)}if(!C||i>=BJo)return x;let S;try{S=C.length}catch{return x}if(!Number.isInteger(S)||S<0||S>4294967295)return x;let P=[];for(let D=0;i<BJo&&o<wAh&&D<S;D++){o++;let R;try{R=A.next(C[D])}catch{i++,R=this.coerceFallback(p(m+1))}R&&P.push(R)}return{...x,errors:P}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=u(g,f,m+1);if(!A)throw l;return A},next:g=>u(g,f+1)}),d=p(n);return{...d,apply:f=>u(f,n)??this.coerceFallback(d)}}};var OB="?",PAh="<anonymous>",BAh=/^([a-z][a-z0-9.+-]+):/i,DAh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function RAh(e){if(!e||e===PAh)return!1;let t=BAh.exec(e);return!t||DAh.includes(t[1].toLowerCase())}function Mre(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?OB:r,in_app:RAh(t)};return mhe(n)||(o.lineno=n),mhe(i)||(o.colno=i),o}var Vtn=(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]:OB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var kAh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,FAh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,NAh=/\((\S*)(?::(\d+))(?::(\d+))\)/,DJo=(e,t)=>{let r=kAh.exec(e);if(r){let[,i,o,s]=r;return Mre(t,i,OB,+o,+s)}let n=FAh.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=NAh.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Vtn(n[1]||OB,n[2]);return Mre(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var jAh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zAh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,RJo=(e,t)=>{let r=jAh.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=zAh.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]||OB;return[o,i]=Vtn(o,i),Mre(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var QAh=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,tcu=(e,t)=>{let r=QAh.exec(e);return r?Mre(t,r[2],r[1]||OB,+r[3],r[4]?+r[4]:void 0):void 0};var MAh=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,rcu=(e,t)=>{let r=MAh.exec(e);return r?Mre(t,r[2],r[3]||OB,+r[1]):void 0},LAh=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ncu=(e,t)=>{let r=LAh.exec(e);return r?Mre(t,r[5],r[3]||r[4]||OB,+r[1],+r[2]):void 0};var _Ah=/^\s*[-]{4,}$/,UAh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,VAh=/^Promise\.(?:all|any)$/,GAh=/^index \d+$/,qAh="node:internal/promise",ocu=(e,t)=>{let r=e.match(UAh);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let u=o.lastIndexOf(".");if(o[u-1]==="."&&u--,u>0){n=o.slice(0,u),i=o.slice(u+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||OB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!l&&(c=r[5]),VAh.test(o)&&GAh.test(c||"")&&(c=qAh),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:icu(r[3]),colno:icu(r[4]),in_app:WAh(c||"",l),platform:t}}if(e.match(_Ah))return{filename:e,platform:t}};function WAh(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 icu(e){return parseInt(e||"",10)||void 0}var scu=/\(error: (.*)\)/,acu=50,HAh=10,KAh=1e3;function kJo(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function JAh(e){for(let t=1;t<=HAh;t++){let r=e.length-2*t;if(r<0)break;let n=!0;for(let i=0;i<t;i++){let o=e[r+i];if(!kJo(o,e[r+t+i])){n=!1;break}}if(n){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function YAh(e,t){let r=t.start+t.length,n=lcu(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function ccu(e,t){let r=t.start;for(;r>0&&kJo(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function lcu(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&kJo(e[n],e[n-t.length]);)n++;return n-r}function XAh(e,t){let r=t[0],n=e.length-(r?ccu(e,r):0);for(let i of t)n-=lcu(e,i);return n}function ZAh(e){let t=e.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<t.length;n++)$Ah(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function $Ah(e,t,r){for(let n=0;n<e.length;n++){let i=e[(t+n)%e.length],o=e[(r+n)%e.length];if(i!==o)return i<o}return!1}function ucu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,acu).map(r=>({...r,filename:r.filename||eyh(t).filename,function:r.function||OB}))}function eyh(e){return e[e.length-1]||{}}function FJo(){return pcu("web:javascript",DJo,RJo)}function pcu(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
3497
3497
|
`),s=Math.min(o.length,n+KAh),a=[];for(let u=n;u<s;u++){let p=o[u];if(p.length>1024)continue;let d=scu.test(p)?p.replace(scu,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=JAh(i);if(g){for(let A=a.length-1;A>=0;A--){let b=a[A];if(b.start+b.length<=g.start)break;a.pop()}a.push(g)}break}}if(XAh(i,a)>=acu)break}}let c=[...a].sort((u,p)=>p.start-u.start),l=c[c.length-1];if(l){let u=ccu(i,l);i.splice(l.start-u,u);for(let p of c)p.start-=u}for(let u of c)YAh(i,u);return a.some(u=>u.start===0&&i.length===u.length)&&ZAh(i),ucu(i)}}var NJo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=wR(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 CVe(t,"DOMException")}isDOMError(t){return CVe(t,"DOMError")}};var lWt=class{match(t){return Fwe(t)}coerce(t,r){let n=this.getStack(t),i=n===void 0?r.syntheticException?.stack:void 0,o=!!i;return{type:this.getType(t),value:this.getMessage(t,r),stack:n??i,cause:t.cause?r.next(t.cause):void 0,synthetic:o}}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){try{let r=t.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var jJo=class{match(t){if(!Tau(t))return!1;let r=t;return r.error!=null||this._hasUsableMessage(r)}coerce(t,r){if(t.error!=null)return r.apply(t.error);let n=r.apply(t.message);return{...n,stack:this._buildLocationStack(t)??n.stack,synthetic:!0}}_hasUsableMessage(t){return wR(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!wR(r.filename)||r.filename.length===0)&&n!==0)return`Error
|
|
3498
|
-
at ${r.filename}:${n}:${i}`}};var tyh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,uWt=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(tyh);return i&&(r=i[1],n=i[2]),[r,n]}};var fcu=["fatal","error","warning","log","info","debug"];function Gtn(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 pWt=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:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(_ut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!bJo(r)?r:"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=Gtn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!bJo(t)&&fcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(Fwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var zJo=class{match(t){return _ut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Gtn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var fWt=class{match(t){return Ptn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var QJo=class{match(t){return CVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!_ut(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 Ptn(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 MJo=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 dWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},ryh=new Set([dWt.MESSAGE,dWt.TIMESTAMP]),qtn={enabled:!0,max_bytes:32768};function LJo(e){return e?{enabled:e.enabled??qtn.enabled,max_bytes:iyh(e.max_bytes,qtn.max_bytes)}:{...qtn}}function nyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>ryh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var _Jo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=LJo(t)}setConfig(t){this._config=LJo(t),this._trimToMaxBytes()}add(t){let r=oyh(t);if(!r)return;let n=dcu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function iyh(e,t){if(!Lut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function oyh(e){let t;try{t=kwe(e)}catch{return}try{let r=JSON.parse(t);if(!iWt(r))return;let n=r,i=n[dWt.MESSAGE],o=n[dWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Lut(o)?void 0:{step:n,json:t}}catch{return}}function dcu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function syh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var UJo=e=>{if("flags"in e){let t=mcu(e.flags),r=hcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,qut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,ayh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function ayh(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 mcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,mWt(r)]).filter(([,t])=>t!==void 0)),hcu=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?qut(n):void 0]}))},mWt=e=>e===void 0?void 0:e.variant??e.enabled,qut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var gcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],cyh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...gcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],hWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return cyh.forEach(n),t.forEach(n),r};var Wtn=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)}};function VJo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var uyh="NativeGzipValidationError",pyh=31,fyh=139,dyh=8,myh=e=>e.length>=2&&e[0]===pyh&&e[1]===fyh;var gWt,hyh=()=>{if(gWt)return gWt;gWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;gWt[e]=t>>>0}return gWt},gyh=e=>{let t=hyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Htn=e=>{throw Gut(uyh,`Native gzip produced invalid output: ${e}`)},Ayh=async(e,t)=>{e.size<18&&Htn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!myh(r)||r[2]!==dyh)&&Htn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==gyh(t)&&Htn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Htn("invalid-size")};async function AWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Ayh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var O8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return OJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Gut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Gut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},ghe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Icu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Acu(e){if(e instanceof O8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 yyh(e){return typeof e=="object"&&(e instanceof O8||vcu(e))}function vcu(e){return e instanceof ghe}function byh(e){if(e instanceof O8)return e.status===502||e.status===504;if(!(e instanceof ghe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var ycu=10485760;function bcu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Jau):new TextEncoder().encode(e).length}catch{return 0}}function Wut(e){return typeof e=="object"&&e instanceof O8&&e.status===413}function Ktn(e){return e instanceof O8?e.status===408||e.status===429||e.status>=500:vcu(e)}function Ecu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var GJo="default",yWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new cWt([new lWt,new pWt,new uWt,new fWt],FJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ftn,this._events=new Wtn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Fau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Yau(i||"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:Ktn},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,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=!VJo()||(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(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.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){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Icu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=hWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}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 groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("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,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).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}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:byh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:UJo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof O8)return{type:"api_error",statusCode:t.status};if(t instanceof ghe){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=mWt(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={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.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"),l.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:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(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,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}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(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return GJo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[GJo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){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 o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Ecu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=SVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:PJo(),uuid:SVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(Ecu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Acu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>aWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),aWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return AWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=GJo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:PJo()};this.historicalMigration&&(i.historical_migration=!0);let o=kwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Wut(p)?!1:Ktn(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Wut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof ghe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=bcu(i);if(o>ycu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${ycu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Wut(u)||u instanceof O8&&u.retryAfterMs!==void 0?!1:Ktn(u)}),{kind:"ok"}}catch(u){if(Wut(u))return{kind:"too-large"};if(Ktn(u)){let p=u instanceof O8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=bcu(s),c={...this._retryOptions,...i},l=0;return await Xau(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=$2(()=>{let S=Gut("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new ghe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new ghe(P)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new O8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new ghe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof O8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Nwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!yyh(i))throw i;await Acu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}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 xyh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var YfC=new RegExp(xyh.source,"i"),Ccu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,XfC=new RegExp(`^${Ccu.source}`,"i"),ZfC=new RegExp(Ccu.source,"gi");var Syh=["is_not","is_set"],wyh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function qJo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!qJo(t in e?e[t]:null))return!1;return!0}function WJo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!WJo(t in e?e[t]:null))return!1;return!0}function bWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function Ytn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void bWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Ytn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))bWt(n),Ytn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function Tyh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function HJo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return bWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?HJo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(bWt),`{${n.sort(Tyh).map(i=>`${JSON.stringify(i)}:${HJo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function Jtn(e){return typeof e=="string"?(bWt(e),e):HJo(e)}function xcu(e){try{return new RegExp(e),!0}catch{return!1}}function P8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function wcu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:wcu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function B8(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 Oyh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Pyh(e,t){let[r,n,i]=Fw(e,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 Byh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return wcu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function Scu(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 Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function KJo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!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}function JJo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Syh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&qJo(p)||Array.isArray(p)&&p.length===0)return Ytn(d),WJo(p)===WJo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&qJo(p))return Ytn(d),!1;if(Array.isArray(p)){let f=Jtn(d).toLowerCase();return p.some(m=>Jtn(m).toLowerCase()===f)}return Jtn(p).toLowerCase()===Jtn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return P8(c).includes(P8(i));case"not_icontains":return!P8(c).includes(P8(i));case"starts_with":return P8(c).startsWith(P8(i));case"not_starts_with":return!P8(c).startsWith(P8(i));case"ends_with":return P8(c).endsWith(P8(i));case"not_ends_with":return!P8(c).endsWith(P8(i));case"regex":return xcu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return xcu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=KJo(String(i));p==null&&(p=Scu(i));let d=Scu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return B8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return B8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return B8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return B8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return B8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return B8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=Oyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=Pyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=Byh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function Tcu(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(n=>n.toString(16).padStart(2,"0")).join("")}async function EWt(e,t,r="",n="."){let i=await Tcu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/wyh}async function YJo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await EWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Xtn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function XJo(e,t,r){let n=await EWt(e,t,"variant");return Xtn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function ZJo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:qut(n)}var Ocu=9223372036854776e3,Dyh="9223372036854775808",Ryh=Object.prototype.propertyIsEnumerable;function kyh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Lre(e,t){try{return Pcu(e,t,kyh(),0)}catch{return[]}}function Fyh(e,t){let r=e.toString(),n=BigInt(Dyh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function tYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Ltn};if(r.remainingNodes--,wau(e))return{boolValue:e};if(typeof e=="bigint")return Fyh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Ocu||e<-Ocu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Qre(e)};if(typeof e=="function")return{stringValue:Kau};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Mtn};if(n>=20)return{stringValue:Ltn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Qre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return tYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:Nyh(e,t,r,n+1)}}:{kvlistValue:{values:Pcu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Qre(String(e))}}function Nyh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(AJ(a))continue;i.push(tYo(a,t,r,n))}catch{i.push({stringValue:T8})}return e.length>s&&i.push({stringValue:Ltn}),i}function Pcu(e,t,r,n){let i=[];for(let o in e)if(Ryh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(EJo(s)||mhe(s))continue;i.push({key:Qre(o),value:tYo(s,t,r,n)})}catch{i.push({key:Qre(o),value:{stringValue:T8}})}}return i}function vWt(e,t,r){return{...hhe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var jyh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function CWt(e,t){let r=hhe({},e),n={};for(let i of jyh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Lre(r,t),...Lre(n,t)]}var Bcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function zyh(e){if(e)return Object.prototype.hasOwnProperty.call(Bcu,e)?Bcu[e]:e}function rYo(e,t){let r=zyh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var Qyh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},mdC=Qyh.info;var wVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function xWt(){return 1-.25+Math.random()*.25*2}var D8=1;function SWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var wWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function nYo(e){return String(e)+"000000"}function iYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Dcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function oYo(e,t,r){return vWt(e,t,r)}function sYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:CWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function $tn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Rcu=1,TWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new wVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=iYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(wWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Dcu(r,wWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=xWt()):(this._consecutiveFlushFailures=0,this._flushJitter=D8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return sYo(this._buildMetrics(t),oYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=nYo(Date.now()),n=new Map;for(let i of t.values()){let o=iYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Rcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Rcu,dataPoints:[]},n.set(o,s));let a=Lre(i.attributes??{},this._logger),c=nYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:wWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var Uyh="0".repeat(32),Vyh="0".repeat(16),Gyh=/^[0-9a-f]+$/;function qyh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Wyh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function kcu(e){let t=Wyh(qyh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Fcu(){return kcu(16)}function Ncu(){return kcu(8)}function jcu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Gyh.test(e)}function zcu(e){return jcu(e,32,Uyh)}function Qcu(e){return jcu(e,16,Vyh)}var Hyh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Mcu(e){let t=Lcu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Kyh(t.flags)}}function Kyh(e){return 1&parseInt(e,16)?trn:Jyh}function Lcu(e){if(typeof e!="string")return;let t=Hyh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!zcu(n)||!Qcu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function _cu(e){return Lcu(e)&&e.trim()}function ern(e){return Array.isArray(e)&&e.length===1?e[0]:e}var trn="01",Jyh="00";function Ucu(e,t,r=trn){return`00-${e}-${t}-${r}`}var Yyh=32,aYo=512;function rrn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Yyh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=aYo?t:Zyh(r)}}var Xyh=128;function Zyh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>aYo;n--)t[n].length>Xyh&&t.splice(n,1);for(;t.length&&r()>aYo;)t.pop();return t.length?t.join(","):void 0}var Vcu="unknown";function TVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Vcu}"`),Vcu)}function Hut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function Gcu(e,t,r){let n=Hut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function nrn(e,t){return e<t?t:e}function OWt(e,t,r,n){let i=Hut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function orn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Kut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??trn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:orn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=orn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(AJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=arn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=hhe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Kcu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:TVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:OWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:cYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=lYo(t);return this.addEvent($yh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=TVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Ucu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=OWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:nrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},$yh="exception",ebh=4294967295;function tbh(e){try{return typeof e=="string"?e:String(e)}catch{return T8}}function OVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),ebh)}function rbh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function Wcu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of rbh(e.attributes,s)){let m=e.attributes[f];if(!AJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:arn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=OVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Kcu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=OVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=OVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:cYo(tbh(e.status.message),o)})}var srn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Hcu=new srn,PWt=class extends srn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function nbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function jwe(e,t){let r=ern(e?.parent)??t,n=typeof r=="string"||r==null?r:qcu(r,"traceparent"),i=_cu(n);if(!i)return Hcu;let o=typeof r=="string"||r==null?e?.tracestate:qcu(r,"tracestate");return new PWt(i,rrn(o))}function qcu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function cYo(e,t){return e.length>t?e.slice(0,t):e}function arn(e,t){return irn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function irn(e,t,r,n){if(e===null||typeof e!="object")return AJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?cYo(e,t):e);if(r.ancestors.has(e))return Mtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=ibh(e);if(i.selfDescribed)return AJ(i.value)?String(i.value):irn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(irn(e[l],t,r,n+1))}catch{c.push(T8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=irn(e[a],t,r,n+1)}catch{c=T8}a&&!AJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function ibh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Kcu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=arn(e[a],r)}catch{c=T8}AJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Jcu(e,t){for(let r of Object.keys(e))e[r]=arn(e[r],t);return e}function BWt(e,t,r){return t===Hcu?r(t):e.with(t,()=>r(t))}function lYo(e){try{let t=nbh(e);if(Fwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var uYo={internal:1,server:2,client:3,producer:4,consumer:5},obh={ok:1,error:2},sbh=1,abh=256,cbh=512;function lbh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:sbh)|abh|(e.parentIsRemote?cbh:0)}function crn(e){if(typeof e=="string")return Qre(e);try{return Qre(String(e))}catch{return T8}}function ubh(e){return e&&Object.prototype.hasOwnProperty.call(uYo,e)?uYo[e]:uYo.internal}function pYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function pbh(e,t){let r={name:crn(e.name),timeUnixNano:pYo(e.timestamp)};if(e.attributes){let i=Lre(e.attributes,t);i.length&&(r.attributes=i)}let n=OVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Ycu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:crn(e.name),kind:ubh(e.kind),startTimeUnixNano:pYo(e.startTime),endTimeUnixNano:pYo(e.endTime),flags:lbh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=crn(e.traceState));let n=Lre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>pbh(s,t)));let i=OVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=OVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:obh[e.status.code],...e.status.message&&{message:crn(e.status.message)}}),r}function Xcu(e,t,r){return vWt(e,t,r)}function Zcu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:CWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var $cu=8;function lrn(){return orn()??Date.now()}function fYo(e){try{return e instanceof Kut}catch{return!1}}function elu(e,t){let r=Mcu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:rrn(t),traceFlags:r.flags,isRemote:!0}}function fbh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function dbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function urn(e,t,r){e[t]!==r&&(e[t]=r)}function mbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var DWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new wVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return jwe(r,this._contextManager.active());let n=ern(r?.parent);if(n&&typeof n!="string"&&!fYo(n)){if(fbh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),jwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),jwe(r,this._contextManager.active());let o=Date.now(),s=Gcu(r?.startTime,o,this._logger),a=Ncu();this._liveSpans.set(a,lrn());let c=this._autoContextAttributes();return new Kut({traceId:i?.traceId??Fcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:TVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:hhe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Hut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=BWt(this._contextManager,s,o);return Zau(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=elu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(fYo(t))return t.childContext();let n=this._contextManager.active();if(fYo(n))return n.childContext();if(n instanceof PWt)return elu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Kut))return;let{type:n,message:i,stack:o}=lYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=lrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!dbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=TVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Hut(u.startTime)??i.startTime,u.endTime=nrn(Hut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:TVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:OWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,Wcu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{urn(t,"traceId",r.traceId),urn(t,"spanId",r.spanId),urn(t,"parentSpanId",r.parentSpanId),urn(t,"traceState",r.traceState)}catch{return mbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Ycu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Jcu(Xcu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=lrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Zcu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=xWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=lrn()+this._nextFlushDelay()),this._headBatchFailures<$cu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${$cu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var RWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var hbh=5e3,gbh=512,Abh=2048,ybh=128,bbh=128,Ebh=128,Ibh=8192,vbh=1e4,Cbh=36e5;function zwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var tlu=["service.name","service.version","deployment.environment"];function xbh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(tlu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of tlu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Sbh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function dYo(e,t,r){let n=hhe({...t},xbh(e?.resourceAttributes)),i=zwe(e?.maxExportBatchSize,gbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Sbh(e?.beforeSpanSend,r),maxAttributesPerSpan:zwe(e?.maxAttributesPerSpan,ybh),maxEventsPerSpan:zwe(e?.maxEventsPerSpan,bbh),maxAttributesPerEvent:Ebh,maxAttributeValueLength:zwe(e?.maxAttributeValueLength,Ibh),flushIntervalMs:zwe(e?.flushIntervalMs,hbh),maxExportBatchSize:i,maxQueueSize:Math.max(zwe(e?.maxQueueSize,Abh),i),maxLiveSpans:zwe(e?.maxLiveSpans,vbh),maxSpanAgeMs:zwe(e?.maxSpanAgeMs,Cbh)}}var mYo=require("fs"),ilu=require("fs/promises"),gYo=require("path"),olu=require("readline"),prn=new LT.ReduceableCache(25),kWt=new LT.ReduceableCache(20),AYo=7,wbh=1e3,Tbh=1e4,hYo=10485760;async function slu(e,t=ilu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Rbh(l)||kbh(c)||!(0,gYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=alu(a,i);if(c===void 0||kWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=Nbh(l);if(u.every(d=>Fbh(c,d)))continue;let p=jbh(prn,c,{});s.push(Pbh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Bbh(e,prn,i),prn.reduce(),e}async function Obh(e,t,r){let n,i=!1;try{n=await t(e,mYo.constants.O_RDONLY|mYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>hYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${hYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Pbh(e,t,r,n,i,o){let s=await Obh(e,i,o);if(s===void 0)return void kWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:hYo-1})}catch{kWt.set(n,1),u();return}let d;try{d=(0,olu.createInterface)({input:p})}catch{kWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){kWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=zbh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Bbh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=alu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Dbh(n.lineno,n,o)}}function Dbh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=clu(e);i<e;i++){let o=r[i];if(o===void 0)return void rlu(t);t.pre_context.push(o)}if(r[e]===void 0)return void rlu(t);t.context_line=r[e];let n=llu(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 rlu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Rbh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function kbh(e){return e.lineno!==void 0&&e.lineno>Tbh||e.colno!==void 0&&e.colno>wbh}function alu(e,t){return(0,gYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Fbh(e,t){let r=prn.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 Nbh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=nlu(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+AYo:(i.push(n),n=nlu(o)),t++}return i}function nlu(e){return[clu(e),llu(e)]}function clu(e){return Math.max(1,e-AYo)}function llu(e){return e+AYo}function jbh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function zbh(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}var Jut=require("path");function ulu(e=process.cwd()){let t=Jut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Jut.isAbsolute)(o.filename)&&(o.filename=r((0,Jut.relative)(n,r(o.filename))));return i}}var plu="5.55.0";var Ahe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Qwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Ahe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Ahe.QUOTA_LIMITED),r===void 0&&o.push(Ahe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var Qbh=6e4;function flu(e){return e==="client"||e==="server"?e:"all"}function Mbh(e,t){return e===t||e==="all"||t==="all"}var Yut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Lbh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var _re=class e extends Error{constructor(t){super(t),Lbh(this,e)}},frn=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.pollerStopped=!1,this.filteredOutFlagKeys=new Set,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.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}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(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}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=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=ZJo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l 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 u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===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 Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,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}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`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){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await YJo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof _re)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await mlu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):dlu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await EWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return XJo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Xtn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?flu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Mbh(flu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!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(this.featureFlags),!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(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(Qbh,t*2**this.backOffCount):t}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);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 Yut(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Yut(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Yut(`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=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Yut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}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}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Nwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function dlu(e,t,r,n){return JJo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function _bh(e,t){if(!(e in t))throw new _re(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function mlu(e,t,r,n=!1,i,o){let s=String(e.value);_bh(s,r);let a=r[s];return hlu(a,t,r,n,i,o)}async function hlu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await hlu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await mlu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=dlu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var Ubh=["--unhandled-rejections","--unhandled_rejections"],Vbh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Gbh=[...globalThis.process?.execArgv??[]],qbh=globalThis.process?.env?.NODE_OPTIONS;function Wbh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function glu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Ubh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Vbh.has(o)&&(t=o)}return t}function Hbh(e=Gbh,t=qbh){return glu(e)??glu(Wbh(t??""))??"throw"}var Alu=Hbh();function ylu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Kbh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;ylu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function blu(e,t,r=Alu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>ylu(e,i,o));n.on("uncaughtException",Kbh(e,t))}}function Elu(e,t=Alu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Jbh=2e3,yYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Dtn({...Dau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return iWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(blu(this.onException.bind(this),this.onFatalError.bind(this)),Elu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),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._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Jbh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},PVe=yYo;var drn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Ybh(e){return e==="v0"||e==="v1"}function Ilu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Ybh(e)?e:"v0"}var Xbh="$ai_",FWt="analytics";function vlu(e){return typeof e.event=="string"&&e.event.startsWith(Xbh)}var Xut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function bYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Zbh(e){return typeof e=="string"?e:void 0}var $bh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Zbh}],eEh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function tEh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Clu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function nEh(e){let r={...tEh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of $bh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of eEh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Clu(r,"$set",e.$set),Clu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:rEh(e.timestamp),...i,options:n,properties:r}}function xlu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(nEh)};return r&&(n.historical_migration=!0),n}var iEh="/i/v1/analytics/events",oEh=3e4,sEh=new Set([408,500,502,503,504]),mrn=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??oEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??AWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=xlu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${iEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=kwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&sEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Xut({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Xut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Xut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var BVe="ai-capture",hrn="/i/v0/ai/batch/";var cEh=new TextEncoder;function IYo(e){return cEh.encode(kwe(e)).length}function Slu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=IYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var lEh=100,wlu=3e4,uEh=5e4,pEh=50,fEh=500,dEh="https://us.i.posthog.com",Tlu=new Set;function Arn(e,t){Tlu.has(e)||(Tlu.add(e),console.warn(`[PostHog] ${t}`))}function mEh(e){return typeof e=="string"?e.trim():""}function hEh(e){return(typeof e=="string"?e.trim():"")||void 0}function gEh(e){return(typeof e=="string"?e.trim():"")||dEh}function AEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function yEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var yrn=class extends yWt{constructor(t,r={}){let n=mEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:gEh(r.host),personalApiKey:hEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new drn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Ilu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,lEh):i.featureFlagsPollingInterval===null?null:wlu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new frn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new PVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||uEh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:aWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}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??fEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??pEh;this._waitUntilCycle.timer=$2(()=>{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 this._flushEventsAndSpans()}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)}getQueueRouteKey(t){return this.captureMode==="v1"&&vlu(t)?"ai":FWt}persistedQueueKeyForRoute(t){return t===BVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[FWt,"ai"]:[FWt];return this._aiCaptureRouteActive&&t.push(BVe),t}getBatchEndpointPath(t){return t===BVe?hrn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=FWt){if(n===BVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=Slu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${hrn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,BVe)}catch(n){if(!Wut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${IYo(o)} bytes) was rejected with 413 by ${hrn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new mrn({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return plu}get metrics(){return this._metrics||(this._metrics=new TWt(this,$tn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new RWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new DWt(this,dYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??jwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):BWt(this._spanContextManager,jwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","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._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,BVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=AEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=wlu){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){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof _re||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Ahe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Ahe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Ahe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Ahe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Arn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");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(Arn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),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.disabled)return void this._logger.warn("The client is disabled");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){Arn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!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:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}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=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await Nwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Nwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!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=$2(()=>{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(Oau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");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 l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,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={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!PVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!PVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?hWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Arn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return yEh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Bau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.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)try{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)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Olu=require("async_hooks"),brn=class{constructor(){this.storage=new Olu.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 Plu=require("async_hooks"),Ern=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Plu.AsyncLocalStorage}};var Blu=require("zlib"),Dlu=require("util"),bEh=(0,Dlu.promisify)(Blu.gzip);async function Rlu(e,t=!0){try{let r=await bEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Irn=require("os");function klu(){let e,t;try{e=(0,Irn.platform)(),t=(0,Irn.release)()}catch{}return rYo(e,t)}var Flu="posthog-node";function EEh(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[vYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,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},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),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 vYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Flu,this.name=Flu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(EEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Ure=class extends yrn{getLibraryId(){return"posthog-node"}compressPayload(t){return Rlu(t,this.isDebug)}initializeContext(){return new brn}initializeSpanContextManager(){return new Ern}hostResourceAttributes(){return klu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[Cau(),t=>slu(t,void 0,this._logger),ulu()])}};function Nlu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var vrn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},IEh="feature_flag_evaluated",vEh=3e3,CEh=3e3,Crn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Ure(n??"",{featureFlagsRequestTimeoutMs:vEh,isServer:!1})}isEnabled(t,r){let n=jlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(jlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,CEh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=SEh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,CYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Nlu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=xEh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.228.0"};this.tryCapture({distinctId:CYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:CYo(r),event:IEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Nlu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function xEh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function CYo(e){return`org:${e}`}function SEh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function jlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var xrn;function Srn(){return xrn==null&&(xrn=wEh()),xrn}async function xYo(){await xrn?.flush()}function wEh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new vrn:new Crn({posthogApiKey:e,environment:gJ(),sendFeatureFlagEvents:Ttn()})}var wrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Ure(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.228.0",usingAccessToken:!0,cliReleaseEnvironment:gJ(),...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var NWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var Zut=require("fs/promises"),zlu=require("os"),Qlu=require("path");TUe();var TEh="id",OEh=".fern",jWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Ure(r,{isServer:!1}),this.userId=t==null?void 0:JJi(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:"5.228.0",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:gJ(),agent:Dpr(),...r!=null?{userEmail:r}:{},...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}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 Dl({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=Dw(),r=Re(Zt.of((0,zlu.homedir)()),be.of(OEh),be.of(TEh));try{await Ut(r)?this.persistedDistinctId=(await(0,Zut.readFile)(r)).toString():(await(0,Zut.mkdir)((0,Qlu.dirname)(r),{recursive:!0}),await(0,Zut.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var SYo;async function zWt(){return SYo==null&&(SYo=await PEh()),SYo}async function PEh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!Ttn())return new NWt;let t=await uZe();return t!=null?new jWt({token:t,posthogApiKey:e}):await jz()!=null?new wrn({posthogApiKey:e}):new jWt({token:void 0,posthogApiKey:e})}catch{return new NWt}}tn();mt();Bt();_Q();var QWt=Ae(require("process"),1);yKe();var _lu=Ae(s$i(),1),Ulu=Ae(Llu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=w7(e),e.length===0))return 0;e=e.replace((0,Ulu.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(_lu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function Trn(e){let t=0;for(let r of e.split(`
|
|
3498
|
+
at ${r.filename}:${n}:${i}`}};var tyh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,uWt=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(tyh);return i&&(r=i[1],n=i[2]),[r,n]}};var fcu=["fatal","error","warning","log","info","debug"];function Gtn(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 pWt=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:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(_ut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!bJo(r)?r:"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=Gtn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!bJo(t)&&fcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(Fwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var zJo=class{match(t){return _ut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Gtn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var fWt=class{match(t){return Ptn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var QJo=class{match(t){return CVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!_ut(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 Ptn(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 MJo=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 dWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},ryh=new Set([dWt.MESSAGE,dWt.TIMESTAMP]),qtn={enabled:!0,max_bytes:32768};function LJo(e){return e?{enabled:e.enabled??qtn.enabled,max_bytes:iyh(e.max_bytes,qtn.max_bytes)}:{...qtn}}function nyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>ryh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var _Jo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=LJo(t)}setConfig(t){this._config=LJo(t),this._trimToMaxBytes()}add(t){let r=oyh(t);if(!r)return;let n=dcu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function iyh(e,t){if(!Lut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function oyh(e){let t;try{t=kwe(e)}catch{return}try{let r=JSON.parse(t);if(!iWt(r))return;let n=r,i=n[dWt.MESSAGE],o=n[dWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Lut(o)?void 0:{step:n,json:t}}catch{return}}function dcu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function syh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var UJo=e=>{if("flags"in e){let t=mcu(e.flags),r=hcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,qut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,ayh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function ayh(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 mcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,mWt(r)]).filter(([,t])=>t!==void 0)),hcu=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?qut(n):void 0]}))},mWt=e=>e===void 0?void 0:e.variant??e.enabled,qut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var gcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],cyh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...gcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],hWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return cyh.forEach(n),t.forEach(n),r};var Wtn=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)}};function VJo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var uyh="NativeGzipValidationError",pyh=31,fyh=139,dyh=8,myh=e=>e.length>=2&&e[0]===pyh&&e[1]===fyh;var gWt,hyh=()=>{if(gWt)return gWt;gWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;gWt[e]=t>>>0}return gWt},gyh=e=>{let t=hyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Htn=e=>{throw Gut(uyh,`Native gzip produced invalid output: ${e}`)},Ayh=async(e,t)=>{e.size<18&&Htn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!myh(r)||r[2]!==dyh)&&Htn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==gyh(t)&&Htn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Htn("invalid-size")};async function AWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Ayh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var O8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return OJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Gut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Gut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},ghe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Icu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Acu(e){if(e instanceof O8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 yyh(e){return typeof e=="object"&&(e instanceof O8||vcu(e))}function vcu(e){return e instanceof ghe}function byh(e){if(e instanceof O8)return e.status===502||e.status===504;if(!(e instanceof ghe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var ycu=10485760;function bcu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Jau):new TextEncoder().encode(e).length}catch{return 0}}function Wut(e){return typeof e=="object"&&e instanceof O8&&e.status===413}function Ktn(e){return e instanceof O8?e.status===408||e.status===429||e.status>=500:vcu(e)}function Ecu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var GJo="default",yWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new cWt([new lWt,new pWt,new uWt,new fWt],FJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ftn,this._events=new Wtn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Fau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Yau(i||"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:Ktn},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,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=!VJo()||(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(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.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){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Icu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=hWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}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 groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("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,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).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}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:byh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:UJo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof O8)return{type:"api_error",statusCode:t.status};if(t instanceof ghe){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=mWt(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={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.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"),l.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:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(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,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}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(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return GJo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[GJo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){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 o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Ecu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=SVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:PJo(),uuid:SVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(Ecu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Acu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>aWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),aWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return AWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=GJo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:PJo()};this.historicalMigration&&(i.historical_migration=!0);let o=kwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Wut(p)?!1:Ktn(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Wut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof ghe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=bcu(i);if(o>ycu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${ycu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Wut(u)||u instanceof O8&&u.retryAfterMs!==void 0?!1:Ktn(u)}),{kind:"ok"}}catch(u){if(Wut(u))return{kind:"too-large"};if(Ktn(u)){let p=u instanceof O8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=bcu(s),c={...this._retryOptions,...i},l=0;return await Xau(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=$2(()=>{let S=Gut("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new ghe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new ghe(P)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new O8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new ghe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof O8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Nwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!yyh(i))throw i;await Acu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}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 xyh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var YfC=new RegExp(xyh.source,"i"),Ccu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,XfC=new RegExp(`^${Ccu.source}`,"i"),ZfC=new RegExp(Ccu.source,"gi");var Syh=["is_not","is_set"],wyh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function qJo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!qJo(t in e?e[t]:null))return!1;return!0}function WJo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!WJo(t in e?e[t]:null))return!1;return!0}function bWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function Ytn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void bWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Ytn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))bWt(n),Ytn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function Tyh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function HJo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return bWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?HJo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(bWt),`{${n.sort(Tyh).map(i=>`${JSON.stringify(i)}:${HJo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function Jtn(e){return typeof e=="string"?(bWt(e),e):HJo(e)}function xcu(e){try{return new RegExp(e),!0}catch{return!1}}function P8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function wcu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:wcu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function B8(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 Oyh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Pyh(e,t){let[r,n,i]=Fw(e,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 Byh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return wcu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function Scu(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 Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function KJo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!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}function JJo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Syh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&qJo(p)||Array.isArray(p)&&p.length===0)return Ytn(d),WJo(p)===WJo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&qJo(p))return Ytn(d),!1;if(Array.isArray(p)){let f=Jtn(d).toLowerCase();return p.some(m=>Jtn(m).toLowerCase()===f)}return Jtn(p).toLowerCase()===Jtn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return P8(c).includes(P8(i));case"not_icontains":return!P8(c).includes(P8(i));case"starts_with":return P8(c).startsWith(P8(i));case"not_starts_with":return!P8(c).startsWith(P8(i));case"ends_with":return P8(c).endsWith(P8(i));case"not_ends_with":return!P8(c).endsWith(P8(i));case"regex":return xcu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return xcu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=KJo(String(i));p==null&&(p=Scu(i));let d=Scu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return B8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return B8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return B8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return B8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return B8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return B8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=Oyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=Pyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=Byh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function Tcu(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(n=>n.toString(16).padStart(2,"0")).join("")}async function EWt(e,t,r="",n="."){let i=await Tcu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/wyh}async function YJo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await EWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Xtn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function XJo(e,t,r){let n=await EWt(e,t,"variant");return Xtn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function ZJo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:qut(n)}var Ocu=9223372036854776e3,Dyh="9223372036854775808",Ryh=Object.prototype.propertyIsEnumerable;function kyh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Lre(e,t){try{return Pcu(e,t,kyh(),0)}catch{return[]}}function Fyh(e,t){let r=e.toString(),n=BigInt(Dyh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function tYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Ltn};if(r.remainingNodes--,wau(e))return{boolValue:e};if(typeof e=="bigint")return Fyh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Ocu||e<-Ocu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Qre(e)};if(typeof e=="function")return{stringValue:Kau};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Mtn};if(n>=20)return{stringValue:Ltn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Qre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return tYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:Nyh(e,t,r,n+1)}}:{kvlistValue:{values:Pcu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Qre(String(e))}}function Nyh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(AJ(a))continue;i.push(tYo(a,t,r,n))}catch{i.push({stringValue:T8})}return e.length>s&&i.push({stringValue:Ltn}),i}function Pcu(e,t,r,n){let i=[];for(let o in e)if(Ryh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(EJo(s)||mhe(s))continue;i.push({key:Qre(o),value:tYo(s,t,r,n)})}catch{i.push({key:Qre(o),value:{stringValue:T8}})}}return i}function vWt(e,t,r){return{...hhe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var jyh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function CWt(e,t){let r=hhe({},e),n={};for(let i of jyh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Lre(r,t),...Lre(n,t)]}var Bcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function zyh(e){if(e)return Object.prototype.hasOwnProperty.call(Bcu,e)?Bcu[e]:e}function rYo(e,t){let r=zyh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var Qyh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},mdC=Qyh.info;var wVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function xWt(){return 1-.25+Math.random()*.25*2}var D8=1;function SWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var wWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function nYo(e){return String(e)+"000000"}function iYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Dcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function oYo(e,t,r){return vWt(e,t,r)}function sYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:CWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function $tn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Rcu=1,TWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new wVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=iYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(wWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Dcu(r,wWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=xWt()):(this._consecutiveFlushFailures=0,this._flushJitter=D8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return sYo(this._buildMetrics(t),oYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=nYo(Date.now()),n=new Map;for(let i of t.values()){let o=iYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Rcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Rcu,dataPoints:[]},n.set(o,s));let a=Lre(i.attributes??{},this._logger),c=nYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:wWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var Uyh="0".repeat(32),Vyh="0".repeat(16),Gyh=/^[0-9a-f]+$/;function qyh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Wyh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function kcu(e){let t=Wyh(qyh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Fcu(){return kcu(16)}function Ncu(){return kcu(8)}function jcu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Gyh.test(e)}function zcu(e){return jcu(e,32,Uyh)}function Qcu(e){return jcu(e,16,Vyh)}var Hyh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Mcu(e){let t=Lcu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Kyh(t.flags)}}function Kyh(e){return 1&parseInt(e,16)?trn:Jyh}function Lcu(e){if(typeof e!="string")return;let t=Hyh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!zcu(n)||!Qcu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function _cu(e){return Lcu(e)&&e.trim()}function ern(e){return Array.isArray(e)&&e.length===1?e[0]:e}var trn="01",Jyh="00";function Ucu(e,t,r=trn){return`00-${e}-${t}-${r}`}var Yyh=32,aYo=512;function rrn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Yyh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=aYo?t:Zyh(r)}}var Xyh=128;function Zyh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>aYo;n--)t[n].length>Xyh&&t.splice(n,1);for(;t.length&&r()>aYo;)t.pop();return t.length?t.join(","):void 0}var Vcu="unknown";function TVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Vcu}"`),Vcu)}function Hut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function Gcu(e,t,r){let n=Hut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function nrn(e,t){return e<t?t:e}function OWt(e,t,r,n){let i=Hut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function orn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Kut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??trn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:orn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=orn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(AJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=arn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=hhe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Kcu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:TVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:OWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:cYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=lYo(t);return this.addEvent($yh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=TVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Ucu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=OWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:nrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},$yh="exception",ebh=4294967295;function tbh(e){try{return typeof e=="string"?e:String(e)}catch{return T8}}function OVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),ebh)}function rbh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function Wcu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of rbh(e.attributes,s)){let m=e.attributes[f];if(!AJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:arn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=OVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Kcu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=OVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=OVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:cYo(tbh(e.status.message),o)})}var srn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Hcu=new srn,PWt=class extends srn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function nbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function jwe(e,t){let r=ern(e?.parent)??t,n=typeof r=="string"||r==null?r:qcu(r,"traceparent"),i=_cu(n);if(!i)return Hcu;let o=typeof r=="string"||r==null?e?.tracestate:qcu(r,"tracestate");return new PWt(i,rrn(o))}function qcu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function cYo(e,t){return e.length>t?e.slice(0,t):e}function arn(e,t){return irn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function irn(e,t,r,n){if(e===null||typeof e!="object")return AJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?cYo(e,t):e);if(r.ancestors.has(e))return Mtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=ibh(e);if(i.selfDescribed)return AJ(i.value)?String(i.value):irn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(irn(e[l],t,r,n+1))}catch{c.push(T8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=irn(e[a],t,r,n+1)}catch{c=T8}a&&!AJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function ibh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Kcu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=arn(e[a],r)}catch{c=T8}AJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Jcu(e,t){for(let r of Object.keys(e))e[r]=arn(e[r],t);return e}function BWt(e,t,r){return t===Hcu?r(t):e.with(t,()=>r(t))}function lYo(e){try{let t=nbh(e);if(Fwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var uYo={internal:1,server:2,client:3,producer:4,consumer:5},obh={ok:1,error:2},sbh=1,abh=256,cbh=512;function lbh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:sbh)|abh|(e.parentIsRemote?cbh:0)}function crn(e){if(typeof e=="string")return Qre(e);try{return Qre(String(e))}catch{return T8}}function ubh(e){return e&&Object.prototype.hasOwnProperty.call(uYo,e)?uYo[e]:uYo.internal}function pYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function pbh(e,t){let r={name:crn(e.name),timeUnixNano:pYo(e.timestamp)};if(e.attributes){let i=Lre(e.attributes,t);i.length&&(r.attributes=i)}let n=OVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Ycu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:crn(e.name),kind:ubh(e.kind),startTimeUnixNano:pYo(e.startTime),endTimeUnixNano:pYo(e.endTime),flags:lbh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=crn(e.traceState));let n=Lre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>pbh(s,t)));let i=OVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=OVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:obh[e.status.code],...e.status.message&&{message:crn(e.status.message)}}),r}function Xcu(e,t,r){return vWt(e,t,r)}function Zcu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:CWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var $cu=8;function lrn(){return orn()??Date.now()}function fYo(e){try{return e instanceof Kut}catch{return!1}}function elu(e,t){let r=Mcu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:rrn(t),traceFlags:r.flags,isRemote:!0}}function fbh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function dbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function urn(e,t,r){e[t]!==r&&(e[t]=r)}function mbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var DWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new wVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return jwe(r,this._contextManager.active());let n=ern(r?.parent);if(n&&typeof n!="string"&&!fYo(n)){if(fbh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),jwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),jwe(r,this._contextManager.active());let o=Date.now(),s=Gcu(r?.startTime,o,this._logger),a=Ncu();this._liveSpans.set(a,lrn());let c=this._autoContextAttributes();return new Kut({traceId:i?.traceId??Fcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:TVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:hhe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Hut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=BWt(this._contextManager,s,o);return Zau(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=elu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(fYo(t))return t.childContext();let n=this._contextManager.active();if(fYo(n))return n.childContext();if(n instanceof PWt)return elu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Kut))return;let{type:n,message:i,stack:o}=lYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=lrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!dbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=TVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Hut(u.startTime)??i.startTime,u.endTime=nrn(Hut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:TVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:OWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,Wcu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{urn(t,"traceId",r.traceId),urn(t,"spanId",r.spanId),urn(t,"parentSpanId",r.parentSpanId),urn(t,"traceState",r.traceState)}catch{return mbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Ycu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Jcu(Xcu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=lrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Zcu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=xWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=lrn()+this._nextFlushDelay()),this._headBatchFailures<$cu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${$cu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var RWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var hbh=5e3,gbh=512,Abh=2048,ybh=128,bbh=128,Ebh=128,Ibh=8192,vbh=1e4,Cbh=36e5;function zwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var tlu=["service.name","service.version","deployment.environment"];function xbh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(tlu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of tlu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Sbh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function dYo(e,t,r){let n=hhe({...t},xbh(e?.resourceAttributes)),i=zwe(e?.maxExportBatchSize,gbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Sbh(e?.beforeSpanSend,r),maxAttributesPerSpan:zwe(e?.maxAttributesPerSpan,ybh),maxEventsPerSpan:zwe(e?.maxEventsPerSpan,bbh),maxAttributesPerEvent:Ebh,maxAttributeValueLength:zwe(e?.maxAttributeValueLength,Ibh),flushIntervalMs:zwe(e?.flushIntervalMs,hbh),maxExportBatchSize:i,maxQueueSize:Math.max(zwe(e?.maxQueueSize,Abh),i),maxLiveSpans:zwe(e?.maxLiveSpans,vbh),maxSpanAgeMs:zwe(e?.maxSpanAgeMs,Cbh)}}var mYo=require("fs"),ilu=require("fs/promises"),gYo=require("path"),olu=require("readline"),prn=new LT.ReduceableCache(25),kWt=new LT.ReduceableCache(20),AYo=7,wbh=1e3,Tbh=1e4,hYo=10485760;async function slu(e,t=ilu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Rbh(l)||kbh(c)||!(0,gYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=alu(a,i);if(c===void 0||kWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=Nbh(l);if(u.every(d=>Fbh(c,d)))continue;let p=jbh(prn,c,{});s.push(Pbh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Bbh(e,prn,i),prn.reduce(),e}async function Obh(e,t,r){let n,i=!1;try{n=await t(e,mYo.constants.O_RDONLY|mYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>hYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${hYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Pbh(e,t,r,n,i,o){let s=await Obh(e,i,o);if(s===void 0)return void kWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:hYo-1})}catch{kWt.set(n,1),u();return}let d;try{d=(0,olu.createInterface)({input:p})}catch{kWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){kWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=zbh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Bbh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=alu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Dbh(n.lineno,n,o)}}function Dbh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=clu(e);i<e;i++){let o=r[i];if(o===void 0)return void rlu(t);t.pre_context.push(o)}if(r[e]===void 0)return void rlu(t);t.context_line=r[e];let n=llu(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 rlu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Rbh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function kbh(e){return e.lineno!==void 0&&e.lineno>Tbh||e.colno!==void 0&&e.colno>wbh}function alu(e,t){return(0,gYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Fbh(e,t){let r=prn.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 Nbh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=nlu(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+AYo:(i.push(n),n=nlu(o)),t++}return i}function nlu(e){return[clu(e),llu(e)]}function clu(e){return Math.max(1,e-AYo)}function llu(e){return e+AYo}function jbh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function zbh(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}var Jut=require("path");function ulu(e=process.cwd()){let t=Jut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Jut.isAbsolute)(o.filename)&&(o.filename=r((0,Jut.relative)(n,r(o.filename))));return i}}var plu="5.55.0";var Ahe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Qwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Ahe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Ahe.QUOTA_LIMITED),r===void 0&&o.push(Ahe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var Qbh=6e4;function flu(e){return e==="client"||e==="server"?e:"all"}function Mbh(e,t){return e===t||e==="all"||t==="all"}var Yut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Lbh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var _re=class e extends Error{constructor(t){super(t),Lbh(this,e)}},frn=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.pollerStopped=!1,this.filteredOutFlagKeys=new Set,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.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}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(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}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=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=ZJo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l 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 u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===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 Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,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}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`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){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await YJo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof _re)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await mlu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):dlu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await EWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return XJo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Xtn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?flu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Mbh(flu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!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(this.featureFlags),!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(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(Qbh,t*2**this.backOffCount):t}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);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 Yut(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Yut(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Yut(`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=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Yut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}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}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Nwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function dlu(e,t,r,n){return JJo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function _bh(e,t){if(!(e in t))throw new _re(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function mlu(e,t,r,n=!1,i,o){let s=String(e.value);_bh(s,r);let a=r[s];return hlu(a,t,r,n,i,o)}async function hlu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await hlu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await mlu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=dlu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var Ubh=["--unhandled-rejections","--unhandled_rejections"],Vbh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Gbh=[...globalThis.process?.execArgv??[]],qbh=globalThis.process?.env?.NODE_OPTIONS;function Wbh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function glu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Ubh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Vbh.has(o)&&(t=o)}return t}function Hbh(e=Gbh,t=qbh){return glu(e)??glu(Wbh(t??""))??"throw"}var Alu=Hbh();function ylu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Kbh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;ylu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function blu(e,t,r=Alu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>ylu(e,i,o));n.on("uncaughtException",Kbh(e,t))}}function Elu(e,t=Alu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Jbh=2e3,yYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Dtn({...Dau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return iWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(blu(this.onException.bind(this),this.onFatalError.bind(this)),Elu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),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._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Jbh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},PVe=yYo;var drn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Ybh(e){return e==="v0"||e==="v1"}function Ilu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Ybh(e)?e:"v0"}var Xbh="$ai_",FWt="analytics";function vlu(e){return typeof e.event=="string"&&e.event.startsWith(Xbh)}var Xut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function bYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Zbh(e){return typeof e=="string"?e:void 0}var $bh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Zbh}],eEh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function tEh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Clu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function nEh(e){let r={...tEh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of $bh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of eEh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Clu(r,"$set",e.$set),Clu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:rEh(e.timestamp),...i,options:n,properties:r}}function xlu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(nEh)};return r&&(n.historical_migration=!0),n}var iEh="/i/v1/analytics/events",oEh=3e4,sEh=new Set([408,500,502,503,504]),mrn=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??oEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??AWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=xlu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${iEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=kwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&sEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Xut({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Xut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Xut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var BVe="ai-capture",hrn="/i/v0/ai/batch/";var cEh=new TextEncoder;function IYo(e){return cEh.encode(kwe(e)).length}function Slu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=IYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var lEh=100,wlu=3e4,uEh=5e4,pEh=50,fEh=500,dEh="https://us.i.posthog.com",Tlu=new Set;function Arn(e,t){Tlu.has(e)||(Tlu.add(e),console.warn(`[PostHog] ${t}`))}function mEh(e){return typeof e=="string"?e.trim():""}function hEh(e){return(typeof e=="string"?e.trim():"")||void 0}function gEh(e){return(typeof e=="string"?e.trim():"")||dEh}function AEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function yEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var yrn=class extends yWt{constructor(t,r={}){let n=mEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:gEh(r.host),personalApiKey:hEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new drn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Ilu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,lEh):i.featureFlagsPollingInterval===null?null:wlu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new frn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new PVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||uEh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:aWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}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??fEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??pEh;this._waitUntilCycle.timer=$2(()=>{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 this._flushEventsAndSpans()}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)}getQueueRouteKey(t){return this.captureMode==="v1"&&vlu(t)?"ai":FWt}persistedQueueKeyForRoute(t){return t===BVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[FWt,"ai"]:[FWt];return this._aiCaptureRouteActive&&t.push(BVe),t}getBatchEndpointPath(t){return t===BVe?hrn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=FWt){if(n===BVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=Slu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${hrn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,BVe)}catch(n){if(!Wut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${IYo(o)} bytes) was rejected with 413 by ${hrn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new mrn({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return plu}get metrics(){return this._metrics||(this._metrics=new TWt(this,$tn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new RWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new DWt(this,dYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??jwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):BWt(this._spanContextManager,jwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","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._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,BVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=AEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=wlu){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){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof _re||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Ahe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Ahe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Ahe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Ahe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Arn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");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(Arn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),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.disabled)return void this._logger.warn("The client is disabled");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){Arn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!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:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new Qwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}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=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await Nwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Nwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!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=$2(()=>{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(Oau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");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 l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,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={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!PVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!PVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?hWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Arn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return yEh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Bau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.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)try{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)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Olu=require("async_hooks"),brn=class{constructor(){this.storage=new Olu.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 Plu=require("async_hooks"),Ern=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Plu.AsyncLocalStorage}};var Blu=require("zlib"),Dlu=require("util"),bEh=(0,Dlu.promisify)(Blu.gzip);async function Rlu(e,t=!0){try{let r=await bEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Irn=require("os");function klu(){let e,t;try{e=(0,Irn.platform)(),t=(0,Irn.release)()}catch{}return rYo(e,t)}var Flu="posthog-node";function EEh(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[vYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,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},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),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 vYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Flu,this.name=Flu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(EEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Ure=class extends yrn{getLibraryId(){return"posthog-node"}compressPayload(t){return Rlu(t,this.isDebug)}initializeContext(){return new brn}initializeSpanContextManager(){return new Ern}hostResourceAttributes(){return klu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[Cau(),t=>slu(t,void 0,this._logger),ulu()])}};function Nlu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var vrn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},IEh="feature_flag_evaluated",vEh=3e3,CEh=3e3,Crn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Ure(n??"",{featureFlagsRequestTimeoutMs:vEh,isServer:!1})}isEnabled(t,r){let n=jlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(jlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,CEh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=SEh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,CYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Nlu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=xEh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.228.1"};this.tryCapture({distinctId:CYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:CYo(r),event:IEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Nlu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function xEh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function CYo(e){return`org:${e}`}function SEh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function jlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var xrn;function Srn(){return xrn==null&&(xrn=wEh()),xrn}async function xYo(){await xrn?.flush()}function wEh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new vrn:new Crn({posthogApiKey:e,environment:gJ(),sendFeatureFlagEvents:Ttn()})}var wrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Ure(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.228.1",usingAccessToken:!0,cliReleaseEnvironment:gJ(),...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var NWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var Zut=require("fs/promises"),zlu=require("os"),Qlu=require("path");TUe();var TEh="id",OEh=".fern",jWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Ure(r,{isServer:!1}),this.userId=t==null?void 0:JJi(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:"5.228.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:gJ(),agent:Dpr(),...r!=null?{userEmail:r}:{},...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}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 Dl({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=Dw(),r=Re(Zt.of((0,zlu.homedir)()),be.of(OEh),be.of(TEh));try{await Ut(r)?this.persistedDistinctId=(await(0,Zut.readFile)(r)).toString():(await(0,Zut.mkdir)((0,Qlu.dirname)(r),{recursive:!0}),await(0,Zut.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var SYo;async function zWt(){return SYo==null&&(SYo=await PEh()),SYo}async function PEh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!Ttn())return new NWt;let t=await uZe();return t!=null?new jWt({token:t,posthogApiKey:e}):await jz()!=null?new wrn({posthogApiKey:e}):new jWt({token:void 0,posthogApiKey:e})}catch{return new NWt}}tn();mt();Bt();_Q();var QWt=Ae(require("process"),1);yKe();var _lu=Ae(s$i(),1),Ulu=Ae(Llu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=w7(e),e.length===0))return 0;e=e.replace((0,Ulu.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(_lu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function Trn(e){let t=0;for(let r of e.split(`
|
|
3499
3499
|
`))t=Math.max(t,_T(r));return t}var cuu=Ae(TYo(),1);var DEh=/[\p{Lu}]/u,REh=/[\p{Ll}]/u,qlu=/^[\p{Lu}](?![\p{Lu}])/gu,Klu=/([\p{Alpha}\p{N}_]|$)/u,OYo=/[_.\- ]+/,kEh=new RegExp("^"+OYo.source),Wlu=new RegExp(OYo.source+Klu.source,"gu"),Hlu=new RegExp("\\d+"+Klu.source,"gu"),FEh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let l=e[c];a=c>2?e[c-3]==="-":!0,i&&DEh.test(l)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&REh.test(l)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(l)===l&&r(l)!==l,s=o,o=r(l)===l&&t(l)!==l)}return e},NEh=(e,t)=>(qlu.lastIndex=0,e.replace(qlu,r=>t(r))),jEh=(e,t)=>(Wlu.lastIndex=0,Hlu.lastIndex=0,e.replace(Wlu,(r,n)=>t(n)).replace(Hlu,r=>t(r)));function PYo(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?OYo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=FEh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(kEh,""),e=t.preserveConsecutiveUppercase?NEh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),jEh(e,n))}var kYo=Ae(Ylu(),1);yKe();var Xlu=(e=0)=>t=>`\x1B[${t+e}m`,Zlu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,$lu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,e0={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]}},oAC=Object.keys(e0.modifier),LEh=Object.keys(e0.color),_Eh=Object.keys(e0.bgColor),sAC=[...LEh,..._Eh];function UEh(){let e=new Map;for(let[t,r]of Object.entries(e0)){for(let[n,i]of Object.entries(r))e0[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=e0[n],e.set(i[0],i[1]);Object.defineProperty(e0,t,{value:r,enumerable:!1})}return Object.defineProperty(e0,"codes",{value:e,enumerable:!1}),e0.color.close="\x1B[39m",e0.bgColor.close="\x1B[49m",e0.color.ansi=Xlu(),e0.color.ansi256=Zlu(),e0.color.ansi16m=$lu(),e0.bgColor.ansi=Xlu(10),e0.bgColor.ansi256=Zlu(10),e0.bgColor.ansi16m=$lu(10),Object.defineProperties(e0,{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=>e0.rgbToAnsi256(...e0.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)=>e0.ansi256ToAnsi(e0.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>e0.ansi256ToAnsi(e0.hexToAnsi256(t)),enumerable:!1}}),e0}var VEh=UEh(),euu=VEh;var Orn=new Set(["\x1B","\x9B"]),GEh=39,DYo="\x07",nuu="[",qEh="]",iuu="m",RYo=`${qEh}8;;`,tuu=e=>`${Orn.values().next().value}${nuu}${e}${iuu}`,ruu=e=>`${Orn.values().next().value}${RYo}${e}${DYo}`,WEh=e=>e.split(" ").map(t=>_T(t)),BYo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=_T(w7(e[e.length-1]));for(let[a,c]of n.entries()){let l=_T(c);if(s+l<=r?e[e.length-1]+=c:(e.push(c),s=0),Orn.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(RYo)),i){o?c===DYo&&(i=!1,o=!1):c===iuu&&(i=!1);continue}s+=l,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())},HEh=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(_T(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},KEh=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=WEh(e),a=[""];for(let[l,u]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=_T(a[a.length-1]);if(l!==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[l]>t){let d=t-p,f=1+Math.floor((s[l]-d-1)/t);Math.floor((s[l]-1)/t)<f&&a.push(""),BYo(a,u,t);continue}if(p+s[l]>t&&p>0&&s[l]>0){if(r.wordWrap===!1&&p<t){BYo(a,u,t);continue}a.push("")}if(p+s[l]>t&&r.wordWrap===!1){BYo(a,u,t);continue}a[a.length-1]+=u}r.trim!==!1&&(a=a.map(l=>HEh(l)));let c=[...a.join(`
|
|
3500
3500
|
`)];for(let[l,u]of c.entries()){if(n+=u,Orn.has(u)){let{groups:d}=new RegExp(`(?:\\${nuu}(?<code>\\d+)m|\\${RYo}(?<uri>.*)${DYo})`).exec(c.slice(l).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===GEh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=euu.codes.get(Number(i));c[l+1]===`
|
|
3501
3501
|
`?(o&&(n+=ruu("")),i&&p&&(n+=tuu(p))):u===`
|
|
@@ -4165,7 +4165,7 @@ ${ut.stack}`),ee&&m?.({event:"reload",ok:!1,durationMs:Date.now()-we,error:rn(ut
|
|
|
4165
4165
|
|
|
4166
4166
|
`),o.add(u),l.on("close",()=>o.delete(u));return}s.requestStarted(),u.once("close",()=>s.requestFinished());let d=sTp(l.url,i),f=M2s.default.request(d!=null?{host:"127.0.0.1",port:n,method:l.method,path:d,headers:l.headers}:{host:"127.0.0.1",port:t,method:l.method,path:l.url,headers:{...l.headers,[uTp]:r}},m=>{let g={...m.headers};if(!((g["content-type"]??"").includes("text/html")&&g["content-encoding"]==null)){u.writeHead(m.statusCode??502,g),m.pipe(u);return}let b=[];m.on("data",I=>b.push(I)),m.on("end",()=>{let I=Buffer.concat(b).toString("utf-8"),C=I.lastIndexOf("</body>"),x=C>=0?`${I.slice(0,C)}${cTp}${I.slice(C)}`:`${I}${cTp}`,S=Buffer.from(x,"utf-8");delete g["transfer-encoding"],g["content-length"]=S.byteLength.toString(),u.writeHead(m.statusCode??502,g),u.end(S)}),m.on("error",()=>u.destroy())});f.on("error",m=>{u.headersSent||u.writeHead(502,{"content-type":"text/plain"}),u.end(`Astro preview server unavailable: ${m.message}
|
|
4167
4167
|
`)}),l.pipe(f)})}function lnA({req:e,res:t,pathname:r,port:n,serverInfo:i,onShutdownRequest:o}){let s=(c,l,u={})=>{t.writeHead(c,{"content-type":"application/json","cache-control":"no-store",...u}),t.end(`${JSON.stringify(l)}
|
|
4168
|
-
`)},a=o_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[lSt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===aSt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function unA(){return new Promise((e,t)=>{let r=L2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function pnA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=L2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Bt();var mTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,fTp="docs.buildwithfern.com",dTp=62;function Fqe(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)),mTp.test(t)}function Wtr({orgId:e,previewId:t}){let r=MX(t),n=`${e}-preview-${r}.${fTp}`;if(n.length<=dTp)return n;let i=`${e}-preview-`,o=dTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${fTp}`}mt();h0();sm();tr();UE();Bt();tn();var hNs=require("child_process"),TOp=Ae(gTp(),1),gNs=Ae(OCi(),1),ANs=Ae(require("fs"),1),bNs=require("fs/promises"),OOp=Ae(require("http"),1),POp=Ae(require("os"),1),WCi=Ae(require("path"),1);uNs();h0();tr();var pNs=require("fs/promises");async function fNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,pNs.readFile)(ae,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async le=>{let ae=await A(le);return(0,pNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],xe=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await G3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=q3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=RO(ue);Pe=M3(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=g8e(n.config.root,g,t),S=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=y8e(x,S),P=b8e(S)??P,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&x!=null){let le=m8e(x,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=h8e(x,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:P,navbarLinks:D,settings:E8e(n.config.settings,S)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var RW=require("fs/promises"),IOp=require("os"),mNs=Ae(require("path"),1),QiA=".fern",MiA="logs",dNs=100*1024*1024;function LiA(){return"cli@5.228.
|
|
4168
|
+
`)},a=o_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[lSt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===aSt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function unA(){return new Promise((e,t)=>{let r=L2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function pnA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=L2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Bt();var mTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,fTp="docs.buildwithfern.com",dTp=62;function Fqe(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)),mTp.test(t)}function Wtr({orgId:e,previewId:t}){let r=MX(t),n=`${e}-preview-${r}.${fTp}`;if(n.length<=dTp)return n;let i=`${e}-preview-`,o=dTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${fTp}`}mt();h0();sm();tr();UE();Bt();tn();var hNs=require("child_process"),TOp=Ae(gTp(),1),gNs=Ae(OCi(),1),ANs=Ae(require("fs"),1),bNs=require("fs/promises"),OOp=Ae(require("http"),1),POp=Ae(require("os"),1),WCi=Ae(require("path"),1);uNs();h0();tr();var pNs=require("fs/promises");async function fNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,pNs.readFile)(ae,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async le=>{let ae=await A(le);return(0,pNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],xe=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await G3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=q3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=RO(ue);Pe=M3(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=g8e(n.config.root,g,t),S=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=y8e(x,S),P=b8e(S)??P,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&x!=null){let le=m8e(x,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=h8e(x,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:P,navbarLinks:D,settings:E8e(n.config.settings,S)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var RW=require("fs/promises"),IOp=require("os"),mNs=Ae(require("path"),1),QiA=".fern",MiA="logs",dNs=100*1024*1024;function LiA(){return"cli@5.228.1"}var Lqe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Re(Re(Zt.of((0,IOp.homedir)()),be.of(QiA)),be.of(MiA));await Ut(n)||await(0,RW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,be.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${mNs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
4169
4169
|
`);await(0,RW.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)+`
|
|
4170
4170
|
`;try{await(0,RW.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:LiA(),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,RW.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let l=mNs.default.join(t,c);try{let u=await(0,RW.stat)(l);i.push({name:c,fullPath:l,size:u.size,mtimeMs:u.mtimeMs})}catch{}}let o=i.reduce((c,l)=>c+l.size,0),s=Math.round(o/1024/1024*100)/100,a=dNs/1024/1024;if(o<=dNs){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,l)=>c.mtimeMs-l.mtimeMs);for(let c of i){if(o<=dNs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,RW.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 qCi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function vOp(e){let t=_iA();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(l){let u=JSON.stringify(l),p=[];for(let[d]of s)try{d.send(u)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(l,u){if(l.method==="OPTIONS")return new Response(null,{status:204,headers:qCi});let p=new URL(l.url);if(l.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(l,{data:{connectionId:`${Date.now()}`}});return}if(l.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await l.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...qCi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...qCi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return l.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:qCi}):new Response("Not Found",{status:404})},websocket:{open(l){let{connectionId:u}=l.data,p=setInterval(()=>{let d=s.get(l);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){l.close();return}try{l.send(JSON.stringify({type:"ping",timestamp:f}))}catch{l.close()}},3e4);s.set(l,{pingInterval:p,lastPong:Date.now()});try{l.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(l,u){try{let p=JSON.parse(u.toString());if(p.type==="pong"){let d=s.get(l);d&&(d.lastPong=Date.now())}else Lqe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(l){let u=s.get(l);u&&(clearInterval(u.pingInterval),s.delete(l))}}});return{sendData:a,stop:l=>c.stop(l)}}function _iA(){return globalThis.Bun}var COp=require("fs"),xOp=Ae(require("path"),1),UiA=`"use strict";
|
|
4171
4171
|
|
|
@@ -4503,7 +4503,7 @@ ${A}
|
|
|
4503
4503
|
|
|
4504
4504
|
Add a 'docs:' section to your fern.yml to get started.`,code:T.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new T({message:`No libraries configured in docs.yml.
|
|
4505
4505
|
|
|
4506
|
-
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await cir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function v4s(e){let t=new I4s;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function C4s(e){bA({cli:e,name:"md",subcommands:[v4s,G3s]})}Bt();function fPi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},ein(n)),s.version(!1).usage(r)})}mt();h0();Bt();tn();mt();Bt();var dPi=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 Cd({context:this.context,task:this.task});try{let s=await Itr({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:"5.228.
|
|
4506
|
+
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await cir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function v4s(e){let t=new I4s;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function C4s(e){bA({cli:e,name:"md",subcommands:[v4s,G3s]})}Bt();function fPi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},ein(n)),s.version(!1).usage(r)})}mt();h0();Bt();tn();mt();Bt();var dPi=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 Cd({context:this.context,task:this.task});try{let s=await Itr({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:"5.228.1",loginCommand:"fern auth login"});return o.getResult()===gf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:rn(s)}}}};mt();tn();var aBt=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(`
|
|
4507
4507
|
`),this.stream.write(`${oe.cyan("\u25C6")} ${oe.bold(t.title)}
|
|
4508
4508
|
`),t.subtitle!=null&&this.stream.write(` ${oe.dim(t.subtitle)}
|
|
4509
4509
|
`),this.stream.write(`
|
|
@@ -5595,7 +5595,7 @@ ${t}`),n}catch{return}}function rdy(e){let t=e.split(`
|
|
|
5595
5595
|
`),g="";return c&&(g=u.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
|
|
5596
5596
|
`)]});var Fmy=cx((e,t)=>{let{validate:r=()=>!0}=e,n=jI(e.theme),[i,o]=cl("idle"),[s,a]=cl(),[c,l]=cl(""),u=sx({status:i,theme:n});ax(async(g,A)=>{if(i==="idle")if(ox(g)){let b=c;o("loading");let I=await r(b);I===!0?(l(b),o("done"),t(b)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else l(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${RDt}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[u,p,e.mask?d:f].join(" "),m]});var aHe=Ae(Rw(),1);var Nmy={icon:{cursor:Xx.pointer},style:{disabled:e=>aHe.default.dim(`- ${e}`),searchTerm:e=>aHe.default.cyan(e),description:e=>aHe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${aHe.default.bold(t)} ${aHe.default.dim(r)}`).join(aHe.default.dim(" \u2022 "))},helpMode:"always"};function vta(e){return!Bd.isSeparator(e)&&!e.disabled}function jmy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var zmy=cx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=jI(Nmy,e.theme),[o,s]=cl("loading"),[a,c]=cl(""),[l,u]=cl([]),[p,d]=cl(),f=sx({status:o,theme:i}),m=T6(()=>{let j=l.findIndex(vta),Y=l.findLastIndex(vta);return{first:j,last:Y}},[l]),[g=m.first,A]=cl();K4(()=>{let j=new AbortController;return s("loading"),d(void 0),(async()=>{try{let ee=await e.source(a||void 0,{signal:j.signal});j.signal.aborted||(A(void 0),d(void 0),u(jmy(ee)),s("idle"))}catch(ee){!j.signal.aborted&&ee instanceof Error&&d(ee.message)}})(),()=>{j.abort()}},[a]);let b=l[g];ax(async(j,Y)=>{if(ox(j))if(b){s("loading");let ee=await n(b.value);s("idle"),ee===!0?(s("done"),t(b.value)):b.name===a?d(ee||"You must provide a valid value"):(Y.write(b.name),c(b.name))}else Y.write(a);else if(hbe(j)&&b)Y.clearLine(0),Y.write(b.name),c(b.name);else if(o!=="loading"&&(uD(j)||w6(j))){if(Y.clearLine(0),uD(j)&&g!==m.first||w6(j)&&g!==m.last){let ee=uD(j)?-1:1,te=g;do te=(te+ee+l.length)%l.length;while(!vta(l[te]));A(te)}}else c(Y.line)});let I=i.style.message(e.message,o),C;if(i.helpMode!=="never")if(e.instructions){let{pager:j,navigation:Y}=e.instructions;C=i.style.help(l.length>r?j:Y)}else C=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=nHe({items:l,active:g,renderItem({item:j,isActive:Y}){if(Bd.isSeparator(j))return` ${j.separator}`;if(j.disabled){let ce=typeof j.disabled=="string"?j.disabled:"(disabled)";return i.style.disabled(`${j.name} ${ce}`)}let ee=Y?i.style.highlight:ce=>ce,te=Y?i.icon.cursor:" ";return ee(`${te} ${j.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):l.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let P;if(o==="done"&&b)return[f,I,i.style.answer(b.short)].filter(Boolean).join(" ").trimEnd();P=i.style.searchTerm(a);let D=b?.description,R=[f,I,P].filter(Boolean).join(" ").trimEnd(),O=[S??x," ",D?i.style.description(D):"",C].filter(Boolean).join(`
|
|
5597
5597
|
`).trimEnd();return[R,O]});var FDt=Ae(Rw(),1);var Qmy={icon:{cursor:Xx.pointer},style:{disabled:e=>FDt.default.dim(`- ${e}`),description:e=>FDt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${FDt.default.bold(t)} ${FDt.default.dim(r)}`).join(FDt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function kDt(e){return!Bd.isSeparator(e)&&!e.disabled}function Mmy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var Cta=cx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=jI(Qmy,e.theme),{keybindings:o}=i,[s,a]=cl("idle"),c=sx({status:s,theme:i}),l=rHe(),u=!o.includes("vim"),p=T6(()=>Mmy(e.choices),[e.choices]),d=T6(()=>{let D=p.findIndex(kDt),R=p.findLastIndex(kDt);if(D===-1)throw new fue("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:R}},[p]),f=T6(()=>"default"in e?p.findIndex(D=>kDt(D)&&D.value===e.default):-1,[e.default,p]),[m,g]=cl(f===-1?d.first:f),A=p[m];ax((D,R)=>{if(clearTimeout(l.current),ox(D))a("done"),t(A.value);else if(uD(D,o)||w6(D,o)){if(R.clearLine(0),r||uD(D,o)&&m!==d.first||w6(D,o)&&m!==d.last){let O=uD(D,o)?-1:1,j=m;do j=(j+O+p.length)%p.length;while(!kDt(p[j]));g(j)}}else if(msr(D)&&!Number.isNaN(Number(R.line))){let O=Number(R.line)-1,j=-1,Y=p.findIndex(te=>Bd.isSeparator(te)?!1:(j++,j===O)),ee=p[Y];ee!=null&&kDt(ee)&&g(Y),l.current=setTimeout(()=>{R.clearLine(0)},700)}else if($7e(D))R.clearLine(0);else if(u){let O=R.line.toLowerCase(),j=p.findIndex(Y=>Bd.isSeparator(Y)||!kDt(Y)?!1:Y.name.toLowerCase().startsWith(O));j!==-1&&g(j),l.current=setTimeout(()=>{R.clearLine(0)},700)}}),K4(()=>()=>{clearTimeout(l.current)},[]);let b=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:R}=e.instructions;I=i.style.help(p.length>n?D:R)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let C=0,x=nHe({items:p,active:m,renderItem({item:D,isActive:R,index:O}){if(Bd.isSeparator(D))return C++,` ${D.separator}`;let j=i.indexMode==="number"?`${O+1-C}. `:"";if(D.disabled){let te=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${j}${D.name} ${te}`)}let Y=R?i.style.highlight:te=>te,ee=R?i.icon.cursor:" ";return Y(`${ee} ${j}${D.name}`)},pageSize:n,loop:r});if(s==="done")return[c,b,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,b].filter(Boolean).join(" "),x," ",S?i.style.description(S):"",I].filter(Boolean).join(`
|
|
5598
|
-
`).trimEnd()}${RDt}`});tn();xo();var due={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Lmy={[due.GENERATION_STARTED]:!1,[due.GENERATION_COMPLETED]:!1,[due.GENERATION_FAILED]:!0,[due.VERIFICATION_FAILED]:!0,[due.SDK_PR_CREATED]:!1,[due.UPGRADE_APPLIED]:!1,[due.MAJOR_VERSION_BUMP]:!1};function i$p(e){return Lmy[e]}function o$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function s$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function a$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function c$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function l$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?due.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?due.VERIFICATION_FAILED:due.GENERATION_FAILED}var _my="",Umy="FERN_AUTOMATION_EVENTS_ORIGIN",Vmy=3e3,eFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[Umy]??_my)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Vmy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(c$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function u$p(){let{fern_run_id:e,github_run_id:t}=Rfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.228.
|
|
5598
|
+
`).trimEnd()}${RDt}`});tn();xo();var due={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Lmy={[due.GENERATION_STARTED]:!1,[due.GENERATION_COMPLETED]:!1,[due.GENERATION_FAILED]:!0,[due.VERIFICATION_FAILED]:!0,[due.SDK_PR_CREATED]:!1,[due.UPGRADE_APPLIED]:!1,[due.MAJOR_VERSION_BUMP]:!1};function i$p(e){return Lmy[e]}function o$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function s$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function a$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function c$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function l$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?due.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?due.VERIFICATION_FAILED:due.GENERATION_FAILED}var _my="",Umy="FERN_AUTOMATION_EVENTS_ORIGIN",Vmy=3e3,eFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[Umy]??_my)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Vmy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(c$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function u$p(){let{fern_run_id:e,github_run_id:t}=Rfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.228.1"}}function p$p(){return process.env.FERN_AUTOMATION==="true"}var Gmy=3e3,tFi=class{constructor(t,r=eFi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=u$p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,Gmy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:o$p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!i$p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:s$p(t,r),context:{automation:a$p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Bt();function rFi(e,t,r){if(t instanceof rc)return;let n=Cfe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});p$p()?Wmy(i,e,n,s,a):qmy(e,o,n,a)}function qmy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),NLe(r)&&e.captureException(n,{tags:{"error.code":r}})}function Wmy(e,t,r,n,i){let o=l$p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Bt();function cHe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function nFi({cliName:e,packageVersion:t,isLocal:r}){return cHe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var iFi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(nFi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=l_t({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[U$e(),hve(),gve(),$Ie(),mve()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),u_t()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):GP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Bt();var oFi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};dee();mt();Iy();Bt();tn();var ysr=class{result=gf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new rc(t??(r instanceof rc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=gf.Failure,!(r instanceof rc)&&(t!=null&&(this.lastFailureMessage=t),$Le({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),rFi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=L0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new xta({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${oe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===gf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
|
|
5599
5599
|
`)}},xta=class extends ysr{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Un.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===gf.Success?this.logAtLevelWithOverrides(Un.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Un.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(oe.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Hj({prefix:this.getIcon({spinner:t}),content:r.join(`
|
|
5600
5600
|
`)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?oe.dim("\u25B8 "):oe.dim("\u25E6 ");case"running":return r?oe.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case gf.Success:return r?oe.green("\u25BE "):oe.green("\u2713 ");case gf.Failure:return r?oe.red("\u25BE "):oe.red("x ")}}}getResult(){if(this.result===gf.Failure)return gf.Failure;for(let t of this.subtasks)if(t.getResult()===gf.Failure)return gf.Failure;return gf.Success}};Bt();var f$p=Ae(lLe(),1);tn();function d$p(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function Hmy(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||d$p(e.generatorUpgradeInfo)}async function m$p({cliEnvironment:e,upgradeInfo:t}){if(!Hmy(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${oe.underline("Upgrades available")}
|
|
5601
5601
|
|
|
@@ -5604,7 +5604,7 @@ ${t}`),n}catch{return}}function rdy(e){let t=e.split(`
|
|
|
5604
5604
|
Run ${oe.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
5605
5605
|
Run ${oe.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Lwe(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Sta({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!d$p(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+=`
|
|
5606
5606
|
${await Kmy(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+oe.dim(a.currentVersion)+oe.reset(" \u2192 ")+oe.green(a.latestVersion);return i+=`
|
|
5607
|
-
`,n?Lwe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Kmy(e){let r=await new f$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}qn();Dme();Bt();var bsr=Ae(QA(),1);function NDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function sFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!h$p(t)||!h$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=bsr.default.valid(t),i=bsr.default.valid(r);if(n!=null&&i!=null)return Math.sign(bsr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function h$p(e){if(e==="latest"||bsr.default.valid(e)!=null)return!0;try{return GK(e),!0}catch{return!1}}async function aFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${ser} feature flag is off for this organization.`);let a=Tae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await YIs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function Jmy({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await vy().catch(()=>{})!=null?NDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await g$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=j4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await y$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await g$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=j4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await y$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function g$p({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 Z_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?nh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function A$p(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=sFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;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 y$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Ymy({organization:s,generatorName:nh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await aFi({generatorId:nh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:AB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function cFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await Jmy({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...A$p(u,l,t.logger));else a.push(...A$p(c.versions,void 0,t.logger))}return a}async function Ymy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ROs({organization:e,generatorName:t})??!1:$wt({organization:e,generatorName:t})}mt();Bt();pUt();async function J4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Wde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Wn(r)}`,code:T.Code.NetworkError})}}var b$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],lFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new oFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await zWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new OMt(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 iFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new tFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.228.
|
|
5607
|
+
`,n?Lwe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Kmy(e){let r=await new f$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}qn();Dme();Bt();var bsr=Ae(QA(),1);function NDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function sFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!h$p(t)||!h$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=bsr.default.valid(t),i=bsr.default.valid(r);if(n!=null&&i!=null)return Math.sign(bsr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function h$p(e){if(e==="latest"||bsr.default.valid(e)!=null)return!0;try{return GK(e),!0}catch{return!1}}async function aFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${ser} feature flag is off for this organization.`);let a=Tae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await YIs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function Jmy({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await vy().catch(()=>{})!=null?NDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await g$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=j4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await y$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await g$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=j4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await y$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function g$p({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 Z_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?nh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function A$p(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=sFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;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 y$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Ymy({organization:s,generatorName:nh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await aFi({generatorId:nh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:AB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function cFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await Jmy({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...A$p(u,l,t.logger));else a.push(...A$p(c.versions,void 0,t.logger))}return a}async function Ymy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ROs({organization:e,generatorName:t})??!1:$wt({organization:e,generatorName:t})}mt();Bt();pUt();async function J4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Wde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Wn(r)}`,code:T.Code.NetworkError})}}var b$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],lFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new oFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await zWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new OMt(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 iFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new tFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.228.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${oe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new rc(t??(r instanceof rc?r.failureMessage:r!=null?rn(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof rc)&&($Le({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),rFi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
|
|
5608
5608
|
`)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async withRealStdout(t){this.stdoutRedirector.restore();try{return await t()}finally{this.jsonMode&&this.stdoutRedirector.redirect()}}logAfterTasks(t){this.isTTY?this.linesAfterTasks.push(t):this.logger.info(t)}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();for(let r of this.linesAfterTasks)process.stdout.write(`${r}
|
|
5609
5609
|
`);try{await Promise.all([this.posthogManager.flush(),xYo()])}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable({skipFeatureFlagRequest:!0}),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await m$p({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
5610
5610
|
`)||(r+=`
|