fern-api 4.31.0 → 4.31.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.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1493,7 +1493,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1493
1493
  Location: ${i.join("-> ")}`),Fr.unknown({nameOverride:p,generatedName:m,title:h,description:g,availability:A,namespace:a,groupName:f,example:void 0})}}function _Qc(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 rne(e){if(e.$ref.startsWith(f_e))return e.$ref.replace(f_e,"")}function rKn(e,t,r,n,i){let o=Vr(e,bn.TYPE_NAME),s=py(t,n),a=e.description,u=AS(e),c=rne(e);if(c==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return aa.reference({generatedName:s,nameOverride:o,title:void 0,schema:c,description:a??void 0,availability:u,namespace:i.getNamespace(c),groupName:void 0,source:r})}function SQc(e){return e.oneOf==null||e.oneOf.length===0}function OJo(e){return e.allOf==null||e.allOf.length===0}function fJt(e){return e.properties==null||Wd(e.properties)===0}function mJt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function eG(e,t,r,n){if(e.type==="reference")return Fr.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n});if(e.type==="optional"){let i=eG(e.value,t,r,n);return Fr.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=eG(e.value,t,r,n);return Fr.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 Fr.primitive({...e,description:t});return e}function dJt(e){return ei(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>dJt(t)):e.oneOf!=null?e.oneOf.every(t=>dJt(t)):e.anyOf!=null?e.anyOf.every(t=>dJt(t)):!1}function PJo({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,nameOverride:a,generatedName:u,title:c}){let l=Fr.literal({nameOverride:a,generatedName:u,title:c,value:e,namespace:n,groupName:i,description:o,availability:s});return r&&(l=Fr.nullable({nameOverride:a,generatedName:u,title:c,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(l=Fr.optional({nameOverride:a,generatedName:u,title:c,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),l}function qw({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,generatedName:a,nameOverride:u,title:c}){i=typeof i=="string"?[i]:i;let l=Fr.primitive({nameOverride:u,generatedName:a,title:c,schema:e,description:o,availability:s,namespace:n,groupName:i});return r&&(l=Fr.nullable({nameOverride:u,generatedName:a,title:c,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(l=Fr.optional({nameOverride:u,generatedName:a,title:c,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),l}function BQc({schemas:e}){let t=new Set;for(let r of e){if(ei(r))return;if(r.enum!=null&&mJt(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function TJo({schemas:e,context:t}){let r={};for(let n of e){let i=FJo({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)return{discriminant:n,schemas:i}}function FJo({schema:e,context:t}){let r=ei(e)?t.resolveSchemaReference(e):e;return OQc({schema:r,context:t})}function OQc({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=FJo({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=ei(i)?t.resolveSchemaReference(i):i;o.type==="string"&&o.enum!=null&&mJt(o.enum)&&PQc(o.enum).length===1&&o.enum[0]!=null&&(r[n]=o.enum[0]);let s=kJo(o,"const");o.type==="string"&&s!=null&&(r[n]=s),n==="type"&&o.example!=null&&(r[n]=o.example)}return r}function PQc(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 kJo(e,t){let r=e[t];if(r!=null)return r}function TQc({schema:e,logger:t}){let r=pJo({schema:e,logger:t});if(r!=null)return bJo(r)}var bUe=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(f_e))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let n=t.$ref.substring(f_e.length).split("/"),i=this.document.components;if(i==null||i.schemas==null)throw new Error("Document does not have components.schemas.");let[o,s,a]=n;if(o==null||o==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let u=i.schemas[o];if(u==null)throw new Error(`Schema "${o}" is undefined in document.components.schemas.`);if(ei(u)&&(u=this.resolveSchemaReference(u)),s==="properties"&&a!=null){let c=u.properties?.[a];if(c==null)throw new Error(`Property "${a}" not found on "${o}". Full ref: ${t.$ref}`);ei(c)?u=this.resolveSchemaReference(c):u=c}return u}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 gJt=class extends bUe{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 Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let i=t.$ref.substring(r.length),o=n.messages[i];if(o==null)throw new Error(`${t.$ref} is undefined`);return o}};Qt();function EUe(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let n={};for(let[i,o]of Object.entries(t))switch(o.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(o.namespace==null){r[i]=o;continue}let s=o.namespace;n[s]??={},n[s][i]=o;continue}case"oneOf":case"unknown":r[i]=o;continue;default:xe(o)}return{rootSchemas:r,namespacedSchemas:n}}Qt();var vUe=_e(require("fs"),1),d_e=_e(require("path"),1);Qt();function ype(e){if(typeof e=="string")return Ha.primitive(as.string(e));if(typeof e=="number")return Number.isInteger(e)?Ha.primitive(as.int(e)):Ha.primitive(as.double(e));if(typeof e=="boolean")return Ha.primitive(as.boolean(e));if(Array.isArray(e)){let t=e.map(r=>ype(r));return t.length===0?void 0:Ha.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=ype(n);i!=null&&t.push({key:as.string(r),value:i})}return Ha.map(t)}}function zmt(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function QJo(e){if(e!=null&&Array.isArray(e))return e}var bpe=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"&&NJo({schema:n,value:r}))return Ha.enum(r);if(r!=null){let u=n.values.map(l=>l.value),c=e.truncateExample(r);this.context.logger.warn(`Example value ${c} is not a valid enum value${s.name!=null?` for '${s.name}'`:""}. Allowed values: [${u.join(", ")}]. Using fallback value instead.`)}return n.values[0]!=null?Ha.enum(n.values[0]?.value):void 0;case"literal":return Ha.literal(n.value);case"nullable":{if(r===null)return Ha.null({});if(r==null&&!this.hasExample(n.value,0,o,s)&&this.exceedsMaxDepth(i,s))return Ha.null({});let u=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return u??Ha.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 u=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return u!=null&&u.type==="array"&&u.value.length===0||u!=null&&u.type==="map"&&u.value.length===0||u!=null&&u.type==="object"&&Object.keys(u.properties).length===0?void 0:u}case"primitive":{let u=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:s});return Ha.primitive(u)}case"reference":{let u=this.schemas[n.schema];if(u!=null&&!o.has(n.schema)){o.add(n.schema);let c=u?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),l=this.buildExampleHelper({example:r,schema:u,exampleId:t,visitedSchemaIds:o,depth:i,options:s,skipReadonly:c||this.context.options.respectReadonlySchemas?a:!1});return o.delete(n.schema),l}return}case"oneOf":switch(n.value.type){case"discriminated":{let u={},c={},l={},p=zmt(r),d=p?.[n.value.discriminantProperty],f=n.value.schemas[d],m=[],h=this.getDiscriminatedUnionVariantSchema(n.value,p);h!=null&&m.push(h),m.push(...Object.entries(n.value.schemas));for(let g of m)if(d!=null&&f!=null&&f.type==="object"){c=this.getAllProperties(f),l=this.getAllRequiredProperties(f),u[n.value.discriminantProperty]=Ha.primitive(as.string(d));break}else{let A=this.buildExampleHelper({exampleId:t,schema:g[1],example:void 0,visitedSchemaIds:o,depth:i,options:s,skipReadonly:a});if(A!=null){this.mergeExampleWith(A,u),u[n.value.discriminantProperty]=Ha.primitive(as.string(g[0]));break}}for(let g of n.value.commonProperties){c[g.key]={schema:g.schema,readonly:!1};let A=this.getResolvedSchema(g.schema);A.type!=="optional"&&A.type!=="nullable"&&(l[g.key]=g.schema)}for(let[g,A]of Object.entries(c)){let E=g in l;if(E&&p?.[g]!=null){let v=this.buildExampleHelper({schema:A.schema,exampleId:t,example:p[g],visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});if(v!=null)u[g]=v;else return}else{let v=this.buildExampleHelper({exampleId:t,schema:A.schema,example:p?.[g],visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});if(v!=null)u[g]=v;else if(E)return}}return Ha.oneOf(epe.discriminated(u))}case"undiscriminated":{let u=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(u!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:u,visitedSchemaIds:o,depth:i,options:s,skipReadonly:a});break}}return;case"unknown":if(r!=null){let u=ype(r);if(u!=null)return Ha.unknown(u)}return s.ignoreOptionals||this.exceedsMaxDepth(i,s)?void 0:s.isParameter?Ha.primitive(as.string(s.name??"string")):Ha.map([{key:as.string("key"),value:Ha.primitive(as.string("value"))}]);case"array":{let u=QJo(r),c=[];if(u!=null&&u.length>0)for(let l of u){let p=this.buildExampleHelper({exampleId:t,example:l,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});p!=null&&c.push(p)}else if(n.example!=null&&n.example.length>0)for(let l of n.example){let p=this.buildExampleHelper({exampleId:t,example:l,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});p!=null&&c.push(p)}else{let l=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});l!=null&&c.push(l)}return Ha.array(c)}case"map":{let u=zmt(r??n.example);if(u!=null&&Object.entries(u).length>0){let p=[];for(let[d,f]of Object.entries(u)){let m=this.buildExampleFromPrimitive({schema:n.key.schema,example:d,options:s}),h=this.buildExampleHelper({exampleId:t,example:f,schema:n.value,visitedSchemaIds:o,depth:i+1,options:s,skipReadonly:a});h!=null&&p.push({key:m,value:h})}return Ha.map(p)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return Ha.map([{key:as.string("key"),value:Ha.unknown(Ha.primitive(as.string("value")))}]);let c=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...s,name:"key"}}),l=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:o,depth:i+1,options:{...s,name:"value"},skipReadonly:a});return l!=null&&l.type!=="null"?Ha.map([{key:c,value:l}]):Ha.map([])}case"object":{let u={},c=n.fullExamples?.find(f=>f.name===t)??n.fullExamples?.find(f=>f.name==null)??n.fullExamples?.[0],l=zmt(r)??(c!=null?zmt(c.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:I=>typeof I.availability=="string"&&I.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 h=f in d,g=Object.keys(l).includes(f),A=l[f],E=this.getSchemaExample(m.schema),v=g?A:E,b=this.buildExampleHelper({schema:m.schema,exampleId:t,example:v,visitedSchemaIds:o,depth:i+1,options:{...s,name:f},skipReadonly:a});if(h&&b!=null)u[f]=b;else{if(h)return;(g&&b!=null||!s.ignoreOptionals&&b!=null)&&(u[f]=b)}}if(n.additionalProperties){for(let[f,m]of Object.entries(l))if(!(f in u)){let h=this.buildExampleHelper({schema:Fr.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});h!=null&&(u[f]=h)}}return Ha.object({properties:u})}default:xe(n)}}mergeExampleWith(t,r){t._visit({array:ft,enum:ft,literal:ft,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:ft,unknown:ft,null:ft,_other:ft})}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 NJo({schema:t,value:r})?5:0;case"object":{if(!ba(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(!ba(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){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(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 Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);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"?as.string(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string",schemaType:r.type,options:n}),as.string(r.example??n.name??Ai.STRING));case"base64":return t!=null&&typeof t=="string"?as.base64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (base64)",schemaType:r.type,options:n}),as.base64(r.example??Ai.BASE64));case"boolean":return t!=null&&typeof t=="boolean"?as.boolean(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"boolean",schemaType:r.type,options:n}),as.boolean(r.example??Ai.BOOLEAN));case"date":return t!=null&&typeof t=="string"?as.date(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (date)",schemaType:r.type,options:n}),as.date(r.example??Ai.DATE));case"datetime":return t!=null&&typeof t=="string"?as.datetime(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime)",schemaType:r.type,options:n}),as.datetime(r.example??Ai.DATE_TIME));case"datetimeRfc2822":return t!=null&&typeof t=="string"?as.datetimeRfc2822(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime RFC 2822)",schemaType:r.type,options:n}),as.datetimeRfc2822(r.example??Ai.DATE_TIME_RFC_2822));case"double":return t!=null&&typeof t=="number"?as.double(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (double)",schemaType:r.type,options:n}),as.double(r.example??Ai.DOUBLE));case"float":return t!=null&&typeof t=="number"?as.float(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (float)",schemaType:r.type,options:n}),as.float(r.example??Ai.FLOAT));case"int":return t!=null&&typeof t=="number"?as.int(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int)",schemaType:r.type,options:n}),as.int(r.example??Ai.INT));case"int64":return t!=null&&typeof t=="number"?as.int64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int64)",schemaType:r.type,options:n}),as.int64(r.example??Ai.INT64));case"uint":return t!=null&&typeof t=="number"?as.uint(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint)",schemaType:r.type,options:n}),as.uint(r.example??Ai.UINT));case"uint64":return t!=null&&typeof t=="number"?as.uint64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint64)",schemaType:r.type,options:n}),as.uint64(r.example??Ai.UINT64));default:xe(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.warn(`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 NJo({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}Qt();function e8(e){switch(e.type){case"object":return Fr.object({allOf:e.allOf,properties:e.properties.map(t=>RQc(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});case"array":return Fr.array({description:e.description,availability:e.availability,value:e8(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});case"enum":return Fr.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 Fr.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 Fr.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:e8(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Fr.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:e8(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Fr.primitive({description:e.description,availability:e.availability,schema:jJo(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Fr.map({description:e.description,availability:e.availability,key:Fr.primitive({description:e.key.description,availability:e.key.availability,schema:jJo(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:e8(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 Fr.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 Fr.oneOf(DQc(e.value));case"unknown":return Fr.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:xe(e)}}function DQc(e){switch(e.type){case"discriminated":return Z2.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:e8(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,discriminantPropertyNameOverride:e.discriminantPropertyNameOverride,discriminatorContext:e.discriminatorContext,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,e8(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return Z2.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>e8(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:xe(e)}}function jJo(e){switch(e.type){case"string":return Ii.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Ii.base64({example:void 0});case"boolean":return Ii.boolean({default:e.default,example:void 0});case"date":return Ii.date({example:void 0});case"datetime":return Ii.datetime({example:void 0});case"datetimeRfc2822":return Ii.datetimeRfc2822({example:void 0});case"double":return Ii.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 Ii.float({example:void 0});case"int":return Ii.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 Ii.int64({default:e.default,example:void 0});case"uint":return Ii.uint({default:void 0,example:void 0});case"uint64":return Ii.uint64({default:void 0,example:void 0});default:xe(e)}}function RQc(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:e8(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function AJt(e){return e.type!=="optional"&&e.type!=="nullable"}function iKn(e){return e==="POST"||e==="PUT"||e==="PATCH"}function Vmt(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 yJt=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 bpe(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=d_e.dirname(o),a=s;for(;a!==d_e.dirname(a);){let u=d_e.join(a,"fern");if(vUe.existsSync(u)&&vUe.statSync(u).isDirectory()){t=u;break}a=d_e.dirname(a)}t||(t=s)}else t=process.cwd();let r=t??process.cwd(),n=d_e.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 u=JSON.stringify(o.autoGeneratedExample,null,4).split(`
1494
1494
  `).map(c=>` ${c}`).join(`
1495
1495
  `);s.push(u)}return s.push(""),s}),""].join(`
1496
- `);try{vUe.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=kQc(t.request),n=QQc(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:iKn(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:iKn(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,tM.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,tM.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,tM.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,tM.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&&!t8(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&&!t8(f)&&(this.logger.debug(`Expected a primitive 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 u=[];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&&!t8(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&&u.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?e8(p.schema):Fr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Ii.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&&!t8(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&&u.push({name:p.header,value:f})}let c=[];t.request!=null&&t.response!=null?c=FQc(i,o):t.request!=null?c=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(c=o.map(([p,d])=>({id:p,request:void 0,response:d})));let l=t.examples.filter(p=>Vmt(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=>ma(p));return c.length===0?[eM.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:u,request:void 0,response:void 0,codeSamples:l})]:c.map(({id:p,request:d,response:f})=>eM.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:u,request:d,response:f,codeSamples:l}))}convertCodeSamples(t){return t.map(r=>"language"in r?q9.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):q9.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?Lw.Csharp:r.sdk,code:r.code})).filter(ma)}isSchemaRequired(t){return AJt(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function FQc(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(([u])=>u==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 u=0;u<t.length;u++){let[c,l]=t[u];c==null||n.has(u)||i===c&&(r.push({id:i,request:o,response:l}),c!=null&&n.add(u),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(([u])=>u==null)?.[1]??e[0]?.[1];a!=null&&r.push({id:o,request:a,response:s})}return r}function kQc(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:NQc(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function QQc(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 t8(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return t8(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return t8(e.value.value);default:return!1}case"null":return!0;default:xe(e)}}function NQc(e){return Fr.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:e8(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(ma),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})}var IUe=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new bpe(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 u=[];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&&!t8(f)&&(f=void 0),!(d&&f==null)&&f!=null&&u.push({name:p.name,value:f})}let c=[];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&&!t8(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let l=[];for(let p of a.messages){let d=t.getExampleMessageReference(p),f=t.resolveMessageReference({$ref:d}),m=ei(f.payload)?t.resolveSchemaReference(f.payload):f.payload,h=this.exampleTypeFactory.buildExample({schema:Va(m,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});h!=null&&l.push({messageType:p.type,payload:h,description:void 0})}s.push({name:a.summary,queryParameters:u,headers:c,description:a.description,messages:l})}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),u=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(u!=null&&!t8(u)&&(u=void 0),a&&u==null)return;u!=null&&i.push({name:s.name,value:u})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),u=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(u!=null&&!t8(u)&&(u=void 0),a&&u==null)return;u!=null&&o.push({name:s.name,value:u})}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 AJt(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var Q0={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 bJt(e){return Vr(e,Q0.FERN_EXAMPLES)??[]}function EJt(e,t){return t.includes("://")?t:`${e}://${t}`}function vJt(e){return e.startsWith("/")?e:"/"+e}function UJo({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[c,l]of Object.entries(i.components?.schemas??{})){let p=Va(l,!1,!1,e,[c],r,e.namespace);o[c]=p}let a=new IUe(o,e),u={};for(let[c,l]of Object.entries(i.servers??{})){let p=Vr(l,Q0.FERN_SERVER_NAME);u[c]={name:p??c,url:EJt(l.protocol,l.url)}}for(let[c,l]of Object.entries(i.channels??{})){let p=Vr(l,Q0.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${c} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(l.parameters!=null)for(let[A,E]of Object.entries(l.parameters??{})){let v=Vr(E,Q0.FERN_PARAMETER_NAME);d.push({name:A,description:E.description,parameterNameOverride:v,schema:E.schema!=null?Va(E.schema,!1,!1,e,t,r,e.namespace):Fr.primitive({schema:Ii.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:AS(E),source:r,explode:void 0})}let f=[],m=[];if(l.bindings?.ws!=null){if(l.bindings.ws.headers!=null){let A=l.bindings.ws.headers.required??[];for(let[E,v]of Object.entries(l.bindings.ws.headers.properties??{})){if(ei(v)){let x=e.resolveSchemaReference(v),C=A.includes(E),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];f.push({name:E,schema:Z5(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,env:void 0,availability:AS(x),source:r});continue}let b=A.includes(E),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!b]:[!b,!1];f.push({name:E,schema:Va(v,I,w,e,[...t,E],r,e.namespace),description:v.description,parameterNameOverride:void 0,env:void 0,availability:AS(v),source:r})}}if(l.bindings.ws.query!=null){let A=l.bindings.ws.query.required??[];for(let[E,v]of Object.entries(l.bindings.ws.query.properties??{})){if(ei(v)){let x=e.resolveSchemaReference(v),C=A.includes(E),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];m.push({name:E,schema:Z5(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,availability:AS(x),source:r,explode:void 0});continue}let b=A.includes(E),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!b]:[!b,!1];m.push({name:E,schema:Va(v,I,w,e,[...t,E],r,e.namespace),description:v.description,parameterNameOverride:void 0,availability:AS(v),source:r,explode:void 0})}}}let h;l.publish!=null&&("oneOf"in l.publish.message?h=MJo({generatedName:l.publish.operationId??"PublishEvent",event:l.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):h=LJo({action:"Publish",channelPath:c,message:l.publish.message,context:e,source:r}));let g;if(l.subscribe!=null&&("oneOf"in l.subscribe.message?g=MJo({generatedName:l.subscribe.operationId??"SubscribeEvent",event:l.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=LJo({action:"Subscribe",channelPath:c,message:l.subscribe.message,context:e,source:r})),f.length>0||m.length>0||h!=null||g!=null){let A=bJt(l),E=[];if(A.length>0)E=a.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:A,handshake:{headers:f,queryParameters:m},source:r,namespace:e.namespace});else{let w=[];h!=null&&w.push({type:"publish",payload:h}),g!=null&&w.push({type:"subscribe",payload:g});let x=a.buildWebsocketSessionExample({handshake:{headers:f,queryParameters:m},messages:w});x!=null&&E.push(x)}let v=Vr(l,Q0.FERN_CHANNEL_ADDRESS),b=v??vJt(c),I=[];h!=null&&I.push({origin:"client",name:"publish",body:ff(h),methodName:void 0}),g!=null&&I.push({origin:"server",name:"subscribe",body:ff(g),methodName:void 0}),s[c]={audiences:Vr(l,bn.AUDIENCES)??[],handshake:{headers:f.map(w=>({...w,schema:ff(w.schema),env:w.env})),queryParameters:m.map(w=>({...w,schema:ff(w.schema)})),pathParameters:d.map(w=>({...w,schema:ff(w.schema)}))},groupName:e.resolveGroupName([Vr(l,Q0.FERN_SDK_GROUP_NAME)??c]),messages:I,servers:(l.servers?.map(w=>u[w])??Object.values(u)).filter(w=>w!=null&&w.name!=null).map(w=>({...w,name:w.name})),summary:Vr(l,Q0.FERN_DISPLAY_NAME),connectMethodName:Vr(l,Q0.FERN_SDK_METHOD_NAME),path:b,description:l.description,examples:E,source:r}}}return{groupedSchemas:EUe(e.namespace,o),channels:s??void 0,servers:Object.values(u).map(c=>({...c,name:c.name})),basePath:Vr(i,Q0.BASE_PATH)}}function MJo({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=[],u=[];for(let c of t.message.oneOf){let l,p={type:"notFound"};if(ei(c)){let d=r.resolveMessageReference(c);!ei(d.payload)&&s.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,l={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):l=d.payload}else l=c;u.push(p),a.push(l)}return Ape({description:t.description??t.message.description,availability:AS(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"?u:[]})}}function LJo({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return ei(r.payload)&&(o=n.resolveSchemaReference(r.payload)),Va(o,!1,!1,n,[t,e],i,n.namespace)}}var IJt=class extends bUe{getExampleMessageReference(t){let r=t.channelId??this.getDefaultChannelId();if(r==null)throw new Error("Cannot resolve example message reference: no channelId provided and no channels found in document");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 Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new Error("Cannot resolve message reference: message is null or undefined");if(!t.$ref)throw new Error("Cannot resolve message reference: message.$ref is undefined or empty");if(t.$ref.startsWith(n)){let u=t.$ref.split("/"),c=u[2],l=u[4],p=c?.replace(/~1/g,"/").replace(/~0/g,"~");if(p==null||l==null||!this.document.channels?.[p])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${p}`);let f=this.document.channels[p].messages?.[l];if(f==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in f&&!r?this.resolveMessageReference(f):{...f,name:l}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let s=t.$ref.substring(i.length),a=o.messages[s];if(a==null)throw new Error(`${t.$ref} is undefined`);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}};Ci();var zJo="#/channels/",VJo="#/servers/",oKn="$message.";function GJo({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){hJt();let o={},s={},a={},u=[],c={};e.logger.debug("Parsing V3 AsyncAPI...");let l=Z9();for(let[x,C]of Object.entries(i.components?.schemas??{})){let _=l.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);o[_]=Va(C,!1,!1,e,[_],r,e.namespace)}for(let[x,C]of Object.entries(i.channels??{}))if(s[x]||(s[x]={}),C.messages)for(let[_,R]of Object.entries(C.messages))if(a[_]||(a[_]=[]),e.isReferenceObject(R)){let U=e.resolveMessageReference(R);a[_].push({channelId:x,payload:U.payload})}else e.isMessageWithPayload(R)&&a[_].push({channelId:x,payload:R.payload});for(let[x,C]of Object.entries(a))if(C.length===1){let _=C[0],R=_.channelId;s[R]=s[R]||{},s[R][x]=Va(_.payload,!1,!1,e,[x],r,e.namespace)}else{u.push(x);for(let{channelId:_,payload:R}of C){let U=`${_}_${x}`;s[_]||(s[_]={}),s[_][U]=Va(R,!1,!1,e,[U],r,e.namespace)}}let p={},d=Z9();for(let[x,C]of Object.entries(s))for(let[_,R]of Object.entries(C)){let U=d.getUniqueSchemaId(_,e.logger,e.options.resolveSchemaCollisions);p[U]=R}let f=new IUe({...o,...p},e),m={};for(let[x,C]of Object.entries(i.servers??{})){let _=Vr(C,Q0.FERN_SERVER_NAME);m[x]={name:_??x,url:EJt(C.protocol,C.host)}}let h={},g=Object.keys(i.channels??{});for(let[x,C]of Object.entries(i.operations??{})){if(Vr(C,Q0.IGNORE))continue;let _;if(C.channel==null||!("$ref"in C.channel)||C.channel.$ref==null)if(g.length===1&&g[0]!=null)_=g[0];else continue;else _=MQc(C);h[_]||(h[_]={subscribe:[],publish:[],__parsedMessages:[]});let R=Vr(C,Q0.FERN_SDK_METHOD_NAME);if(!C.messages||!Array.isArray(C.messages))continue;let U=C.messages.filter(z=>z!=null&&z.$ref!=null).map(z=>({ref:z,methodName:R})),q=h[_];if(q==null)throw new Error(`Internal error: channelEvents["${_}"] is unexpectedly undefined for operation ${x}`);if(C.action==="receive")q.subscribe.push(...U);else if(C.action==="send")q.publish.push(...U);else throw new Error(`Operation ${x} has an invalid action: ${C.action}`)}for(let[x,C]of Object.entries(h)){let _=[];_.push(...qJo({messages:C.subscribe,channelPath:x,origin:"server",messageSchemas:s[x]??{},duplicatedMessageIds:u,context:e})),_.push(...qJo({messages:C.publish,channelPath:x,origin:"client",messageSchemas:s[x]??{},duplicatedMessageIds:u,context:e})),h[x]!=null&&(h[x].__parsedMessages=_)}for(let[x,C]of Object.entries(i.channels??{})){if(Vr(C,Q0.IGNORE))continue;let _=[],R=[],U=[];if(C.parameters!=null)for(let[q,z]of Object.entries(C.parameters)){let Z=e.isReferenceObject(z)?e.resolveParameterReference(z):z,{type:oe,parameterKey:V}=Z.location!=null?LQc(Z.location):{type:C.address?.includes(`={${q}}`)?"query":"path",parameterKey:q},K=Vr(Z,Q0.FERN_PARAMETER_OPTIONAL),be=Nc(Ln(x))+Nc(Ln(q)),Ce=Z.schema!=null?ei(Z.schema)?Z5(Z.schema,!1,!1,e,[V],void 0,r,e.namespace):Va(Z.schema,!1,!1,e,[V],r,e.namespace):Va({...Z,type:"string",title:be,example:Z.examples?.[0],default:Z.default,enum:Z.enum,required:void 0},!1,!1,e,[V],r,e.namespace),J=K?Fr.optional({value:Ce,description:void 0,availability:void 0,generatedName:"",title:be,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Ce,H={name:V,description:Z.description,parameterNameOverride:void 0,schema:J,variableReference:void 0,availability:AS(z),source:r,explode:void 0};oe==="header"?_.push({...H,env:void 0}):oe==="path"?R.push(H):(oe==="payload"||oe==="query")&&U.push(H)}if(_.length>0||U.length>0||h[x]!=null&&(h[x].publish!=null||h[x].subscribe!=null)){let q=bJt(C),z=h[x]?.__parsedMessages??[],Z=[];try{if(q.length>0)Z=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:q,handshake:{headers:_,queryParameters:U},source:r,namespace:e.namespace});else{let Ce=[],{examplePublishMessage:J,exampleSubscribeMessage:H}=zQc({messages:z,messageSchemas:s[x]??{}});J!=null&&Ce.push(J),H!=null&&Ce.push(H);let ge=f.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:U},messages:Ce});ge!=null&&Z.push(ge)}}catch(Ce){e.logger.warn(`Failed to build examples for channel ${x}: ${Ce instanceof Error?Ce.message:String(Ce)}`)}let oe=Vr(C,Q0.FERN_SDK_GROUP_NAME),V=Vr(C,Q0.FERN_SDK_METHOD_NAME),K=(C.servers?.map(Ce=>UQc(m,Ce))??Object.values(m)).map(Ce=>({...Ce,name:Ce.name})),be=C.address?.split("?")[0]??vJt(x);c[x]={audiences:Vr(C,bn.AUDIENCES)??[],handshake:{headers:_.map(Ce=>({...Ce,schema:ff(Ce.schema),env:Ce.env})),queryParameters:U.map(Ce=>({...Ce,schema:ff(Ce.schema)})),pathParameters:R.map(Ce=>({...Ce,parameterNameOverride:void 0,schema:ff(Ce.schema)}))},groupName:e.resolveGroupName(typeof oe=="string"?[oe]:oe??[x]),messages:z,summary:Vr(C,Q0.FERN_DISPLAY_NAME),connectMethodName:V,servers:K,path:be,description:C.description,examples:Z,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${x} as it does not qualify for inclusion (no headers, query params, or operations)`)}let A={...o,...p},E={},v=Z9();for(let[x,C]of Object.entries(A)){let _=v.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);E[_]=ff(C)}let b=EUe(e.namespace,o),I=Object.values(m).map(x=>({...x,name:x.name})),w=Vr(i,Q0.BASE_PATH);return{groupedSchemas:b,channels:c,servers:I,basePath:w}}function jQc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function MQc(e){if(!e.channel)throw new Error("Operation is missing required 'channel' field");if(!e.channel.$ref)throw new Error("Operation channel is missing required '$ref' field");if(!e.channel.$ref.startsWith(zJo))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return jQc(e.channel.$ref.substring(zJo.length))}function LQc(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(oKn))throw new Error(`Invalid location format: ${e}; expected ${oKn} prefix`);let n=t.substring(oKn.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function UQc(e,t){if(!t.$ref.startsWith(VJo))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(VJo.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function qJo({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,u)=>{try{let l=o.resolveMessageReference(a.ref,!0).name;i.includes(l)&&(l=`${t}_${l}`);let p=n[l];p!=null&&s.push({origin:r,name:l??`${r}Message${u+1}`,body:ff(p),methodName:a.methodName})}catch(c){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${c instanceof Error?c.message:String(c)}`)}}),s}function zQc({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}}function WJo({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 u=new gJt({document:a,taskContext:t,options:r,namespace:o});return UJo({context:u,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,u=new IJt({document:a,taskContext:t,options:r,namespace:o});return GJo({context:u,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}Qt();Ci();Ci();function $Jo(e){return Vr(e,bn.ASYNC_CONFIG)}var HJo="$request.";function KJo(e){let t=Vr(e,bn.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json",terminator:void 0}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format,terminator:t.terminator}:{type:"streamCondition",format:t.format??"json",terminator:t.terminator,streamDescription:t["stream-description"],streamConditionProperty:VQc(t["stream-condition"]),streamRequestName:t["stream-request-name"],responseStream:t["response-stream"],response:t.response}}function VQc(e){return e.startsWith(HJo)?e.slice(HJo.length):e}function JJo(e){let t=e;if(t.cursor!=null)return yI.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return yI.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return yI.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return yI.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 yI.custom({results:i.results})}throw new Error("Invalid pagination extension")}function YJo(e,t){let r=Vr(t,bn.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=Vr(e,bn.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:JJo(n)}return JJo(r)}}function XJo(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:wUe(n,t)}}}function ZJo(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function qQc(e){return e.includes("json")||e==="*/*"}function sKn({content:e,context:t}){for(let[r,n]of Object.entries(e))if(wJt({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function wJt({mediaType:e,mediaTypeObject:t,context:r}){if(!qQc(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:wUe(t,r)}}function CJt({content:e,context:t}){let r=sKn({content:e,context:t});if(!r)return;let[n,i]=r;return wJt({mediaType:n,mediaTypeObject:i,context:t})}function eYo(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:wUe(n,t)}}}function wUe(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=Vr(e,c_.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=ei(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}Qt();Qt();function tYo(e){let t=GQc(e),r={};return aKn({obj:t,occurrences:r,breadcrumbs:[]}),r}function aKn({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)aKn({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)aKn({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function GQc(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?qmt(r.get):void 0,put:r?.put!=null?qmt(r.put):void 0,post:r?.post!=null?qmt(r.post):void 0,patch:r?.patch!=null?qmt(r.patch):void 0,delete:r?.delete!=null?qmt(r.delete):void 0}]))}}function qmt(e){return{...e,requestBody:e.requestBody!=null?ei(e.requestBody)?e.requestBody:WQc(e.requestBody):void 0}}function WQc(e){let t,r;for(let n in e.content){let i=af.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[af.MULTIPART_FORM_DATA]:r}}:e}var xJt=class{endpoints;parser=new xre;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 rYo="#/components/parameters/",nYo="#/components/responses/",iYo="#/components/examples/",oYo="#/components/requestBodies/",sYo="#/components/securitySchemes/",CUe=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}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=tYo(t),this.options=i,this.source=o,this.filter=new xJt({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"}):(ei(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(rYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(rYo.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(oYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(oYo.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(nYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(nYo.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(iYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(iYo.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(sYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(sYo.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(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;for(let[r,n]of Object.entries(this.document.components.schemas))!n||ei(n)||t.set(r,Vr(n,bn.SDK_NAMESPACE)||this.namespace);return t}};var m_e=class extends CUe{constructor({document:t,taskContext:r,options:n,source:i,namespace:o}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o})}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){}};Qt();var TJt=require("fs"),DJt=require("path");var mt={};Y(mt,{BRAND:()=>yNc,DIRTY:()=>h_e,EMPTY_PATH:()=>JQc,INVALID:()=>tu,NEVER:()=>rjc,OK:()=>yS,ParseStatus:()=>l_,Schema:()=>Nl,ZodAny:()=>Ipe,ZodArray:()=>sne,ZodBigInt:()=>A_e,ZodBoolean:()=>y_e,ZodBranded:()=>Wmt,ZodCatch:()=>O_e,ZodDate:()=>b_e,ZodDefault:()=>B_e,ZodDiscriminatedUnion:()=>BJt,ZodEffects:()=>uM,ZodEnum:()=>__e,ZodError:()=>HD,ZodFirstPartyTypeKind:()=>Ou,ZodFunction:()=>PJt,ZodIntersection:()=>w_e,ZodIssueCode:()=>on,ZodLazy:()=>C_e,ZodLiteral:()=>x_e,ZodMap:()=>PUe,ZodNaN:()=>DUe,ZodNativeEnum:()=>S_e,ZodNever:()=>r8,ZodNull:()=>v_e,ZodNullable:()=>nG,ZodNumber:()=>g_e,ZodObject:()=>KD,ZodOptional:()=>sM,ZodParsedType:()=>Lo,ZodPipeline:()=>$mt,ZodPromise:()=>wpe,ZodReadonly:()=>P_e,ZodRecord:()=>OJt,ZodSchema:()=>Nl,ZodSet:()=>TUe,ZodString:()=>vpe,ZodSymbol:()=>BUe,ZodTransformer:()=>uM,ZodTuple:()=>rG,ZodType:()=>Nl,ZodUndefined:()=>E_e,ZodUnion:()=>I_e,ZodUnknown:()=>one,ZodVoid:()=>OUe,addIssueToContext:()=>lo,any:()=>SNc,array:()=>TNc,bigint:()=>INc,boolean:()=>AYo,coerce:()=>tjc,custom:()=>mYo,date:()=>wNc,datetimeRegex:()=>fYo,defaultErrorMap:()=>nne,discriminatedUnion:()=>kNc,effect:()=>$Nc,enum:()=>qNc,function:()=>UNc,getErrorMap:()=>xUe,getParsedType:()=>tG,instanceof:()=>ENc,intersection:()=>QNc,isAborted:()=>_Jt,isAsync:()=>_Ue,isDirty:()=>SJt,isValid:()=>Epe,late:()=>bNc,lazy:()=>zNc,literal:()=>VNc,makeIssue:()=>Gmt,map:()=>MNc,nan:()=>vNc,nativeEnum:()=>GNc,never:()=>ONc,null:()=>_Nc,nullable:()=>KNc,number:()=>gYo,object:()=>DNc,objectUtil:()=>uKn,oboolean:()=>ejc,onumber:()=>ZNc,optional:()=>HNc,ostring:()=>XNc,pipeline:()=>YNc,preprocess:()=>JNc,promise:()=>WNc,quotelessJson:()=>$Qc,record:()=>jNc,set:()=>LNc,setErrorMap:()=>KQc,strictObject:()=>RNc,string:()=>hYo,symbol:()=>CNc,transformer:()=>$Nc,tuple:()=>NNc,undefined:()=>xNc,union:()=>FNc,unknown:()=>BNc,util:()=>bp,void:()=>PNc});var bp;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(bp||(bp={}));var uKn;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(uKn||(uKn={}));var Lo=bp.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tG=e=>{switch(typeof e){case"undefined":return Lo.undefined;case"string":return Lo.string;case"number":return Number.isNaN(e)?Lo.nan:Lo.number;case"boolean":return Lo.boolean;case"function":return Lo.function;case"bigint":return Lo.bigint;case"symbol":return Lo.symbol;case"object":return Array.isArray(e)?Lo.array:e===null?Lo.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Lo.promise:typeof Map<"u"&&e instanceof Map?Lo.map:typeof Set<"u"&&e instanceof Set?Lo.set:typeof Date<"u"&&e instanceof Date?Lo.date:Lo.object;default:return Lo.unknown}};var on=bp.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$Qc=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),HD=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let c=s.path[u];u===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,bp.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};HD.create=e=>new HD(e);var HQc=(e,t)=>{let r;switch(e.code){case on.invalid_type:e.received===Lo.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case on.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,bp.jsonStringifyReplacer)}`;break;case on.unrecognized_keys:r=`Unrecognized key(s) in object: ${bp.joinValues(e.keys,", ")}`;break;case on.invalid_union:r="Invalid input";break;case on.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${bp.joinValues(e.options)}`;break;case on.invalid_enum_value:r=`Invalid enum value. Expected ${bp.joinValues(e.options)}, received '${e.received}'`;break;case on.invalid_arguments:r="Invalid function arguments";break;case on.invalid_return_type:r="Invalid function return type";break;case on.invalid_date:r="Invalid date";break;case on.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:bp.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case on.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case on.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case on.custom:r="Invalid input";break;case on.invalid_intersection_types:r="Intersection results could not be merged";break;case on.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case on.not_finite:r="Number must be finite";break;default:r=t.defaultError,bp.assertNever(e)}return{message:r}},nne=HQc;var aYo=nne;function KQc(e){aYo=e}function xUe(){return aYo}var Gmt=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},JQc=[];function lo(e,t){let r=xUe(),n=Gmt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===nne?void 0:nne].filter(i=>!!i)});e.common.issues.push(n)}var l_=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return tu;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return tu;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},tu=Object.freeze({status:"aborted"}),h_e=e=>({status:"dirty",value:e}),yS=e=>({status:"valid",value:e}),_Jt=e=>e.status==="aborted",SJt=e=>e.status==="dirty",Epe=e=>e.status==="valid",_Ue=e=>typeof Promise<"u"&&e instanceof Promise;var Zs;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Zs||(Zs={}));var aM=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},uYo=(e,t)=>{if(Epe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new HD(e.common.issues);return this._error=r,this._error}}};function ml(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:u}=e;return s.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}var Nl=class{get description(){return this._def.description}_getType(t){return tG(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:tG(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new l_,ctx:{common:t.parent.common,data:t.data,parsedType:tG(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(_Ue(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)},i=this._parseSync({data:t,path:n.path,parent:n});return uYo(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Epe(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Epe(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(_Ue(i)?i:Promise.resolve(i));return uYo(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:on.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new uM({schema:this,typeName:Ou.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return sM.create(this,this._def)}nullable(){return nG.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sne.create(this)}promise(){return wpe.create(this,this._def)}or(t){return I_e.create([this,t],this._def)}and(t){return w_e.create(this,t,this._def)}transform(t){return new uM({...ml(this._def),schema:this,typeName:Ou.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new B_e({...ml(this._def),innerType:this,defaultValue:r,typeName:Ou.ZodDefault})}brand(){return new Wmt({typeName:Ou.ZodBranded,type:this,...ml(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new O_e({...ml(this._def),innerType:this,catchValue:r,typeName:Ou.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return $mt.create(this,t)}readonly(){return P_e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},YQc=/^c[^\s-]{8,}$/i,XQc=/^[0-9a-z]+$/,ZQc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,eNc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,tNc=/^[a-z0-9_-]{21}$/i,rNc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nNc=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,iNc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oNc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cKn,sNc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aNc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,uNc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cNc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lNc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pNc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lYo="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fNc=new RegExp(`^${lYo}$`);function pYo(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function dNc(e){return new RegExp(`^${pYo(e)}$`)}function fYo(e){let t=`${lYo}T${pYo(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function mNc(e,t){return!!((t==="v4"||!t)&&sNc.test(e)||(t==="v6"||!t)&&uNc.test(e))}function hNc(e,t){if(!rNc.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function gNc(e,t){return!!((t==="v4"||!t)&&aNc.test(e)||(t==="v6"||!t)&&cNc.test(e))}var vpe=class e extends Nl{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Lo.string){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.string,received:o.parsedType}),tu}let n=new l_,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?lo(i,{code:on.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&lo(i,{code:on.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")iNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"email",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")cKn||(cKn=new RegExp(oNc,"u")),cKn.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"emoji",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")eNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"uuid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")tNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"nanoid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")YQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cuid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")XQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cuid2",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ZQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"ulid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),lo(i,{validation:"url",code:on.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"regex",code:on.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?fYo(o).test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?dNc(o).test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?nNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"duration",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?mNc(t.data,o.version)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"ip",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?hNc(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"jwt",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?gNc(t.data,o.version)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cidr",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?lNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"base64",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?pNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"base64url",code:on.invalid_string,message:o.message}),n.dirty()):bp.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:on.invalid_string,...Zs.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Zs.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Zs.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Zs.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Zs.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Zs.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Zs.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Zs.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Zs.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Zs.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Zs.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Zs.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Zs.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Zs.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...Zs.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Zs.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Zs.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Zs.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Zs.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Zs.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Zs.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Zs.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Zs.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Zs.errToObj(r)})}nonempty(t){return this.min(1,Zs.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};vpe.create=e=>new vpe({checks:[],typeName:Ou.ZodString,coerce:e?.coerce??!1,...ml(e)});function ANc(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var g_e=class e extends Nl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Lo.number){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.number,received:o.parsedType}),tu}let n,i=new l_;for(let o of this._def.checks)o.kind==="int"?bp.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),lo(n,{code:on.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?ANc(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_finite,message:o.message}),i.dirty()):bp.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Zs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Zs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Zs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Zs.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Zs.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Zs.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Zs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Zs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Zs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Zs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Zs.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Zs.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Zs.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Zs.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&bp.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};g_e.create=e=>new g_e({checks:[],typeName:Ou.ZodNumber,coerce:e?.coerce||!1,...ml(e)});var A_e=class e extends Nl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Lo.bigint)return this._getInvalidInput(t);let n,i=new l_;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):bp.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return lo(r,{code:on.invalid_type,expected:Lo.bigint,received:r.parsedType}),tu}gte(t,r){return this.setLimit("min",t,!0,Zs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Zs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Zs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Zs.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Zs.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Zs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Zs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Zs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Zs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Zs.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};A_e.create=e=>new A_e({checks:[],typeName:Ou.ZodBigInt,coerce:e?.coerce??!1,...ml(e)});var y_e=class extends Nl{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Lo.boolean){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.boolean,received:n.parsedType}),tu}return yS(t.data)}};y_e.create=e=>new y_e({typeName:Ou.ZodBoolean,coerce:e?.coerce||!1,...ml(e)});var b_e=class e extends Nl{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Lo.date){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.date,received:o.parsedType}),tu}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_date}),tu}let n=new l_,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):bp.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Zs.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Zs.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};b_e.create=e=>new b_e({checks:[],coerce:e?.coerce||!1,typeName:Ou.ZodDate,...ml(e)});var BUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.symbol){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.symbol,received:n.parsedType}),tu}return yS(t.data)}};BUe.create=e=>new BUe({typeName:Ou.ZodSymbol,...ml(e)});var E_e=class extends Nl{_parse(t){if(this._getType(t)!==Lo.undefined){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.undefined,received:n.parsedType}),tu}return yS(t.data)}};E_e.create=e=>new E_e({typeName:Ou.ZodUndefined,...ml(e)});var v_e=class extends Nl{_parse(t){if(this._getType(t)!==Lo.null){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.null,received:n.parsedType}),tu}return yS(t.data)}};v_e.create=e=>new v_e({typeName:Ou.ZodNull,...ml(e)});var Ipe=class extends Nl{constructor(){super(...arguments),this._any=!0}_parse(t){return yS(t.data)}};Ipe.create=e=>new Ipe({typeName:Ou.ZodAny,...ml(e)});var one=class extends Nl{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yS(t.data)}};one.create=e=>new one({typeName:Ou.ZodUnknown,...ml(e)});var r8=class extends Nl{_parse(t){let r=this._getOrReturnCtx(t);return lo(r,{code:on.invalid_type,expected:Lo.never,received:r.parsedType}),tu}};r8.create=e=>new r8({typeName:Ou.ZodNever,...ml(e)});var OUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.undefined){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.void,received:n.parsedType}),tu}return yS(t.data)}};OUe.create=e=>new OUe({typeName:Ou.ZodVoid,...ml(e)});var sne=class e extends Nl{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Lo.array)return lo(r,{code:on.invalid_type,expected:Lo.array,received:r.parsedType}),tu;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(lo(r,{code:s?on.too_big:on.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(lo(r,{code:on.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(lo(r,{code:on.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new aM(r,s,r.path,a)))).then(s=>l_.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new aM(r,s,r.path,a)));return l_.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Zs.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Zs.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Zs.toString(r)}})}nonempty(t){return this.min(1,t)}};sne.create=(e,t)=>new sne({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ou.ZodArray,...ml(t)});function SUe(e){if(e instanceof KD){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=sM.create(SUe(n))}return new KD({...e._def,shape:()=>t})}else return e instanceof sne?new sne({...e._def,type:SUe(e.element)}):e instanceof sM?sM.create(SUe(e.unwrap())):e instanceof nG?nG.create(SUe(e.unwrap())):e instanceof rG?rG.create(e.items.map(t=>SUe(t))):e}var KD=class e extends Nl{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=bp.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Lo.object){let c=this._getOrReturnCtx(t);return lo(c,{code:on.invalid_type,expected:Lo.object,received:c.parsedType}),tu}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof r8&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let u=[];for(let c of s){let l=o[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new aM(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof r8){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(lo(i,{code:on.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new aM(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>l_.mergeObjectSync(n,c)):l_.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return Zs.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Zs.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ou.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of bp.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of bp.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return SUe(this)}partial(t){let r={};for(let n of bp.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of bp.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof sM;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return dYo(bp.objectKeys(this.shape))}};KD.create=(e,t)=>new KD({shape:()=>e,unknownKeys:"strip",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});KD.strictCreate=(e,t)=>new KD({shape:()=>e,unknownKeys:"strict",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});KD.lazycreate=(e,t)=>new KD({shape:e,unknownKeys:"strip",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});var I_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new HD(a.ctx.common.issues));return lo(r,{code:on.invalid_union,unionErrors:s}),tu}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new HD(u));return lo(r,{code:on.invalid_union,unionErrors:a}),tu}}get options(){return this._def.options}};I_e.create=(e,t)=>new I_e({options:e,typeName:Ou.ZodUnion,...ml(t)});var ine=e=>e instanceof C_e?ine(e.schema):e instanceof uM?ine(e.innerType()):e instanceof x_e?[e.value]:e instanceof __e?e.options:e instanceof S_e?bp.objectValues(e.enum):e instanceof B_e?ine(e._def.innerType):e instanceof E_e?[void 0]:e instanceof v_e?[null]:e instanceof sM?[void 0,...ine(e.unwrap())]:e instanceof nG?[null,...ine(e.unwrap())]:e instanceof Wmt||e instanceof P_e?ine(e.unwrap()):e instanceof O_e?ine(e._def.innerType):[],BJt=class e extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.object)return lo(r,{code:on.invalid_type,expected:Lo.object,received:r.parsedType}),tu;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(lo(r,{code:on.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),tu)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=ine(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Ou.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...ml(n)})}};function lKn(e,t){let r=tG(e),n=tG(t);if(e===t)return{valid:!0,data:e};if(r===Lo.object&&n===Lo.object){let i=bp.objectKeys(t),o=bp.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let u=lKn(e[a],t[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(r===Lo.array&&n===Lo.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],u=lKn(s,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===Lo.date&&n===Lo.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var w_e=class extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(_Jt(o)||_Jt(s))return tu;let a=lKn(o.value,s.value);return a.valid?((SJt(o)||SJt(s))&&r.dirty(),{status:r.value,value:a.data}):(lo(n,{code:on.invalid_intersection_types}),tu)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};w_e.create=(e,t,r)=>new w_e({left:e,right:t,typeName:Ou.ZodIntersection,...ml(r)});var rG=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.array)return lo(n,{code:on.invalid_type,expected:Lo.array,received:n.parsedType}),tu;if(n.data.length<this._def.items.length)return lo(n,{code:on.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tu;!this._def.rest&&n.data.length>this._def.items.length&&(lo(n,{code:on.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new aM(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>l_.mergeArray(r,s)):l_.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rG.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rG({items:e,typeName:Ou.ZodTuple,rest:null,...ml(t)})};var OJt=class e extends Nl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.object)return lo(n,{code:on.invalid_type,expected:Lo.object,received:n.parsedType}),tu;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new aM(n,a,n.path,a)),value:s._parse(new aM(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?l_.mergeObjectAsync(r,i):l_.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Nl?new e({keyType:t,valueType:r,typeName:Ou.ZodRecord,...ml(n)}):new e({keyType:vpe.create(),valueType:t,typeName:Ou.ZodRecord,...ml(r)})}},PUe=class extends Nl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.map)return lo(n,{code:on.invalid_type,expected:Lo.map,received:n.parsedType}),tu;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new aM(n,a,n.path,[c,"key"])),value:o._parse(new aM(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return tu;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of s){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return tu;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};PUe.create=(e,t,r)=>new PUe({valueType:t,keyType:e,typeName:Ou.ZodMap,...ml(r)});var TUe=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.set)return lo(n,{code:on.invalid_type,expected:Lo.set,received:n.parsedType}),tu;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(lo(n,{code:on.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(lo(n,{code:on.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(u){let c=new Set;for(let l of u){if(l.status==="aborted")return tu;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>o._parse(new aM(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:Zs.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Zs.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};TUe.create=(e,t)=>new TUe({valueType:e,minSize:null,maxSize:null,typeName:Ou.ZodSet,...ml(t)});var PJt=class e extends Nl{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.function)return lo(r,{code:on.invalid_type,expected:Lo.function,received:r.parsedType}),tu;function n(a,u){return Gmt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xUe(),nne].filter(c=>!!c),issueData:{code:on.invalid_arguments,argumentsError:u}})}function i(a,u){return Gmt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xUe(),nne].filter(c=>!!c),issueData:{code:on.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof wpe){let a=this;return yS(async function(...u){let c=new HD([]),l=await a._def.args.parseAsync(u,o).catch(f=>{throw c.addIssue(n(u,f)),c}),p=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(p,o).catch(f=>{throw c.addIssue(i(p,f)),c})})}else{let a=this;return yS(function(...u){let c=a._def.args.safeParse(u,o);if(!c.success)throw new HD([n(u,c.error)]);let l=Reflect.apply(s,this,c.data),p=a._def.returns.safeParse(l,o);if(!p.success)throw new HD([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rG.create(t).rest(one.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||rG.create([]).rest(one.create()),returns:r||one.create(),typeName:Ou.ZodFunction,...ml(n)})}},C_e=class extends Nl{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};C_e.create=(e,t)=>new C_e({getter:e,typeName:Ou.ZodLazy,...ml(t)});var x_e=class extends Nl{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return lo(r,{received:r.data,code:on.invalid_literal,expected:this._def.value}),tu}return{status:"valid",value:t.data}}get value(){return this._def.value}};x_e.create=(e,t)=>new x_e({value:e,typeName:Ou.ZodLiteral,...ml(t)});function dYo(e,t){return new __e({values:e,typeName:Ou.ZodEnum,...ml(t)})}var __e=class e extends Nl{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return lo(r,{expected:bp.joinValues(n),received:r.parsedType,code:on.invalid_type}),tu}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return lo(r,{received:r.data,code:on.invalid_enum_value,options:n}),tu}return yS(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};__e.create=dYo;var S_e=class extends Nl{_parse(t){let r=bp.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Lo.string&&n.parsedType!==Lo.number){let i=bp.objectValues(r);return lo(n,{expected:bp.joinValues(i),received:n.parsedType,code:on.invalid_type}),tu}if(this._cache||(this._cache=new Set(bp.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=bp.objectValues(r);return lo(n,{received:n.data,code:on.invalid_enum_value,options:i}),tu}return yS(t.data)}get enum(){return this._def.values}};S_e.create=(e,t)=>new S_e({values:e,typeName:Ou.ZodNativeEnum,...ml(t)});var wpe=class extends Nl{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.promise&&r.common.async===!1)return lo(r,{code:on.invalid_type,expected:Lo.promise,received:r.parsedType}),tu;let n=r.parsedType===Lo.promise?r.data:Promise.resolve(r.data);return yS(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};wpe.create=(e,t)=>new wpe({type:e,typeName:Ou.ZodPromise,...ml(t)});var uM=class extends Nl{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ou.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{lo(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return tu;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?tu:u.status==="dirty"?h_e(u.value):r.value==="dirty"?h_e(u.value):u});{if(r.value==="aborted")return tu;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?tu:a.status==="dirty"?h_e(a.value):r.value==="dirty"?h_e(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?tu:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?tu:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Epe(s))return tu;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Epe(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):tu);bp.assertNever(i)}};uM.create=(e,t,r)=>new uM({schema:e,typeName:Ou.ZodEffects,effect:t,...ml(r)});uM.createWithPreprocess=(e,t,r)=>new uM({schema:t,effect:{type:"preprocess",transform:e},typeName:Ou.ZodEffects,...ml(r)});var sM=class extends Nl{_parse(t){return this._getType(t)===Lo.undefined?yS(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};sM.create=(e,t)=>new sM({innerType:e,typeName:Ou.ZodOptional,...ml(t)});var nG=class extends Nl{_parse(t){return this._getType(t)===Lo.null?yS(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};nG.create=(e,t)=>new nG({innerType:e,typeName:Ou.ZodNullable,...ml(t)});var B_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Lo.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};B_e.create=(e,t)=>new B_e({innerType:e,typeName:Ou.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ml(t)});var O_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _Ue(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new HD(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new HD(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};O_e.create=(e,t)=>new O_e({innerType:e,typeName:Ou.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ml(t)});var DUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.nan){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.nan,received:n.parsedType}),tu}return{status:"valid",value:t.data}}};DUe.create=e=>new DUe({typeName:Ou.ZodNaN,...ml(e)});var yNc=Symbol("zod_brand"),Wmt=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},$mt=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?tu:o.status==="dirty"?(r.dirty(),h_e(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?tu:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Ou.ZodPipeline})}},P_e=class extends Nl{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Epe(i)&&(i.value=Object.freeze(i.value)),i);return _Ue(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};P_e.create=(e,t)=>new P_e({innerType:e,typeName:Ou.ZodReadonly,...ml(t)});function cYo(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function mYo(e,t={},r){return e?Ipe.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=cYo(t,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!o){let s=cYo(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):Ipe.create()}var bNc={object:KD.lazycreate},Ou;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Ou||(Ou={}));var ENc=(e,t={message:`Input not instance of ${e.name}`})=>mYo(r=>r instanceof e,t),hYo=vpe.create,gYo=g_e.create,vNc=DUe.create,INc=A_e.create,AYo=y_e.create,wNc=b_e.create,CNc=BUe.create,xNc=E_e.create,_Nc=v_e.create,SNc=Ipe.create,BNc=one.create,ONc=r8.create,PNc=OUe.create,TNc=sne.create,DNc=KD.create,RNc=KD.strictCreate,FNc=I_e.create,kNc=BJt.create,QNc=w_e.create,NNc=rG.create,jNc=OJt.create,MNc=PUe.create,LNc=TUe.create,UNc=PJt.create,zNc=C_e.create,VNc=x_e.create,qNc=__e.create,GNc=S_e.create,WNc=wpe.create,$Nc=uM.create,HNc=sM.create,KNc=nG.create,JNc=uM.createWithPreprocess,YNc=$mt.create,XNc=()=>hYo().optional(),ZNc=()=>gYo().optional(),ejc=()=>AYo().optional(),tjc={string:(e=>vpe.create({...e,coerce:!0})),number:(e=>g_e.create({...e,coerce:!0})),boolean:(e=>y_e.create({...e,coerce:!0})),bigint:(e=>A_e.create({...e,coerce:!0})),date:(e=>b_e.create({...e,coerce:!0}))};var rjc=tu;var njc=mt.object({lang:mt.string(),label:mt.optional(mt.string()),source:mt.string()}),pKn=mt.array(njc);Qt();var yYo={README_EXT:"x-readme"};function ijc(e){if(!Array.isArray(e))return!1;for(let t of e)if(!ba(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function bYo(e){let t=Vr(e,yYo.README_EXT);if(!ba(t))return[];let r=t["code-samples"];if(!ijc(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}function ojc(e){return ba(e)&&typeof e.$ref=="string"}function sjc(e,t){if(e!=null){if(typeof e=="string")return e;if(ojc(e)){let r=(0,DJt.resolve)(t??process.cwd(),e.$ref);if((0,TJt.existsSync)(r))try{return(0,TJt.readFileSync)(r,"utf-8")}catch{return}}}}function ajc(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!ba(n))continue;let o=sjc(n.code,t);o!=null&&r.push({...n,code:o})}return r}function EYo(e,t,r){let n=Vr(t,bn.EXAMPLES),i=r.source.type==="openapi"?(0,DJt.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!ba(p))return p;let f=p["code-samples"];if(f!=null){let m=ajc(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=$d.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=jmt(t,c_.REDOCLY_CODE_SAMPLES_KEBAB,pKn,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...jmt(t,c_.REDOCLY_CODE_SAMPLES_CAMEL,pKn,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&s.push({"code-samples":c.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let l=bYo(t);return l.length>0&&s.push({"code-samples":l}),s.map(eM.unknown)}function vYo(e){let t=Vr(e,bn.AVAILABILITY);if(t==="ga"||t==="generally-available")return jw.GenerallyAvailable;if(t==="beta"||t==="pre-release")return jw.Beta;if(t==="deprecated")return jw.Deprecated;if(e.deprecated)return jw.Deprecated}function IYo(e){let t=Vr(e,bn.RETRIES);if(t!=null&&t.disabled===!0)return Jh.RetriesConfiguration.disabled(t.disabled)}var ujc="x-fern-default-url";function RJt(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=cjc(e);return{url:pjc({url:e.url,variables:e.variables??{}}),description:e.description,name:fjc(e,t),audiences:Vr(e,bn.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?ljc(e.variables):void 0,defaultUrl:r?n:void 0}}function cjc(e){let t=e[ujc];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function ljc(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function pjc({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 fjc(e,t){let r=Vr(e,[bn.SERVER_NAME_V1,bn.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}}function wYo(e){return Vr(e,bn.PARAMETER_NAME)}function CYo(e){return Vr(e,bn.SDK_VARIABLE)}function FJt({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let u=ei(a)?n.resolveParameterReference(a):a,c=Vr(a,bn.IGNORE)??Vr(u,bn.IGNORE);if(c!=null&&c){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let l=u.required??!1,p=AS(u),d=[...i,u.name],f=py(d,n.options.preserveSchemaIds),m=u.in==="header",[h,g]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!l]:[!l,!1],A=u.schema!=null?Va(u.schema,h,g,n,d,o,n.namespace,!1,new Set,oM({schema:u,logger:n.logger})):l?Fr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Ii.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oM({schema:u,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Fr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Fr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Ii.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oM({schema:u,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(u.in==="header"&&u.schema!=null&&!ei(u.schema)&&u.schema.default!=null){let v=u.schema.default;typeof v=="string"&&v.length>0&&(A=Fr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:wg.string(v),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let E={name:u.name,schema:A,description:u.description,parameterNameOverride:wYo(u),availability:p,source:o};u.in==="query"?s.queryParameters.push({...E,explode:mjc(u)}):u.in==="path"?s.pathParameters.push({...E,variableReference:CYo(u),explode:hjc(u)}):u.in==="header"?!djc.has(u.name.toLowerCase())&&!n.authHeaders.has(u.name)?s.headers.push({...E,env:void 0}):n.logger.debug(`Ignoring ${u.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${u.in} parameter, ${u.name}, in ${t.toUpperCase()} ${e}`)}return s}var djc=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function mjc(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 hjc(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}Qt();function gjc({content:e,context:t}){for(let[r,n]of Object.entries(e))if(_Yo({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function _Yo({mediaType:e,mediaTypeObject:t,context:r}){if(af.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:wUe(t,r)}}function Ajc({content:e,context:t}){for(let[r,n]of Object.entries(e))if(SYo({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function SYo({mediaType:e,mediaTypeObject:t,context:r}){if(af.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:wUe(t,r)}}function BYo({mediaType:e}){return af.parse(e)?.isBinary()??!1}function yjc({content:e}){for(let[t,r]of Object.entries(e))if(BYo({mediaType:t}))return[t,r]}function bjc(e,t){let r=ei(e)?fKn(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!ei(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function QJt({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}){let a=yjc({content:e});if(a){let[d,f]=a;return iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}let u=Ajc({content:e,context:n}),c=sKn({content:e,context:n}),l=Ejc({json:c,multipart:u,document:r,visitor:{json:([d,f])=>iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),multipart:([d,f])=>iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),neither:()=>{}}});if(l)return l;let p=gjc({content:e,context:n});if(p){let[d,f]=p;return iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}}function Ejc({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?n.neither():i?.schema&&o?.schema?i.schema&&bjc(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function iG({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a}){let u=vjc({mediaTypeObject:t});if(BYo({mediaType:e}))return KO.octetStream({description:r,source:s,sdkMethodName:u,contentType:e});let c=SYo({mediaType:e,mediaTypeObject:t,context:i}),l=c?.schema,p=c?.encoding,d=c?.examples;if(l){let h=ei(l)?fKn(l,n):{id:void 0,schema:l},g=Va(h.schema,!1,!1,i,o,s,a,!1),A=[];if(g.type==="object"){let E=new Set(h.schema.required??[]);for(let v of g.properties){let b=E.has(v.key),{isFile:I,isOptional:w,isArray:x,description:C}=kJt({schema:v.schema,isOptional:!b});if(I){let _=xYo(v.key,p);A.push({key:v.key,schema:G9.file({isOptional:w,isArray:x,description:C}),description:C,contentType:_,exploded:!1,encoding:_==null?i.options.defaultFormParameterEncoding:void 0})}else{let _=xYo(v.key,p);A.push({key:v.key,schema:G9.json(v.schema),description:void 0,contentType:_,exploded:p?.[v.key]?.explode,encoding:_==null?i.options.defaultFormParameterEncoding:wjc(_)})}}}return KO.multipart({name:ei(l)&&i.getNumberOfOccurrencesForRef(l)===1?h.id:void 0,description:h.schema.description,properties:A,source:s,sdkMethodName:u,fullExamples:d})}let f=wJt({mediaType:e,mediaTypeObject:t,context:i});if(f){let h=Va(f.schema,!1,!1,i,o,s,a,!0);return KO.json({description:void 0,schema:h,contentType:f.contentType,fullExamples:f.examples,additionalProperties:!ei(f.schema)&&Lmt(f.schema.additionalProperties,i.options),source:s,sdkMethodName:u})}let m=_Yo({mediaType:e,mediaTypeObject:t,context:i});if(m!=null&&m.schema!=null){let h=Va(m.schema,!1,!1,i,o,s,a,!1);return KO.formUrlEncoded({schema:h,description:r,contentType:m.contentType,source:s,fullExamples:m.examples,additionalProperties:!1,sdkMethodName:u})}}function vjc({mediaTypeObject:e}){return Vr(e,bn.SDK_METHOD_NAME)}var Ijc={"application/json":"json"};function wjc(e){return e?Ijc[e]:void 0}function fKn(e,t){if(!e.$ref.startsWith(f_e))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=rne(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return ei(n)?fKn(n,t):{id:r,schema:n}}function kJt({schema:e,isOptional:t,isArray:r,description:n}){return xjc(e)?kJt({schema:e.value,isOptional:!0,isArray:r,description:e.description}):_jc(e)?kJt({schema:e.value,isOptional:t,isArray:r,description:e.description}):Sjc(e)?kJt({schema:e.value,isOptional:t,isArray:!0,description:e.description}):Cjc(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 Cjc(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function xjc(e){return e.type==="optional"}function _jc(e){return e.type==="nullable"}function Sjc(e){return e.type==="array"}function xYo(e,t){return t?.[e]?.contentType}Qt();var dKn={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"},OYo=new Set(Object.values(dKn));var Bjc=["200","201","202","204"];function NJt({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,streamTerminator:s,source:a}){if(t==null)return{value:void 0,errors:{}};let u=Ojc({responses:t,context:r,source:a,namespace:r.namespace}),c=!1,l;for(let p of i!=null?[i]:Bjc){let d=t[p];d!=null&&(c=!0,l==null&&(l=PYo({operationContext:e,response:d,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace,statusCode:typeof p=="string"?parseInt(p):p})))}if(l==null&&!c&&t.default!=null&&(l=PYo({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace})),l!=null)switch(l.type){case"json":return{value:l,errors:u};case"streamingJson":case"streamingSse":return{value:l,errors:u};case"bytes":case"file":case"text":case"streamingText":return{value:l,errors:u};default:xe(l)}return{value:void 0,errors:u}}function PYo({operationContext:e,streamFormat:t,streamTerminator:r,response:n,context:i,responseBreadcrumbs:o,source:s,namespace:a,statusCode:u}){let c=ei(n)?i.resolveResponseReference(n):n;if(c.content!=null&&Object.entries(c.content).find(([f,m])=>{if(m.schema==null)return!1;let h=ei(m.schema)?i.resolveSchemaReference(m.schema):m.schema;return h.type==="string"&&(h.format==="binary"||h.format==null&&h.contentMediaType==="application/octet-stream")}))return i.options.useBytesForBinaryResponse&&t==null?wh.bytes({description:c.description,source:s,statusCode:u}):wh.file({description:c.description,source:s,statusCode:u});let l=XJo(c.content??{},i);if(l!=null&&t!=null)switch(t){case"json":return wh.streamingJson({statusCode:u,description:c.description,responseProperty:Vr(e.operation,bn.RESPONSE_PROPERTY),terminator:r,fullExamples:l.examples,schema:Va(l.schema,!1,!1,i,o,s,a),source:s});case"sse":return wh.streamingSse({description:c.description,responseProperty:void 0,terminator:r,fullExamples:l.examples,schema:Va(l.schema,!1,!1,i,o,s,a),source:s,statusCode:u})}let p=CJt({context:i,content:c.content??{}});if(p){if(t!=null)switch(t){case"json":return wh.streamingJson({description:c.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:Va(p.schema,!1,!1,i,o,s,a),source:s,statusCode:u});case"sse":return wh.streamingSse({description:c.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:Va(p.schema,!1,!1,i,o,s,a),source:s,statusCode:u})}return wh.json({description:c.description,schema:Va(p.schema,!1,!1,i,o,s,a),responseProperty:Vr(e.operation,bn.RESPONSE_PROPERTY),terminator:void 0,fullExamples:p.examples,source:s,statusCode:u})}for(let[d,f]of Object.entries(c.content??{})){let m=af.parse(d);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return wh.file({description:c.description,source:s,statusCode:u});if(m.isText()&&!d.includes("event-stream")){let h=f.schema;if(h==null)return wh.text({description:c.description,source:s,statusCode:u});let g=ei(h)?i.resolveSchemaReference(h):h;return g.type==="string"&&g.format==="byte"?wh.file({description:c.description,source:s,statusCode:u}):wh.text({description:c.description,source:s,statusCode:u})}}}}function Ojc({responses:e,context:t,source:r,namespace:n}){let i={};for(let[o,s]of Object.entries(e)){if(o==="default")continue;let a=parseInt(o);if(a<400||a>600)continue;let u=ei(s)?t.resolveResponseReference(s):s,c=eYo(u.content??{},t),l=dKn[a];if(l==null){t.logger.warn(`No error name found for status code ${o}`);continue}i[a]={statusCode:a,nameOverride:void 0,generatedName:l,description:u.description,schema:Va(c?.schema??{},!1,!1,t,[l,"Body"],r,n),fullExamples:c?.examples,source:r}}return i}function ane({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,source:s,streamRequestNameOverride:a}){let{document:u,operation:c,path:l,method:p,baseBreadcrumbs:d,pathItem:f}=e,m=Vr(c,bn.IDEMPOTENT),h=Vr(c,[bn.REQUEST_NAME_V1,bn.REQUEST_NAME_V2]),g=[...d,"Request"],A=FJt({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:l,httpMethod:p,source:s}),E=/{([^}]+)}/g,v=[...l.matchAll(E)].map(z=>z[1]).filter(z=>z!==void 0),b=[...l.matchAll(E)].map(z=>z[1]);switch(t.options.pathParameterOrder){case yn.PathParameterOrder.SpecOrder:{let z=b.filter(Z=>!A.pathParameters.some(oe=>oe.name===Z));if(z.length>0)for(let Z of z)A.pathParameters.push({name:Z??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Fr.primitive({schema:Ii.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})}break;case yn.PathParameterOrder.UrlOrder:if(v.length>0){let z=new Map(A.pathParameters.map(V=>[V.name,V])),Z=[],oe=new Set;for(let V of v){let K=z.get(V);oe.add(V),K?Z.push(K):Z.push({name:V,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Fr.primitive({schema:Ii.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})}for(let V of A.pathParameters)oe.has(V.name)||Z.push(V);A.pathParameters=Z}break;default:xe(t.options.pathParameterOrder)}let I=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let z=ei(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,Z=Object.values(z.content).every(V=>Tjc({mediaTypeObject:V})!=null),oe=[];if(Z)return oe.push(...Object.entries(z.content).map(([V,K])=>{let be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:new m_e({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return TYo({context:t,convertedParameters:A})&&be!=null&&(be.type==="json"||be.type==="formUrlEncoded")&&be.schema.type!=="object"&&c.requestBody!=null?be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):c.requestBody!=null&&(be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),be}).filter(V=>V!=null)),oe.length===0?[void 0]:oe;{let V=QJt({content:z.content,description:z.description,document:u,context:new m_e({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return TYo({context:t,convertedParameters:A})&&V!=null&&(V.type==="json"||V.type==="formUrlEncoded")&&V.schema.type!=="object"&&c.requestBody!=null?V=QJt({content:z.content,description:z.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):c.requestBody!=null&&(V=QJt({content:z.content,description:z.description,document:u,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),[V]}})(),w=I.length>1,x=[...d,"Response"],C=NJt({operationContext:e,streamFormat:i,streamTerminator:o,responses:c.responses,context:t,responseBreadcrumbs:x,responseStatusCode:r,source:s}),_=IYo(c),R=vYo(c),U=EYo(e,c,t),q=Vr(c,bn.SERVER_NAME_V2);return I.map(z=>({summary:c.summary,internal:Vr(c,c_.INTERNAL),idempotent:m,audiences:Vr(c,bn.AUDIENCES)??[],operationId:c.operationId!=null&&n!=null?c.operationId+"_"+n:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:Djc({operationContext:e,request:z}),pathParameters:A.pathParameters,queryParameters:A.queryParameters,headers:A.headers,requestNameOverride:a??h??void 0,generatedRequestName:py(w?Pjc({breadcrumbs:g,request:z}):g,t.options.preserveSchemaIds),request:z,response:C.value,errors:C.errors,servers:q!=null?[{name:q,url:void 0,audiences:void 0}]:(c.servers??f.servers??[]).map(Z=>RJt(Z,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:Fjc(c,u),security:Rjc(c),availability:R,method:p,path:l,examples:U,pagination:e.pagination,source:s,retries:_}))}function Pjc({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function Tjc({mediaTypeObject:e}){return Vr(e,bn.SDK_METHOD_NAME)}function Djc({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 Rjc(e){return e.security}function Fjc(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function TYo({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function RYo({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,u=r.discriminant.value,c=r["response-status-code"],l=DYo({context:t,headerToIgnore:a,parameters:o}),p=DYo({context:t,headerToIgnore:a,parameters:s}),d=ane({operationContext:{...e,pathItemParameters:l,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==c))}},context:t,streamFormat:void 0,source:n}),f=ane({operationContext:{...e,pathItemParameters:l,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:c,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Fr.literal({nameOverride:void 0,generatedName:py([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:wg.string(u),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:d,async:f}}function DYo({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=ei(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}Qt();var mKn="stream";function NYo({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:ane({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=FYo({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let l=rne(n.schemaReference);l!=null&&t.excludeSchema(l)}let i=kYo({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let l=rne(n.schemaReference);if(l!=null)return`${l}Streaming`}})(),s=ane({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+mKn}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,mKn]},context:t,streamFormat:r.format,streamTerminator:r.terminator,suffix:mKn,source:t.source,streamRequestNameOverride:o});s.forEach(l=>{l.examples=l.examples.filter(p=>QYo(p,t)!==!1)});let a=FYo({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),u=kYo({operation:e.operation,response:r.response}),c=ane({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:u}},context:t,source:t.source});return c.forEach(l=>{l.examples=l.examples.filter(p=>QYo(p,t)!==!0)}),{streaming:s,nonStreaming:c}}default:xe(r)}}function FYo({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=ei(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=CJt({content:i.content,context:e});if(o==null)return;let s=ei(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&ei(a)&&(a=void 0);let u={...s,properties:{...s.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...a??{}}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{content:{[af.APPLICATION_JSON]:{schema:u}}},schemaReference:ei(o.schema)?o.schema:void 0}}function kYo({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[af.APPLICATION_JSON]:{schema:t}}}}}function QYo(e,t){return e._visit({unknown:r=>{let n=$d.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var VYo=require("crypto");function kjc(e){switch(e){case"unix-seconds":return Jh.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Jh.WebhookTimestampFormat.UnixMillis;case"iso8601":return Jh.WebhookTimestampFormat.Iso8601}}function jYo(e){if(e!=null)return{header:e.header,format:e.format!=null?kjc(e.format):void 0,tolerance:e.tolerance}}function Qjc(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Jh.WebhookPayloadComponent.Body;case"timestamp":return Jh.WebhookPayloadComponent.Timestamp;case"notification-url":return Jh.WebhookPayloadComponent.NotificationUrl;case"message-id":return Jh.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter}}function Njc(e){if(e!=null)switch(e){case"sha256":return Jh.WebhookSignatureAlgorithm.Sha256;case"sha1":return Jh.WebhookSignatureAlgorithm.Sha1;case"sha384":return Jh.WebhookSignatureAlgorithm.Sha384;case"sha512":return Jh.WebhookSignatureAlgorithm.Sha512}}function MYo(e){if(e!=null)switch(e){case"base64":return Jh.WebhookSignatureEncoding.Base64;case"hex":return Jh.WebhookSignatureEncoding.Hex}}function jjc(e){if(e!=null)switch(e){case"rsa-sha256":return Jh.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Jh.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Jh.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Jh.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Jh.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Jh.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Jh.AsymmetricAlgorithm.Ed25519}}function UYo(e){if(e.type==="hmac")return Jh.WebhookSignatureVerification.hmac({header:e.header,algorithm:Njc(e.algorithm),encoding:MYo(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:Qjc(e["payload-format"]),timestamp:jYo(e.timestamp)});if(e.type==="asymmetric"){let t=jjc(e["asymmetric-algorithm"]);return t==null?void 0:Jh.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:t,encoding:MYo(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],timestamp:jYo(e.timestamp)})}}function LYo(e){let t=Vr(e,bn.WEBHOOK_SIGNATURE);if(!(t==null||typeof t=="boolean"))return UYo(t)}function zYo(e,t){let r=Vr(t,bn.WEBHOOK_SIGNATURE);return r!=null?typeof r=="boolean"?LYo(e):UYo(r):LYo(e)}function qYo({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:u}=t,c=[...a,"Payload"],l=[...a,"Response"],p=FJt({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:c,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??Ljc({path:o,method:s,sdkMethodName:u}),f=i.responses?NJt({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:l,source:r}):void 0,m=zYo(n,i);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 g=p.queryParameters.map(v=>({key:v.name,schema:v.schema,readonly:void 0,writeonly:void 0,audiences:[],conflict:{},nameOverride:v.parameterNameOverride,generatedName:py([...c,v.name],e.options.preserveSchemaIds),availability:v.availability})),A=Fr.object({description:i.description,properties:g,nameOverride:void 0,generatedName:py(c,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});return[{summary:i.summary,audiences:Vr(i,bn.AUDIENCES)??[],sdkName:u,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:py(c,e.options.preserveSchemaIds),payload:A,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let h=ei(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([g,A])=>iG({mediaType:g,mediaTypeObject:A,description:h.description,document:n,context:e,requestBreadcrumbs:[...a,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"&&g.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let A,E;return g.type==="multipart"?(A={name:g.name,properties:g.properties,description:g.description,source:g.source},E=Fr.unknown({nameOverride:void 0,generatedName:py(c,e.options.preserveSchemaIds),title:void 0,description:g.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):E=g.schema,{summary:i.summary,audiences:Vr(i,bn.AUDIENCES)??[],sdkName:u,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:py(c,e.options.preserveSchemaIds),payload:E,signatureVerification:m,multipartFormData:A,response:f?.value,description:i.description,examples:Mjc(g.fullExamples),source:r}}).filter(g=>g!=null)}function Mjc(e){if(e==null)return[];let t=[];for(let r of e){let n=ype(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function Ljc({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=Ujc(e);if(n===e.toLowerCase())return e;let i=(0,VYo.createHash)("sha256").update(e).digest("hex").slice(0,8);return zjc(`${n}_${t.toLowerCase()}_${i}`)}function Ujc(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function zjc(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function hKn({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=Vr(r,bn.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=Vjc(r,e),s=YJo(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:qjc({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:qYo({context:e,operationContext:a,source:e.source})};let u=KJo(r);if(u==null&&Gjc({operation:r,context:e})&&(u={type:"stream",format:"sse",terminator:void 0}),u!=null){let p=NYo({context:e,operationContext:a,streamingExtension:u});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let c=$Jo(r);if(c!=null){let p=RYo({context:e,operationContext:a,asyncExtension:c,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:ane({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function Vjc(e,t){let r=Vr(e,bn.SDK_METHOD_NAME),n=Vr(e,bn.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function qjc({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(Ln(`${r}_${n.split("/").join("_")}`));return o}function Gjc({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=ei(n)?t.resolveResponseReference(n):n;if(o.content!=null&&ZJo(o.content))return!0}return!1}function GYo(e,t,r,n){let i=[],o=$Yo(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 u=Wjc({operation:a.operation}),c=hKn({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:u});c&&i.push(c)}return i}function WYo(e,t,r,n){let i=[],o=$Yo(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 u=hKn({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});u&&i.push(u)}return i}function $Yo(e){let t=[];return e.get!=null&&t.push({method:Mw.Get,operation:e.get}),e.post!=null&&t.push({method:Mw.Post,operation:e.post}),e.put!=null&&t.push({method:Mw.Put,operation:e.put}),e.delete!=null&&t.push({method:Mw.Delete,operation:e.delete}),e.patch!=null&&t.push({method:Mw.Patch,operation:e.patch}),e.head!=null&&t.push({method:Mw.Head,operation:e.head}),t}function Wjc({operation:e}){return Vr(e,[bn.WEBHOOK])??!1}function HYo(e){let t=Vr(e,bn.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Vr(e,bn.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function KYo(e){return Vr(e,bn.FERN_BASIC_AUTH)}function YYo(e,t,r,n){if(ei(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return JYo(i,t,r)}return JYo(e,t,r)}function JYo(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=Vr(e,c_.BEARER_FORMAT),i=Vr(e,bn.FERN_HEADER_AUTH);return Nw.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??Vr(e,bn.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=Vr(e,bn.FERN_BEARER_TOKEN);return Nw.bearer({tokenVariableName:n?.name??Vr(e,bn.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=KYo(e),i=HYo(e);return Nw.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return Nw.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return Nw.oauth({scopesEnum:$jc(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 $jc(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=gpe({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=ff(n);if(i.type==="enum")return i}}function XYo(e){return Vr(e,bn.BASE_PATH)}var Hjc=mt.record(mt.string(),mt.object({summary:mt.string().optional(),description:mt.string().optional()}));function ZYo({document:e,context:t}){return jmt(e,bn.GROUPS,Hjc,t.logger)}function eXo({context:e,document:t}){return Vr(t,bn.FERN_VERSION)??void 0}function tXo(e){let t=Vr(e,bn.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?Mmt({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}function rXo(e){let t=Vr(e,bn.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?Mmt({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}function nXo(e,t){let r=Vr(e,bn.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:py([n],t),title:i.title,schema:Mc.string({default:yUe(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}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var Kjc="webhooks";function iXo(e){return Vr(e,Kjc)??{}}var Hmt=class extends CUe{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 m_e({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}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 oXo(e){return Vr(e,bn.RESOLUTIONS)}function sXo({openapi:e}){let t=oXo(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=Jjc({openapi:e,schemaReference:o,schemaName:n.name}),e=aXo({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function Jjc({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 aXo({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(u=>t.startsWith(u)).sort((u,c)=>c.length-u.length)[0];if(i!=null){let u=n[i];if(u!=null){let c=r.replace(i,u);return aXo({openapi:e,replaceReference:t,schemaReference:c,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(u=>u.replaceAll("~1","/")),s=e;for(let u of o.slice(0,-1)){let c=s[u];if(c==null)return e;s=c}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}function cXo({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=sXo({openapi:e}),hJt();let o=new Hmt({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([U,q])=>{let z=YYo(q,n,t,o);return z==null?null:[U,z]}).filter(U=>U!==null)),a=e.security?.filter(U=>U!=null),u=new Set(Object.entries(s).map(([U,q])=>q.type==="basic"||q.type==="bearer"||q.type==="oauth"?"Authorization":q.type==="header"?q.headerName:null).filter(U=>U!=null)),c=nXo(e,r.preserveSchemaIds),l=tXo(e),p=rXo(e),d=r.audiences??[],f=[],m=[],h=new Hmt({document:e,taskContext:t,authHeaders:u,options:r,source:n,namespace:i});h.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([U,q])=>{if(q==null)return;let z=GYo(U,q,e,h);for(let Z of z){let oe=uXo({operation:Z});if(!(d.length>0&&!d.some(V=>oe.includes(V))))switch(Z.type){case"async":f.push(...Z.sync),f.push(...Z.async);break;case"http":f.push(...Z.value);break;case"streaming":f.push(...Z.streaming),Z.nonStreaming&&f.push(...Z.nonStreaming);break;case"webhook":m.push(...Z.value);break;default:xe(Z)}}}),Object.entries(iXo(e)).forEach(([U,q])=>{if(q==null)return;t.logger.debug(`Converting path ${U}`);let z=WYo(U,q,e,h);for(let Z of z){let oe=uXo({operation:Z});d.length>0&&!d.some(V=>oe.includes(V))||m.push(...Z.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([U,q])=>{let z=Vr(q,bn.SDK_NAMESPACE);if(!ei(q)){let Z=Vr(q,bn.IGNORE);if(Z!=null&&Z)return[];if(OYo.has(U))return[U,Va({...q,"x-fern-type-name":`${U}Body`},!1,!1,h,[U],n,z??i)]}return[U,Va(q,!1,!1,h,[U],n,z??i)]}).filter(U=>U.length>0)),A=Yjc(g,h,n),E=Xjc(A,h),v=Z9(),b={};for(let[U,q]of Object.entries(E)){let z=ff(q);if(h.isSchemaExcluded(U))continue;let Z=v.getUniqueSchemaId(U,h.logger,r.resolveSchemaCollisions);b[Z]=z}let I=new bpe(E,h.nonRequestReferencedSchemas,h),w=m.map(U=>{let z=U.examples;if(!r.disableExamples&&z.length===0){let Z=I.buildExample({schema:U.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Z!=null&&(z=[{name:void 0,description:void 0,payload:Z}])}return{...U,payload:ff(U.payload),examples:z}}),x=new yJt(E,h,l),C=f.map(U=>{let q=U.examples,z=q;if(!r.disableExamples&&(q.length===0||q.every(Vmt))){let V=x.buildEndpointExample(U);V.length>0&&(z=[...V,...q.filter(K=>!Vmt(K))])}let Z=U.request,oe=U.response;return{...U,request:Z?.type==="json"||Z?.type==="formUrlEncoded"?{...Z,schema:ff(Z.schema)}:Z,response:oe?.type==="json"?{...oe,schema:ff(oe.schema)}:oe,queryParameters:U.queryParameters.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,explode:V.explode,availability:V.availability,source:V.source})),pathParameters:U.pathParameters.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,variableReference:V.variableReference,availability:V.availability,source:V.source})),headers:U.headers.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,env:V.env,availability:V.availability,source:V.source})),examples:z,errors:fl(U.errors,V=>{let K=V.fullExamples?.map(be=>{let Ce=ype(be.value);if(Ce!=null)return{name:be.name,description:be.description,example:Ce}}).filter(ma);if(K?.length===0){let be=I.buildExample({schema:V.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});be!=null&&K.push({name:void 0,description:void 0,example:be})}return{generatedName:V.generatedName,nameOverride:V.nameOverride,schema:ff(V.schema),description:V.description,source:V.source,examples:K}}),retries:U.retries}});x.finalize();let _=ZYo({document:e,context:h});return{apiVersion:eXo({context:h,document:e}),basePath:XYo(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(_??{}).map(([U,q])=>[U,{summary:q.summary??void 0,description:q.description??void 0}])),servers:(e.servers??[]).map(U=>RJt(U,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(U=>[U.name,{id:U.name,description:U.description}])),orderedTagIds:e.tags?.map(U=>U.name)},endpoints:C,webhooks:w,channels:{},groupedSchemas:EUe(i,b),securitySchemes:s,security:a,hasEndpointsMarkedInternal:C.some(U=>U.internal),nonRequestReferencedSchemas:h.getReferencedSchemas(),variables:c,globalHeaders:l,idempotencyHeaders:p}}function Yjc(e,t,r){if(t.options.removeDiscriminantsFromSchemas===yn.RemoveDiscriminantsFromSchemas.Never)return e;let n={};for(let[i,o]of Object.entries(e)){if(o.type!=="object"){n[i]=o;continue}let s={$ref:`#/components/schemas/${i}`},a=t.getReferencesFromDiscriminatedUnion(s);if(a==null){n[i]=o;continue}if(t.getReferencedSchemas().has(i)){n[i]=o;continue}let c={...o,type:"object",properties:o.properties.filter(p=>!a.discriminants.has(p.key)),allOfPropertyConflicts:o.allOfPropertyConflicts.filter(p=>!a.discriminants.has(p.propertyKey)),source:r};n[i]=c;let l=lXo({schema:o,schemas:e});for(let p of[...new Set(l)]){let d=n[p]??e[p];d==null||d.type!=="object"||(n[p]={...d,type:"object",properties:d.properties.filter(f=>!a.discriminants.has(f.key)),allOfPropertyConflicts:d.allOfPropertyConflicts.filter(f=>!a.discriminants.has(f.propertyKey))})}}return n}function Xjc(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 c of i.properties)if(s.discriminants.has(c.key)){let l=s.discriminants.get(c.key);l!=null&&a.push({...c,schema:Fr.literal({nameOverride:void 0,generatedName:py([i.generatedName,l],t.options.preserveSchemaIds),title:void 0,value:wg.string(l),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(c);let u={...i,type:"object",properties:a};r[n]=u}return r}function lXo({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(...lXo({schema:i,schemas:t}))}return r}function jJt(e){return[...new Set(e)]}function uXo({operation:e}){let t=[];switch(e.type){case"async":t=jJt(e.async.flatMap(r=>r.audiences));break;case"http":t=jJt(e.value.flatMap(r=>r.audiences));break;case"streaming":t=jJt(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=jJt(e.value.flatMap(r=>r.audiences));break;default:xe(e)}return t}function T_e({context:e,documents:t,options:r}){let n={apiVersion:void 0,title:void 0,description:void 0,basePath: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:[],idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let s=o.source!=null?o.source:mS.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=cXo({taskContext:e,openApi:o.value,options:iM({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=nMc(n,a,iM({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let a=WJo({document:o.value,taskContext:e,options:iM({options:o.settings,overrides:r}),source:s,asyncApiOptions:Zjc({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(u=>({...u,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=MJt(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath),i++;break}default:xe(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?`
1496
+ `);try{vUe.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=kQc(t.request),n=QQc(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:iKn(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:iKn(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,tM.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,tM.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,tM.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,tM.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&&!t8(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&&!t8(f)&&(this.logger.debug(`Expected a primitive 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 u=[];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&&!t8(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&&u.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?e8(p.schema):Fr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Ii.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&&!t8(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&&u.push({name:p.header,value:f})}let c=[];t.request!=null&&t.response!=null?c=FQc(i,o):t.request!=null?c=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(c=o.map(([p,d])=>({id:p,request:void 0,response:d})));let l=t.examples.filter(p=>Vmt(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=>ma(p));return c.length===0?[eM.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:u,request:void 0,response:void 0,codeSamples:l})]:c.map(({id:p,request:d,response:f})=>eM.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:u,request:d,response:f,codeSamples:l}))}convertCodeSamples(t){return t.map(r=>"language"in r?q9.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):q9.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?Lw.Csharp:r.sdk,code:r.code})).filter(ma)}isSchemaRequired(t){return AJt(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function FQc(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(([u])=>u==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 u=0;u<t.length;u++){let[c,l]=t[u];c==null||n.has(u)||i===c&&(r.push({id:i,request:o,response:l}),c!=null&&n.add(u),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(([u])=>u==null)?.[1]??e[0]?.[1];a!=null&&r.push({id:o,request:a,response:s})}return r}function kQc(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:NQc(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function QQc(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 t8(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return t8(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return t8(e.value.value);default:return!1}case"null":return!0;default:xe(e)}}function NQc(e){return Fr.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:e8(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(ma),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})}var IUe=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new bpe(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 u=[];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&&!t8(f)&&(f=void 0),!(d&&f==null)&&f!=null&&u.push({name:p.name,value:f})}let c=[];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&&!t8(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let l=[];for(let p of a.messages){let d=t.getExampleMessageReference(p),f=t.resolveMessageReference({$ref:d}),m=ei(f.payload)?t.resolveSchemaReference(f.payload):f.payload,h=this.exampleTypeFactory.buildExample({schema:Va(m,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});h!=null&&l.push({messageType:p.type,payload:h,description:void 0})}s.push({name:a.summary,queryParameters:u,headers:c,description:a.description,messages:l})}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),u=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(u!=null&&!t8(u)&&(u=void 0),a&&u==null)return;u!=null&&i.push({name:s.name,value:u})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),u=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(u!=null&&!t8(u)&&(u=void 0),a&&u==null)return;u!=null&&o.push({name:s.name,value:u})}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 AJt(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var Q0={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 bJt(e){return Vr(e,Q0.FERN_EXAMPLES)??[]}function EJt(e,t){return t.includes("://")?t:`${e}://${t}`}function vJt(e){return e.startsWith("/")?e:"/"+e}function UJo({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[c,l]of Object.entries(i.components?.schemas??{})){let p=Va(l,!1,!1,e,[c],r,e.namespace);o[c]=p}let a=new IUe(o,e),u={};for(let[c,l]of Object.entries(i.servers??{})){let p=Vr(l,Q0.FERN_SERVER_NAME);u[c]={name:p??c,url:EJt(l.protocol,l.url)}}for(let[c,l]of Object.entries(i.channels??{})){let p=Vr(l,Q0.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${c} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(l.parameters!=null)for(let[A,E]of Object.entries(l.parameters??{})){let v=Vr(E,Q0.FERN_PARAMETER_NAME);d.push({name:A,description:E.description,parameterNameOverride:v,schema:E.schema!=null?Va(E.schema,!1,!1,e,t,r,e.namespace):Fr.primitive({schema:Ii.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:AS(E),source:r,explode:void 0})}let f=[],m=[];if(l.bindings?.ws!=null){if(l.bindings.ws.headers!=null){let A=l.bindings.ws.headers.required??[];for(let[E,v]of Object.entries(l.bindings.ws.headers.properties??{})){if(ei(v)){let x=e.resolveSchemaReference(v),C=A.includes(E),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];f.push({name:E,schema:Z5(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,env:void 0,availability:AS(x),source:r});continue}let b=A.includes(E),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!b]:[!b,!1];f.push({name:E,schema:Va(v,I,w,e,[...t,E],r,e.namespace),description:v.description,parameterNameOverride:void 0,env:void 0,availability:AS(v),source:r})}}if(l.bindings.ws.query!=null){let A=l.bindings.ws.query.required??[];for(let[E,v]of Object.entries(l.bindings.ws.query.properties??{})){if(ei(v)){let x=e.resolveSchemaReference(v),C=A.includes(E),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];m.push({name:E,schema:Z5(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,availability:AS(x),source:r,explode:void 0});continue}let b=A.includes(E),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!b]:[!b,!1];m.push({name:E,schema:Va(v,I,w,e,[...t,E],r,e.namespace),description:v.description,parameterNameOverride:void 0,availability:AS(v),source:r,explode:void 0})}}}let h;l.publish!=null&&("oneOf"in l.publish.message?h=MJo({generatedName:l.publish.operationId??"PublishEvent",event:l.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):h=LJo({action:"Publish",channelPath:c,message:l.publish.message,context:e,source:r}));let g;if(l.subscribe!=null&&("oneOf"in l.subscribe.message?g=MJo({generatedName:l.subscribe.operationId??"SubscribeEvent",event:l.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=LJo({action:"Subscribe",channelPath:c,message:l.subscribe.message,context:e,source:r})),f.length>0||m.length>0||h!=null||g!=null){let A=bJt(l),E=[];if(A.length>0)E=a.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:A,handshake:{headers:f,queryParameters:m},source:r,namespace:e.namespace});else{let w=[];h!=null&&w.push({type:"publish",payload:h}),g!=null&&w.push({type:"subscribe",payload:g});let x=a.buildWebsocketSessionExample({handshake:{headers:f,queryParameters:m},messages:w});x!=null&&E.push(x)}let v=Vr(l,Q0.FERN_CHANNEL_ADDRESS),b=v??vJt(c),I=[];h!=null&&I.push({origin:"client",name:"publish",body:ff(h),methodName:void 0}),g!=null&&I.push({origin:"server",name:"subscribe",body:ff(g),methodName:void 0}),s[c]={audiences:Vr(l,bn.AUDIENCES)??[],handshake:{headers:f.map(w=>({...w,schema:ff(w.schema),env:w.env})),queryParameters:m.map(w=>({...w,schema:ff(w.schema)})),pathParameters:d.map(w=>({...w,schema:ff(w.schema)}))},groupName:e.resolveGroupName([Vr(l,Q0.FERN_SDK_GROUP_NAME)??c]),messages:I,servers:(l.servers?.map(w=>u[w])??Object.values(u)).filter(w=>w!=null&&w.name!=null).map(w=>({...w,name:w.name})),summary:Vr(l,Q0.FERN_DISPLAY_NAME),connectMethodName:Vr(l,Q0.FERN_SDK_METHOD_NAME),path:b,description:l.description,examples:E,source:r}}}return{groupedSchemas:EUe(e.namespace,o),channels:s??void 0,servers:Object.values(u).map(c=>({...c,name:c.name})),basePath:Vr(i,Q0.BASE_PATH)}}function MJo({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=[],u=[];for(let c of t.message.oneOf){let l,p={type:"notFound"};if(ei(c)){let d=r.resolveMessageReference(c);!ei(d.payload)&&s.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,l={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):l=d.payload}else l=c;u.push(p),a.push(l)}return Ape({description:t.description??t.message.description,availability:AS(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"?u:[]})}}function LJo({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return ei(r.payload)&&(o=n.resolveSchemaReference(r.payload)),Va(o,!1,!1,n,[t,e],i,n.namespace)}}var IJt=class extends bUe{getExampleMessageReference(t){let r=t.channelId??this.getDefaultChannelId();if(r==null)throw new Error("Cannot resolve example message reference: no channelId provided and no channels found in document");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 Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new Error("Cannot resolve message reference: message is null or undefined");if(!t.$ref)throw new Error("Cannot resolve message reference: message.$ref is undefined or empty");if(t.$ref.startsWith(n)){let u=t.$ref.split("/"),c=u[2],l=u[4],p=c?.replace(/~1/g,"/").replace(/~0/g,"~");if(p==null||l==null||!this.document.channels?.[p])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${p}`);let f=this.document.channels[p].messages?.[l];if(f==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in f&&!r?this.resolveMessageReference(f):{...f,name:l}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let s=t.$ref.substring(i.length),a=o.messages[s];if(a==null)throw new Error(`${t.$ref} is undefined`);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}};Ci();var zJo="#/channels/",VJo="#/servers/",oKn="$message.";function GJo({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){hJt();let o={},s={},a={},u=[],c={};e.logger.debug("Parsing V3 AsyncAPI...");let l=Z9();for(let[x,C]of Object.entries(i.components?.schemas??{})){let _=l.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);o[_]=Va(C,!1,!1,e,[_],r,e.namespace)}for(let[x,C]of Object.entries(i.channels??{}))if(s[x]||(s[x]={}),C.messages)for(let[_,R]of Object.entries(C.messages))if(a[_]||(a[_]=[]),e.isReferenceObject(R)){let U=e.resolveMessageReference(R);a[_].push({channelId:x,payload:U.payload})}else e.isMessageWithPayload(R)&&a[_].push({channelId:x,payload:R.payload});for(let[x,C]of Object.entries(a))if(C.length===1){let _=C[0],R=_.channelId;s[R]=s[R]||{},s[R][x]=Va(_.payload,!1,!1,e,[x],r,e.namespace)}else{u.push(x);for(let{channelId:_,payload:R}of C){let U=`${_}_${x}`;s[_]||(s[_]={}),s[_][U]=Va(R,!1,!1,e,[U],r,e.namespace)}}let p={},d=Z9();for(let[x,C]of Object.entries(s))for(let[_,R]of Object.entries(C)){let U=d.getUniqueSchemaId(_,e.logger,e.options.resolveSchemaCollisions);p[U]=R}let f=new IUe({...o,...p},e),m={};for(let[x,C]of Object.entries(i.servers??{})){let _=Vr(C,Q0.FERN_SERVER_NAME);m[x]={name:_??x,url:EJt(C.protocol,C.host)}}let h={},g=Object.keys(i.channels??{});for(let[x,C]of Object.entries(i.operations??{})){if(Vr(C,Q0.IGNORE))continue;let _;if(C.channel==null||!("$ref"in C.channel)||C.channel.$ref==null)if(g.length===1&&g[0]!=null)_=g[0];else continue;else _=MQc(C);h[_]||(h[_]={subscribe:[],publish:[],__parsedMessages:[]});let R=Vr(C,Q0.FERN_SDK_METHOD_NAME);if(!C.messages||!Array.isArray(C.messages))continue;let U=C.messages.filter(z=>z!=null&&z.$ref!=null).map(z=>({ref:z,methodName:R})),q=h[_];if(q==null)throw new Error(`Internal error: channelEvents["${_}"] is unexpectedly undefined for operation ${x}`);if(C.action==="receive")q.subscribe.push(...U);else if(C.action==="send")q.publish.push(...U);else throw new Error(`Operation ${x} has an invalid action: ${C.action}`)}for(let[x,C]of Object.entries(h)){let _=[];_.push(...qJo({messages:C.subscribe,channelPath:x,origin:"server",messageSchemas:s[x]??{},duplicatedMessageIds:u,context:e})),_.push(...qJo({messages:C.publish,channelPath:x,origin:"client",messageSchemas:s[x]??{},duplicatedMessageIds:u,context:e})),h[x]!=null&&(h[x].__parsedMessages=_)}for(let[x,C]of Object.entries(i.channels??{})){if(Vr(C,Q0.IGNORE))continue;let _=[],R=[],U=[];if(C.parameters!=null)for(let[q,z]of Object.entries(C.parameters)){let Z=e.isReferenceObject(z)?e.resolveParameterReference(z):z,{type:oe,parameterKey:V}=Z.location!=null?LQc(Z.location):{type:C.address?.includes(`={${q}}`)?"query":"path",parameterKey:q},K=Vr(Z,Q0.FERN_PARAMETER_OPTIONAL),be=Nc(Ln(x))+Nc(Ln(q)),Ce=Z.schema!=null?ei(Z.schema)?Z5(Z.schema,!1,!1,e,[V],void 0,r,e.namespace):Va(Z.schema,!1,!1,e,[V],r,e.namespace):Va({...Z,type:"string",title:be,example:Z.examples?.[0],default:Z.default,enum:Z.enum,required:void 0},!1,!1,e,[V],r,e.namespace),J=K?Fr.optional({value:Ce,description:void 0,availability:void 0,generatedName:"",title:be,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Ce,H={name:V,description:Z.description,parameterNameOverride:void 0,schema:J,variableReference:void 0,availability:AS(z),source:r,explode:void 0};oe==="header"?_.push({...H,env:void 0}):oe==="path"?R.push(H):(oe==="payload"||oe==="query")&&U.push(H)}if(_.length>0||U.length>0||h[x]!=null&&(h[x].publish!=null||h[x].subscribe!=null)){let q=bJt(C),z=h[x]?.__parsedMessages??[],Z=[];try{if(q.length>0)Z=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:q,handshake:{headers:_,queryParameters:U},source:r,namespace:e.namespace});else{let Ce=[],{examplePublishMessage:J,exampleSubscribeMessage:H}=zQc({messages:z,messageSchemas:s[x]??{}});J!=null&&Ce.push(J),H!=null&&Ce.push(H);let ge=f.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:U},messages:Ce});ge!=null&&Z.push(ge)}}catch(Ce){e.logger.warn(`Failed to build examples for channel ${x}: ${Ce instanceof Error?Ce.message:String(Ce)}`)}let oe=Vr(C,Q0.FERN_SDK_GROUP_NAME),V=Vr(C,Q0.FERN_SDK_METHOD_NAME),K=(C.servers?.map(Ce=>UQc(m,Ce))??Object.values(m)).map(Ce=>({...Ce,name:Ce.name})),be=C.address?.split("?")[0]??vJt(x);c[x]={audiences:Vr(C,bn.AUDIENCES)??[],handshake:{headers:_.map(Ce=>({...Ce,schema:ff(Ce.schema),env:Ce.env})),queryParameters:U.map(Ce=>({...Ce,schema:ff(Ce.schema)})),pathParameters:R.map(Ce=>({...Ce,parameterNameOverride:void 0,schema:ff(Ce.schema)}))},groupName:e.resolveGroupName(typeof oe=="string"?[oe]:oe??[x]),messages:z,summary:Vr(C,Q0.FERN_DISPLAY_NAME),connectMethodName:V,servers:K,path:be,description:C.description,examples:Z,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${x} as it does not qualify for inclusion (no headers, query params, or operations)`)}let A={...o,...p},E={},v=Z9();for(let[x,C]of Object.entries(A)){let _=v.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);E[_]=ff(C)}let b=EUe(e.namespace,o),I=Object.values(m).map(x=>({...x,name:x.name})),w=Vr(i,Q0.BASE_PATH);return{groupedSchemas:b,channels:c,servers:I,basePath:w}}function jQc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function MQc(e){if(!e.channel)throw new Error("Operation is missing required 'channel' field");if(!e.channel.$ref)throw new Error("Operation channel is missing required '$ref' field");if(!e.channel.$ref.startsWith(zJo))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return jQc(e.channel.$ref.substring(zJo.length))}function LQc(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(oKn))throw new Error(`Invalid location format: ${e}; expected ${oKn} prefix`);let n=t.substring(oKn.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function UQc(e,t){if(!t.$ref.startsWith(VJo))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(VJo.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function qJo({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,u)=>{try{let l=o.resolveMessageReference(a.ref,!0).name;i.includes(l)&&(l=`${t}_${l}`);let p=n[l];p!=null&&s.push({origin:r,name:l??`${r}Message${u+1}`,body:ff(p),methodName:a.methodName})}catch(c){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${c instanceof Error?c.message:String(c)}`)}}),s}function zQc({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}}function WJo({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 u=new gJt({document:a,taskContext:t,options:r,namespace:o});return UJo({context:u,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,u=new IJt({document:a,taskContext:t,options:r,namespace:o});return GJo({context:u,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}Qt();Ci();Ci();function $Jo(e){return Vr(e,bn.ASYNC_CONFIG)}var HJo="$request.";function KJo(e){let t=Vr(e,bn.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json",terminator:void 0}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format,terminator:t.terminator}:{type:"streamCondition",format:t.format??"json",terminator:t.terminator,streamDescription:t["stream-description"],streamConditionProperty:VQc(t["stream-condition"]),streamRequestName:t["stream-request-name"],responseStream:t["response-stream"],response:t.response}}function VQc(e){return e.startsWith(HJo)?e.slice(HJo.length):e}function JJo(e){let t=e;if(t.cursor!=null)return yI.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return yI.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return yI.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return yI.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 yI.custom({results:i.results})}throw new Error("Invalid pagination extension")}function YJo(e,t){let r=Vr(t,bn.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=Vr(e,bn.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:JJo(n)}return JJo(r)}}function XJo(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:wUe(n,t)}}}function ZJo(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function qQc(e){return e.includes("json")||e==="*/*"}function sKn({content:e,context:t}){for(let[r,n]of Object.entries(e))if(wJt({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function wJt({mediaType:e,mediaTypeObject:t,context:r}){if(!qQc(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:wUe(t,r)}}function CJt({content:e,context:t}){let r=sKn({content:e,context:t});if(!r)return;let[n,i]=r;return wJt({mediaType:n,mediaTypeObject:i,context:t})}function eYo(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:wUe(n,t)}}}function wUe(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=Vr(e,c_.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=ei(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}Qt();Qt();function tYo(e){let t=GQc(e),r={};return aKn({obj:t,occurrences:r,breadcrumbs:[]}),r}function aKn({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)aKn({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)aKn({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function GQc(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?qmt(r.get):void 0,put:r?.put!=null?qmt(r.put):void 0,post:r?.post!=null?qmt(r.post):void 0,patch:r?.patch!=null?qmt(r.patch):void 0,delete:r?.delete!=null?qmt(r.delete):void 0}]))}}function qmt(e){return{...e,requestBody:e.requestBody!=null?ei(e.requestBody)?e.requestBody:WQc(e.requestBody):void 0}}function WQc(e){let t,r;for(let n in e.content){let i=af.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[af.MULTIPART_FORM_DATA]:r}}:e}var xJt=class{endpoints;parser=new xre;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 rYo="#/components/parameters/",nYo="#/components/responses/",iYo="#/components/examples/",oYo="#/components/requestBodies/",sYo="#/components/securitySchemes/",CUe=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}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=tYo(t),this.options=i,this.source=o,this.filter=new xJt({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"}):(ei(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(rYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(rYo.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(oYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(oYo.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(nYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(nYo.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(iYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(iYo.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(sYo))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(sYo.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return ei(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;for(let[r,n]of Object.entries(this.document.components.schemas))!n||ei(n)||t.set(r,Vr(n,bn.SDK_NAMESPACE)||this.namespace);return t}};var m_e=class extends CUe{constructor({document:t,taskContext:r,options:n,source:i,namespace:o}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o})}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){}};Qt();var TJt=require("fs"),DJt=require("path");var mt={};Y(mt,{BRAND:()=>yNc,DIRTY:()=>h_e,EMPTY_PATH:()=>JQc,INVALID:()=>tu,NEVER:()=>rjc,OK:()=>yS,ParseStatus:()=>l_,Schema:()=>Nl,ZodAny:()=>Ipe,ZodArray:()=>sne,ZodBigInt:()=>A_e,ZodBoolean:()=>y_e,ZodBranded:()=>Wmt,ZodCatch:()=>O_e,ZodDate:()=>b_e,ZodDefault:()=>B_e,ZodDiscriminatedUnion:()=>BJt,ZodEffects:()=>uM,ZodEnum:()=>__e,ZodError:()=>HD,ZodFirstPartyTypeKind:()=>Ou,ZodFunction:()=>PJt,ZodIntersection:()=>w_e,ZodIssueCode:()=>on,ZodLazy:()=>C_e,ZodLiteral:()=>x_e,ZodMap:()=>PUe,ZodNaN:()=>DUe,ZodNativeEnum:()=>S_e,ZodNever:()=>r8,ZodNull:()=>v_e,ZodNullable:()=>nG,ZodNumber:()=>g_e,ZodObject:()=>KD,ZodOptional:()=>sM,ZodParsedType:()=>Lo,ZodPipeline:()=>$mt,ZodPromise:()=>wpe,ZodReadonly:()=>P_e,ZodRecord:()=>OJt,ZodSchema:()=>Nl,ZodSet:()=>TUe,ZodString:()=>vpe,ZodSymbol:()=>BUe,ZodTransformer:()=>uM,ZodTuple:()=>rG,ZodType:()=>Nl,ZodUndefined:()=>E_e,ZodUnion:()=>I_e,ZodUnknown:()=>one,ZodVoid:()=>OUe,addIssueToContext:()=>lo,any:()=>SNc,array:()=>TNc,bigint:()=>INc,boolean:()=>AYo,coerce:()=>tjc,custom:()=>mYo,date:()=>wNc,datetimeRegex:()=>fYo,defaultErrorMap:()=>nne,discriminatedUnion:()=>kNc,effect:()=>$Nc,enum:()=>qNc,function:()=>UNc,getErrorMap:()=>xUe,getParsedType:()=>tG,instanceof:()=>ENc,intersection:()=>QNc,isAborted:()=>_Jt,isAsync:()=>_Ue,isDirty:()=>SJt,isValid:()=>Epe,late:()=>bNc,lazy:()=>zNc,literal:()=>VNc,makeIssue:()=>Gmt,map:()=>MNc,nan:()=>vNc,nativeEnum:()=>GNc,never:()=>ONc,null:()=>_Nc,nullable:()=>KNc,number:()=>gYo,object:()=>DNc,objectUtil:()=>uKn,oboolean:()=>ejc,onumber:()=>ZNc,optional:()=>HNc,ostring:()=>XNc,pipeline:()=>YNc,preprocess:()=>JNc,promise:()=>WNc,quotelessJson:()=>$Qc,record:()=>jNc,set:()=>LNc,setErrorMap:()=>KQc,strictObject:()=>RNc,string:()=>hYo,symbol:()=>CNc,transformer:()=>$Nc,tuple:()=>NNc,undefined:()=>xNc,union:()=>FNc,unknown:()=>BNc,util:()=>bp,void:()=>PNc});var bp;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(bp||(bp={}));var uKn;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(uKn||(uKn={}));var Lo=bp.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tG=e=>{switch(typeof e){case"undefined":return Lo.undefined;case"string":return Lo.string;case"number":return Number.isNaN(e)?Lo.nan:Lo.number;case"boolean":return Lo.boolean;case"function":return Lo.function;case"bigint":return Lo.bigint;case"symbol":return Lo.symbol;case"object":return Array.isArray(e)?Lo.array:e===null?Lo.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Lo.promise:typeof Map<"u"&&e instanceof Map?Lo.map:typeof Set<"u"&&e instanceof Set?Lo.set:typeof Date<"u"&&e instanceof Date?Lo.date:Lo.object;default:return Lo.unknown}};var on=bp.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$Qc=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),HD=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let c=s.path[u];u===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,bp.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};HD.create=e=>new HD(e);var HQc=(e,t)=>{let r;switch(e.code){case on.invalid_type:e.received===Lo.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case on.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,bp.jsonStringifyReplacer)}`;break;case on.unrecognized_keys:r=`Unrecognized key(s) in object: ${bp.joinValues(e.keys,", ")}`;break;case on.invalid_union:r="Invalid input";break;case on.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${bp.joinValues(e.options)}`;break;case on.invalid_enum_value:r=`Invalid enum value. Expected ${bp.joinValues(e.options)}, received '${e.received}'`;break;case on.invalid_arguments:r="Invalid function arguments";break;case on.invalid_return_type:r="Invalid function return type";break;case on.invalid_date:r="Invalid date";break;case on.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:bp.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case on.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case on.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case on.custom:r="Invalid input";break;case on.invalid_intersection_types:r="Intersection results could not be merged";break;case on.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case on.not_finite:r="Number must be finite";break;default:r=t.defaultError,bp.assertNever(e)}return{message:r}},nne=HQc;var aYo=nne;function KQc(e){aYo=e}function xUe(){return aYo}var Gmt=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},JQc=[];function lo(e,t){let r=xUe(),n=Gmt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===nne?void 0:nne].filter(i=>!!i)});e.common.issues.push(n)}var l_=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return tu;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return tu;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},tu=Object.freeze({status:"aborted"}),h_e=e=>({status:"dirty",value:e}),yS=e=>({status:"valid",value:e}),_Jt=e=>e.status==="aborted",SJt=e=>e.status==="dirty",Epe=e=>e.status==="valid",_Ue=e=>typeof Promise<"u"&&e instanceof Promise;var Zs;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Zs||(Zs={}));var aM=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},uYo=(e,t)=>{if(Epe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new HD(e.common.issues);return this._error=r,this._error}}};function ml(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:u}=e;return s.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}var Nl=class{get description(){return this._def.description}_getType(t){return tG(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:tG(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new l_,ctx:{common:t.parent.common,data:t.data,parsedType:tG(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(_Ue(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)},i=this._parseSync({data:t,path:n.path,parent:n});return uYo(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Epe(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Epe(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:tG(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(_Ue(i)?i:Promise.resolve(i));return uYo(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:on.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new uM({schema:this,typeName:Ou.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return sM.create(this,this._def)}nullable(){return nG.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sne.create(this)}promise(){return wpe.create(this,this._def)}or(t){return I_e.create([this,t],this._def)}and(t){return w_e.create(this,t,this._def)}transform(t){return new uM({...ml(this._def),schema:this,typeName:Ou.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new B_e({...ml(this._def),innerType:this,defaultValue:r,typeName:Ou.ZodDefault})}brand(){return new Wmt({typeName:Ou.ZodBranded,type:this,...ml(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new O_e({...ml(this._def),innerType:this,catchValue:r,typeName:Ou.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return $mt.create(this,t)}readonly(){return P_e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},YQc=/^c[^\s-]{8,}$/i,XQc=/^[0-9a-z]+$/,ZQc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,eNc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,tNc=/^[a-z0-9_-]{21}$/i,rNc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nNc=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,iNc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oNc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cKn,sNc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aNc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,uNc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cNc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lNc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pNc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lYo="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fNc=new RegExp(`^${lYo}$`);function pYo(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function dNc(e){return new RegExp(`^${pYo(e)}$`)}function fYo(e){let t=`${lYo}T${pYo(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function mNc(e,t){return!!((t==="v4"||!t)&&sNc.test(e)||(t==="v6"||!t)&&uNc.test(e))}function hNc(e,t){if(!rNc.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function gNc(e,t){return!!((t==="v4"||!t)&&aNc.test(e)||(t==="v6"||!t)&&cNc.test(e))}var vpe=class e extends Nl{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Lo.string){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.string,received:o.parsedType}),tu}let n=new l_,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?lo(i,{code:on.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&lo(i,{code:on.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")iNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"email",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")cKn||(cKn=new RegExp(oNc,"u")),cKn.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"emoji",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")eNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"uuid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")tNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"nanoid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")YQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cuid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")XQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cuid2",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ZQc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"ulid",code:on.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),lo(i,{validation:"url",code:on.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"regex",code:on.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?fYo(o).test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?dNc(o).test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{code:on.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?nNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"duration",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?mNc(t.data,o.version)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"ip",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?hNc(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"jwt",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?gNc(t.data,o.version)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"cidr",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?lNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"base64",code:on.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?pNc.test(t.data)||(i=this._getOrReturnCtx(t,i),lo(i,{validation:"base64url",code:on.invalid_string,message:o.message}),n.dirty()):bp.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:on.invalid_string,...Zs.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Zs.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Zs.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Zs.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Zs.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Zs.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Zs.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Zs.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Zs.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Zs.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Zs.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Zs.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Zs.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Zs.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...Zs.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Zs.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Zs.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Zs.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Zs.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Zs.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Zs.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Zs.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Zs.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Zs.errToObj(r)})}nonempty(t){return this.min(1,Zs.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};vpe.create=e=>new vpe({checks:[],typeName:Ou.ZodString,coerce:e?.coerce??!1,...ml(e)});function ANc(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var g_e=class e extends Nl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Lo.number){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.number,received:o.parsedType}),tu}let n,i=new l_;for(let o of this._def.checks)o.kind==="int"?bp.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),lo(n,{code:on.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?ANc(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_finite,message:o.message}),i.dirty()):bp.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Zs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Zs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Zs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Zs.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Zs.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Zs.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Zs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Zs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Zs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Zs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Zs.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Zs.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Zs.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Zs.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&bp.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};g_e.create=e=>new g_e({checks:[],typeName:Ou.ZodNumber,coerce:e?.coerce||!1,...ml(e)});var A_e=class e extends Nl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Lo.bigint)return this._getInvalidInput(t);let n,i=new l_;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),lo(n,{code:on.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):bp.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return lo(r,{code:on.invalid_type,expected:Lo.bigint,received:r.parsedType}),tu}gte(t,r){return this.setLimit("min",t,!0,Zs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Zs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Zs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Zs.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Zs.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Zs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Zs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Zs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Zs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Zs.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};A_e.create=e=>new A_e({checks:[],typeName:Ou.ZodBigInt,coerce:e?.coerce??!1,...ml(e)});var y_e=class extends Nl{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Lo.boolean){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.boolean,received:n.parsedType}),tu}return yS(t.data)}};y_e.create=e=>new y_e({typeName:Ou.ZodBoolean,coerce:e?.coerce||!1,...ml(e)});var b_e=class e extends Nl{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Lo.date){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_type,expected:Lo.date,received:o.parsedType}),tu}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return lo(o,{code:on.invalid_date}),tu}let n=new l_,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),lo(i,{code:on.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):bp.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Zs.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Zs.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};b_e.create=e=>new b_e({checks:[],coerce:e?.coerce||!1,typeName:Ou.ZodDate,...ml(e)});var BUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.symbol){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.symbol,received:n.parsedType}),tu}return yS(t.data)}};BUe.create=e=>new BUe({typeName:Ou.ZodSymbol,...ml(e)});var E_e=class extends Nl{_parse(t){if(this._getType(t)!==Lo.undefined){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.undefined,received:n.parsedType}),tu}return yS(t.data)}};E_e.create=e=>new E_e({typeName:Ou.ZodUndefined,...ml(e)});var v_e=class extends Nl{_parse(t){if(this._getType(t)!==Lo.null){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.null,received:n.parsedType}),tu}return yS(t.data)}};v_e.create=e=>new v_e({typeName:Ou.ZodNull,...ml(e)});var Ipe=class extends Nl{constructor(){super(...arguments),this._any=!0}_parse(t){return yS(t.data)}};Ipe.create=e=>new Ipe({typeName:Ou.ZodAny,...ml(e)});var one=class extends Nl{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yS(t.data)}};one.create=e=>new one({typeName:Ou.ZodUnknown,...ml(e)});var r8=class extends Nl{_parse(t){let r=this._getOrReturnCtx(t);return lo(r,{code:on.invalid_type,expected:Lo.never,received:r.parsedType}),tu}};r8.create=e=>new r8({typeName:Ou.ZodNever,...ml(e)});var OUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.undefined){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.void,received:n.parsedType}),tu}return yS(t.data)}};OUe.create=e=>new OUe({typeName:Ou.ZodVoid,...ml(e)});var sne=class e extends Nl{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Lo.array)return lo(r,{code:on.invalid_type,expected:Lo.array,received:r.parsedType}),tu;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(lo(r,{code:s?on.too_big:on.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(lo(r,{code:on.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(lo(r,{code:on.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new aM(r,s,r.path,a)))).then(s=>l_.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new aM(r,s,r.path,a)));return l_.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Zs.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Zs.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Zs.toString(r)}})}nonempty(t){return this.min(1,t)}};sne.create=(e,t)=>new sne({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ou.ZodArray,...ml(t)});function SUe(e){if(e instanceof KD){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=sM.create(SUe(n))}return new KD({...e._def,shape:()=>t})}else return e instanceof sne?new sne({...e._def,type:SUe(e.element)}):e instanceof sM?sM.create(SUe(e.unwrap())):e instanceof nG?nG.create(SUe(e.unwrap())):e instanceof rG?rG.create(e.items.map(t=>SUe(t))):e}var KD=class e extends Nl{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=bp.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Lo.object){let c=this._getOrReturnCtx(t);return lo(c,{code:on.invalid_type,expected:Lo.object,received:c.parsedType}),tu}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof r8&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let u=[];for(let c of s){let l=o[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new aM(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof r8){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(lo(i,{code:on.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new aM(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>l_.mergeObjectSync(n,c)):l_.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return Zs.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Zs.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ou.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of bp.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of bp.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return SUe(this)}partial(t){let r={};for(let n of bp.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of bp.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof sM;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return dYo(bp.objectKeys(this.shape))}};KD.create=(e,t)=>new KD({shape:()=>e,unknownKeys:"strip",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});KD.strictCreate=(e,t)=>new KD({shape:()=>e,unknownKeys:"strict",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});KD.lazycreate=(e,t)=>new KD({shape:e,unknownKeys:"strip",catchall:r8.create(),typeName:Ou.ZodObject,...ml(t)});var I_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new HD(a.ctx.common.issues));return lo(r,{code:on.invalid_union,unionErrors:s}),tu}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new HD(u));return lo(r,{code:on.invalid_union,unionErrors:a}),tu}}get options(){return this._def.options}};I_e.create=(e,t)=>new I_e({options:e,typeName:Ou.ZodUnion,...ml(t)});var ine=e=>e instanceof C_e?ine(e.schema):e instanceof uM?ine(e.innerType()):e instanceof x_e?[e.value]:e instanceof __e?e.options:e instanceof S_e?bp.objectValues(e.enum):e instanceof B_e?ine(e._def.innerType):e instanceof E_e?[void 0]:e instanceof v_e?[null]:e instanceof sM?[void 0,...ine(e.unwrap())]:e instanceof nG?[null,...ine(e.unwrap())]:e instanceof Wmt||e instanceof P_e?ine(e.unwrap()):e instanceof O_e?ine(e._def.innerType):[],BJt=class e extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.object)return lo(r,{code:on.invalid_type,expected:Lo.object,received:r.parsedType}),tu;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(lo(r,{code:on.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),tu)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=ine(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Ou.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...ml(n)})}};function lKn(e,t){let r=tG(e),n=tG(t);if(e===t)return{valid:!0,data:e};if(r===Lo.object&&n===Lo.object){let i=bp.objectKeys(t),o=bp.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let u=lKn(e[a],t[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(r===Lo.array&&n===Lo.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],u=lKn(s,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===Lo.date&&n===Lo.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var w_e=class extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(_Jt(o)||_Jt(s))return tu;let a=lKn(o.value,s.value);return a.valid?((SJt(o)||SJt(s))&&r.dirty(),{status:r.value,value:a.data}):(lo(n,{code:on.invalid_intersection_types}),tu)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};w_e.create=(e,t,r)=>new w_e({left:e,right:t,typeName:Ou.ZodIntersection,...ml(r)});var rG=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.array)return lo(n,{code:on.invalid_type,expected:Lo.array,received:n.parsedType}),tu;if(n.data.length<this._def.items.length)return lo(n,{code:on.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tu;!this._def.rest&&n.data.length>this._def.items.length&&(lo(n,{code:on.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new aM(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>l_.mergeArray(r,s)):l_.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rG.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rG({items:e,typeName:Ou.ZodTuple,rest:null,...ml(t)})};var OJt=class e extends Nl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.object)return lo(n,{code:on.invalid_type,expected:Lo.object,received:n.parsedType}),tu;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new aM(n,a,n.path,a)),value:s._parse(new aM(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?l_.mergeObjectAsync(r,i):l_.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Nl?new e({keyType:t,valueType:r,typeName:Ou.ZodRecord,...ml(n)}):new e({keyType:vpe.create(),valueType:t,typeName:Ou.ZodRecord,...ml(r)})}},PUe=class extends Nl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.map)return lo(n,{code:on.invalid_type,expected:Lo.map,received:n.parsedType}),tu;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new aM(n,a,n.path,[c,"key"])),value:o._parse(new aM(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return tu;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of s){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return tu;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};PUe.create=(e,t,r)=>new PUe({valueType:t,keyType:e,typeName:Ou.ZodMap,...ml(r)});var TUe=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Lo.set)return lo(n,{code:on.invalid_type,expected:Lo.set,received:n.parsedType}),tu;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(lo(n,{code:on.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(lo(n,{code:on.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(u){let c=new Set;for(let l of u){if(l.status==="aborted")return tu;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>o._parse(new aM(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:Zs.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Zs.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};TUe.create=(e,t)=>new TUe({valueType:e,minSize:null,maxSize:null,typeName:Ou.ZodSet,...ml(t)});var PJt=class e extends Nl{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.function)return lo(r,{code:on.invalid_type,expected:Lo.function,received:r.parsedType}),tu;function n(a,u){return Gmt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xUe(),nne].filter(c=>!!c),issueData:{code:on.invalid_arguments,argumentsError:u}})}function i(a,u){return Gmt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xUe(),nne].filter(c=>!!c),issueData:{code:on.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof wpe){let a=this;return yS(async function(...u){let c=new HD([]),l=await a._def.args.parseAsync(u,o).catch(f=>{throw c.addIssue(n(u,f)),c}),p=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(p,o).catch(f=>{throw c.addIssue(i(p,f)),c})})}else{let a=this;return yS(function(...u){let c=a._def.args.safeParse(u,o);if(!c.success)throw new HD([n(u,c.error)]);let l=Reflect.apply(s,this,c.data),p=a._def.returns.safeParse(l,o);if(!p.success)throw new HD([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rG.create(t).rest(one.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||rG.create([]).rest(one.create()),returns:r||one.create(),typeName:Ou.ZodFunction,...ml(n)})}},C_e=class extends Nl{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};C_e.create=(e,t)=>new C_e({getter:e,typeName:Ou.ZodLazy,...ml(t)});var x_e=class extends Nl{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return lo(r,{received:r.data,code:on.invalid_literal,expected:this._def.value}),tu}return{status:"valid",value:t.data}}get value(){return this._def.value}};x_e.create=(e,t)=>new x_e({value:e,typeName:Ou.ZodLiteral,...ml(t)});function dYo(e,t){return new __e({values:e,typeName:Ou.ZodEnum,...ml(t)})}var __e=class e extends Nl{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return lo(r,{expected:bp.joinValues(n),received:r.parsedType,code:on.invalid_type}),tu}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return lo(r,{received:r.data,code:on.invalid_enum_value,options:n}),tu}return yS(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};__e.create=dYo;var S_e=class extends Nl{_parse(t){let r=bp.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Lo.string&&n.parsedType!==Lo.number){let i=bp.objectValues(r);return lo(n,{expected:bp.joinValues(i),received:n.parsedType,code:on.invalid_type}),tu}if(this._cache||(this._cache=new Set(bp.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=bp.objectValues(r);return lo(n,{received:n.data,code:on.invalid_enum_value,options:i}),tu}return yS(t.data)}get enum(){return this._def.values}};S_e.create=(e,t)=>new S_e({values:e,typeName:Ou.ZodNativeEnum,...ml(t)});var wpe=class extends Nl{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Lo.promise&&r.common.async===!1)return lo(r,{code:on.invalid_type,expected:Lo.promise,received:r.parsedType}),tu;let n=r.parsedType===Lo.promise?r.data:Promise.resolve(r.data);return yS(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};wpe.create=(e,t)=>new wpe({type:e,typeName:Ou.ZodPromise,...ml(t)});var uM=class extends Nl{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ou.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{lo(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return tu;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?tu:u.status==="dirty"?h_e(u.value):r.value==="dirty"?h_e(u.value):u});{if(r.value==="aborted")return tu;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?tu:a.status==="dirty"?h_e(a.value):r.value==="dirty"?h_e(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?tu:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?tu:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Epe(s))return tu;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Epe(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):tu);bp.assertNever(i)}};uM.create=(e,t,r)=>new uM({schema:e,typeName:Ou.ZodEffects,effect:t,...ml(r)});uM.createWithPreprocess=(e,t,r)=>new uM({schema:t,effect:{type:"preprocess",transform:e},typeName:Ou.ZodEffects,...ml(r)});var sM=class extends Nl{_parse(t){return this._getType(t)===Lo.undefined?yS(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};sM.create=(e,t)=>new sM({innerType:e,typeName:Ou.ZodOptional,...ml(t)});var nG=class extends Nl{_parse(t){return this._getType(t)===Lo.null?yS(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};nG.create=(e,t)=>new nG({innerType:e,typeName:Ou.ZodNullable,...ml(t)});var B_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Lo.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};B_e.create=(e,t)=>new B_e({innerType:e,typeName:Ou.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ml(t)});var O_e=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return _Ue(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new HD(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new HD(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};O_e.create=(e,t)=>new O_e({innerType:e,typeName:Ou.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ml(t)});var DUe=class extends Nl{_parse(t){if(this._getType(t)!==Lo.nan){let n=this._getOrReturnCtx(t);return lo(n,{code:on.invalid_type,expected:Lo.nan,received:n.parsedType}),tu}return{status:"valid",value:t.data}}};DUe.create=e=>new DUe({typeName:Ou.ZodNaN,...ml(e)});var yNc=Symbol("zod_brand"),Wmt=class extends Nl{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},$mt=class e extends Nl{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?tu:o.status==="dirty"?(r.dirty(),h_e(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?tu:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Ou.ZodPipeline})}},P_e=class extends Nl{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Epe(i)&&(i.value=Object.freeze(i.value)),i);return _Ue(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};P_e.create=(e,t)=>new P_e({innerType:e,typeName:Ou.ZodReadonly,...ml(t)});function cYo(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function mYo(e,t={},r){return e?Ipe.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=cYo(t,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!o){let s=cYo(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):Ipe.create()}var bNc={object:KD.lazycreate},Ou;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Ou||(Ou={}));var ENc=(e,t={message:`Input not instance of ${e.name}`})=>mYo(r=>r instanceof e,t),hYo=vpe.create,gYo=g_e.create,vNc=DUe.create,INc=A_e.create,AYo=y_e.create,wNc=b_e.create,CNc=BUe.create,xNc=E_e.create,_Nc=v_e.create,SNc=Ipe.create,BNc=one.create,ONc=r8.create,PNc=OUe.create,TNc=sne.create,DNc=KD.create,RNc=KD.strictCreate,FNc=I_e.create,kNc=BJt.create,QNc=w_e.create,NNc=rG.create,jNc=OJt.create,MNc=PUe.create,LNc=TUe.create,UNc=PJt.create,zNc=C_e.create,VNc=x_e.create,qNc=__e.create,GNc=S_e.create,WNc=wpe.create,$Nc=uM.create,HNc=sM.create,KNc=nG.create,JNc=uM.createWithPreprocess,YNc=$mt.create,XNc=()=>hYo().optional(),ZNc=()=>gYo().optional(),ejc=()=>AYo().optional(),tjc={string:(e=>vpe.create({...e,coerce:!0})),number:(e=>g_e.create({...e,coerce:!0})),boolean:(e=>y_e.create({...e,coerce:!0})),bigint:(e=>A_e.create({...e,coerce:!0})),date:(e=>b_e.create({...e,coerce:!0}))};var rjc=tu;var njc=mt.object({lang:mt.string(),label:mt.optional(mt.string()),source:mt.string()}),pKn=mt.array(njc);Qt();var yYo={README_EXT:"x-readme"};function ijc(e){if(!Array.isArray(e))return!1;for(let t of e)if(!ba(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function bYo(e){let t=Vr(e,yYo.README_EXT);if(!ba(t))return[];let r=t["code-samples"];if(!ijc(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}function ojc(e){return ba(e)&&typeof e.$ref=="string"}function sjc(e,t){if(e!=null){if(typeof e=="string")return e;if(ojc(e)){let r=(0,DJt.resolve)(t??process.cwd(),e.$ref);if((0,TJt.existsSync)(r))try{return(0,TJt.readFileSync)(r,"utf-8")}catch{return}}}}function ajc(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!ba(n))continue;let o=sjc(n.code,t);o!=null&&r.push({...n,code:o})}return r}function EYo(e,t,r){let n=Vr(t,bn.EXAMPLES),i=r.source.type==="openapi"?(0,DJt.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!ba(p))return p;let f=p["code-samples"];if(f!=null){let m=ajc(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=$d.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=jmt(t,c_.REDOCLY_CODE_SAMPLES_KEBAB,pKn,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],c=[...jmt(t,c_.REDOCLY_CODE_SAMPLES_CAMEL,pKn,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];c.length>0&&s.push({"code-samples":c.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let l=bYo(t);return l.length>0&&s.push({"code-samples":l}),s.map(eM.unknown)}function vYo(e){let t=Vr(e,bn.AVAILABILITY);if(t==="ga"||t==="generally-available")return jw.GenerallyAvailable;if(t==="beta"||t==="pre-release")return jw.Beta;if(t==="deprecated")return jw.Deprecated;if(e.deprecated)return jw.Deprecated}function IYo(e){let t=Vr(e,bn.RETRIES);if(t!=null&&t.disabled===!0)return Jh.RetriesConfiguration.disabled(t.disabled)}var ujc="x-fern-default-url";function RJt(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=cjc(e);return{url:pjc({url:e.url,variables:e.variables??{}}),description:e.description,name:fjc(e,t),audiences:Vr(e,bn.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?ljc(e.variables):void 0,defaultUrl:r?n:void 0}}function cjc(e){let t=e[ujc];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function ljc(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function pjc({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 fjc(e,t){let r=Vr(e,[bn.SERVER_NAME_V1,bn.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}}function wYo(e){return Vr(e,bn.PARAMETER_NAME)}function CYo(e){return Vr(e,bn.SDK_VARIABLE)}function FJt({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let u=ei(a)?n.resolveParameterReference(a):a,c=Vr(a,bn.IGNORE)??Vr(u,bn.IGNORE);if(c!=null&&c){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let l=u.required??!1,p=AS(u),d=[...i,u.name],f=py(d,n.options.preserveSchemaIds),m=u.in==="header",[h,g]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!l]:[!l,!1],A=u.schema!=null?Va(u.schema,h,g,n,d,o,n.namespace,!1,new Set,oM({schema:u,logger:n.logger})):l?Fr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Ii.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oM({schema:u,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Fr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Fr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Ii.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oM({schema:u,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(u.in==="header"&&u.schema!=null&&!ei(u.schema)&&u.schema.default!=null){let v=u.schema.default;typeof v=="string"&&v.length>0&&(A=Fr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:wg.string(v),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let E={name:u.name,schema:A,description:u.description,parameterNameOverride:wYo(u),availability:p,source:o};u.in==="query"?s.queryParameters.push({...E,explode:mjc(u)}):u.in==="path"?s.pathParameters.push({...E,variableReference:CYo(u),explode:hjc(u)}):u.in==="header"?!djc.has(u.name.toLowerCase())&&!n.authHeaders.has(u.name)?s.headers.push({...E,env:void 0}):n.logger.debug(`Ignoring ${u.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${u.in} parameter, ${u.name}, in ${t.toUpperCase()} ${e}`)}return s}var djc=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function mjc(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 hjc(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}Qt();function gjc({content:e,context:t}){for(let[r,n]of Object.entries(e))if(_Yo({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function _Yo({mediaType:e,mediaTypeObject:t,context:r}){if(af.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:wUe(t,r)}}function Ajc({content:e,context:t}){for(let[r,n]of Object.entries(e))if(SYo({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function SYo({mediaType:e,mediaTypeObject:t,context:r}){if(af.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:wUe(t,r)}}function BYo({mediaType:e}){return af.parse(e)?.isBinary()??!1}function yjc({content:e}){for(let[t,r]of Object.entries(e))if(BYo({mediaType:t}))return[t,r]}function bjc(e,t){let r=ei(e)?fKn(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!ei(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function QJt({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}){let a=yjc({content:e});if(a){let[d,f]=a;return iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}let u=Ajc({content:e,context:n}),c=sKn({content:e,context:n}),l=Ejc({json:c,multipart:u,document:r,visitor:{json:([d,f])=>iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),multipart:([d,f])=>iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),neither:()=>{}}});if(l)return l;let p=gjc({content:e,context:n});if(p){let[d,f]=p;return iG({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}}function Ejc({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?n.neither():i?.schema&&o?.schema?i.schema&&bjc(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function iG({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a}){let u=vjc({mediaTypeObject:t});if(BYo({mediaType:e}))return KO.octetStream({description:r,source:s,sdkMethodName:u,contentType:e});let c=SYo({mediaType:e,mediaTypeObject:t,context:i}),l=c?.schema,p=c?.encoding,d=c?.examples;if(l){let h=ei(l)?fKn(l,n):{id:void 0,schema:l},g=Va(h.schema,!1,!1,i,o,s,a,!1),A=[];if(g.type==="object"){let E=new Set(h.schema.required??[]);for(let v of g.properties){let b=E.has(v.key),{isFile:I,isOptional:w,isArray:x,description:C}=kJt({schema:v.schema,isOptional:!b});if(I){let _=xYo(v.key,p);A.push({key:v.key,schema:G9.file({isOptional:w,isArray:x,description:C}),description:C,contentType:_,exploded:!1,encoding:_==null?i.options.defaultFormParameterEncoding:void 0})}else{let _=xYo(v.key,p);A.push({key:v.key,schema:G9.json(v.schema),description:void 0,contentType:_,exploded:p?.[v.key]?.explode,encoding:_==null?i.options.defaultFormParameterEncoding:wjc(_)})}}}return KO.multipart({name:ei(l)&&i.getNumberOfOccurrencesForRef(l)===1?h.id:void 0,description:h.schema.description,properties:A,source:s,sdkMethodName:u,fullExamples:d})}let f=wJt({mediaType:e,mediaTypeObject:t,context:i});if(f){let h=Va(f.schema,!1,!1,i,o,s,a,!0);return KO.json({description:void 0,schema:h,contentType:f.contentType,fullExamples:f.examples,additionalProperties:!ei(f.schema)&&Lmt(f.schema.additionalProperties,i.options),source:s,sdkMethodName:u})}let m=_Yo({mediaType:e,mediaTypeObject:t,context:i});if(m!=null&&m.schema!=null){let h=Va(m.schema,!1,!1,i,o,s,a,!1);return KO.formUrlEncoded({schema:h,description:r,contentType:m.contentType,source:s,fullExamples:m.examples,additionalProperties:!1,sdkMethodName:u})}}function vjc({mediaTypeObject:e}){return Vr(e,bn.SDK_METHOD_NAME)}var Ijc={"application/json":"json"};function wjc(e){return e?Ijc[e]:void 0}function fKn(e,t){if(!e.$ref.startsWith(f_e))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=rne(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return ei(n)?fKn(n,t):{id:r,schema:n}}function kJt({schema:e,isOptional:t,isArray:r,description:n}){return xjc(e)?kJt({schema:e.value,isOptional:!0,isArray:r,description:e.description}):_jc(e)?kJt({schema:e.value,isOptional:t,isArray:r,description:e.description}):Sjc(e)?kJt({schema:e.value,isOptional:t,isArray:!0,description:e.description}):Cjc(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 Cjc(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function xjc(e){return e.type==="optional"}function _jc(e){return e.type==="nullable"}function Sjc(e){return e.type==="array"}function xYo(e,t){return t?.[e]?.contentType}Qt();var dKn={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"},OYo=new Set(Object.values(dKn));var Bjc=["200","201","202","204"];function NJt({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,streamTerminator:s,source:a}){if(t==null)return{value:void 0,errors:{}};let u=Ojc({responses:t,context:r,source:a,namespace:r.namespace}),c=!1,l;for(let p of i!=null?[i]:Bjc){let d=t[p];d!=null&&(c=!0,l==null&&(l=PYo({operationContext:e,response:d,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace,statusCode:typeof p=="string"?parseInt(p):p})))}if(l==null&&!c&&t.default!=null&&(l=PYo({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace})),l!=null)switch(l.type){case"json":return{value:l,errors:u};case"streamingJson":case"streamingSse":return{value:l,errors:u};case"bytes":case"file":case"text":case"streamingText":return{value:l,errors:u};default:xe(l)}return{value:void 0,errors:u}}function PYo({operationContext:e,streamFormat:t,streamTerminator:r,response:n,context:i,responseBreadcrumbs:o,source:s,namespace:a,statusCode:u}){let c=ei(n)?i.resolveResponseReference(n):n;if(c.content!=null&&Object.entries(c.content).find(([f,m])=>{if(m.schema==null)return!1;let h=ei(m.schema)?i.resolveSchemaReference(m.schema):m.schema;return h.type==="string"&&(h.format==="binary"||h.format==null&&h.contentMediaType==="application/octet-stream")}))return i.options.useBytesForBinaryResponse&&t==null?wh.bytes({description:c.description,source:s,statusCode:u}):wh.file({description:c.description,source:s,statusCode:u});let l=XJo(c.content??{},i);if(l!=null&&t!=null)switch(t){case"json":return wh.streamingJson({statusCode:u,description:c.description,responseProperty:Vr(e.operation,bn.RESPONSE_PROPERTY),terminator:r,fullExamples:l.examples,schema:Va(l.schema,!1,!1,i,o,s,a),source:s});case"sse":return wh.streamingSse({description:c.description,responseProperty:void 0,terminator:r,fullExamples:l.examples,schema:Va(l.schema,!1,!1,i,o,s,a),source:s,statusCode:u})}let p=CJt({context:i,content:c.content??{}});if(p){if(t!=null)switch(t){case"json":return wh.streamingJson({description:c.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:Va(p.schema,!1,!1,i,o,s,a),source:s,statusCode:u});case"sse":return wh.streamingSse({description:c.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:Va(p.schema,!1,!1,i,o,s,a),source:s,statusCode:u})}return wh.json({description:c.description,schema:Va(p.schema,!1,!1,i,o,s,a),responseProperty:Vr(e.operation,bn.RESPONSE_PROPERTY),terminator:void 0,fullExamples:p.examples,source:s,statusCode:u})}for(let[d,f]of Object.entries(c.content??{})){let m=af.parse(d);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return wh.file({description:c.description,source:s,statusCode:u});if(m.isText()&&!d.includes("event-stream")){let h=f.schema;if(h==null)return wh.text({description:c.description,source:s,statusCode:u});let g=ei(h)?i.resolveSchemaReference(h):h;return g.type==="string"&&g.format==="byte"?wh.file({description:c.description,source:s,statusCode:u}):wh.text({description:c.description,source:s,statusCode:u})}}}}function Ojc({responses:e,context:t,source:r,namespace:n}){let i={};for(let[o,s]of Object.entries(e)){if(o==="default")continue;let a=parseInt(o);if(a<400||a>600)continue;let u=ei(s)?t.resolveResponseReference(s):s,c=eYo(u.content??{},t),l=dKn[a];if(l==null){t.logger.warn(`No error name found for status code ${o}`);continue}i[a]={statusCode:a,nameOverride:void 0,generatedName:l,description:u.description,schema:Va(c?.schema??{},!1,!1,t,[l,"Body"],r,n),fullExamples:c?.examples,source:r}}return i}function ane({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,source:s,streamRequestNameOverride:a}){let{document:u,operation:c,path:l,method:p,baseBreadcrumbs:d,pathItem:f}=e,m=Vr(c,bn.IDEMPOTENT),h=Vr(c,[bn.REQUEST_NAME_V1,bn.REQUEST_NAME_V2]),g=[...d,"Request"],A=FJt({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:l,httpMethod:p,source:s}),E=/{([^}]+)}/g,v=[...l.matchAll(E)].map(z=>z[1]).filter(z=>z!==void 0),b=[...l.matchAll(E)].map(z=>z[1]);switch(t.options.pathParameterOrder){case yn.PathParameterOrder.SpecOrder:{let z=b.filter(Z=>!A.pathParameters.some(oe=>oe.name===Z));if(z.length>0)for(let Z of z)A.pathParameters.push({name:Z??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Fr.primitive({schema:Ii.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})}break;case yn.PathParameterOrder.UrlOrder:if(v.length>0){let z=new Map(A.pathParameters.map(V=>[V.name,V])),Z=[],oe=new Set;for(let V of v){let K=z.get(V);oe.add(V),K?Z.push(K):Z.push({name:V,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Fr.primitive({schema:Ii.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})}for(let V of A.pathParameters)oe.has(V.name)||Z.push(V);A.pathParameters=Z}break;default:xe(t.options.pathParameterOrder)}let I=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let z=ei(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,Z=Object.values(z.content).every(V=>Tjc({mediaTypeObject:V})!=null),oe=[];if(Z)return oe.push(...Object.entries(z.content).map(([V,K])=>{let be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:new m_e({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return TYo({context:t,convertedParameters:A})&&be!=null&&(be.type==="json"||be.type==="formUrlEncoded")&&be.schema.type!=="object"&&c.requestBody!=null?be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):c.requestBody!=null&&(be=iG({mediaType:V,mediaTypeObject:K,description:z.description,document:u,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),be}).filter(V=>V!=null)),oe.length===0?[void 0]:oe;{let V=QJt({content:z.content,description:z.description,document:u,context:new m_e({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return TYo({context:t,convertedParameters:A})&&V!=null&&(V.type==="json"||V.type==="formUrlEncoded")&&V.schema.type!=="object"&&c.requestBody!=null?V=QJt({content:z.content,description:z.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):c.requestBody!=null&&(V=QJt({content:z.content,description:z.description,document:u,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),[V]}})(),w=I.length>1,x=[...d,"Response"],C=NJt({operationContext:e,streamFormat:i,streamTerminator:o,responses:c.responses,context:t,responseBreadcrumbs:x,responseStatusCode:r,source:s}),_=IYo(c),R=vYo(c),U=EYo(e,c,t),q=Vr(c,bn.SERVER_NAME_V2);return I.map(z=>({summary:c.summary,internal:Vr(c,c_.INTERNAL),idempotent:m,audiences:Vr(c,bn.AUDIENCES)??[],operationId:c.operationId!=null&&n!=null?c.operationId+"_"+n:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:Djc({operationContext:e,request:z}),pathParameters:A.pathParameters,queryParameters:A.queryParameters,headers:A.headers,requestNameOverride:a??h??void 0,generatedRequestName:py(w?Pjc({breadcrumbs:g,request:z}):g,t.options.preserveSchemaIds),request:z,response:C.value,errors:C.errors,servers:q!=null?[{name:q,url:void 0,audiences:void 0}]:(c.servers??f.servers??[]).map(Z=>RJt(Z,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:Fjc(c,u),security:Rjc(c),availability:R,method:p,path:l,examples:U,pagination:e.pagination,source:s,retries:_}))}function Pjc({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function Tjc({mediaTypeObject:e}){return Vr(e,bn.SDK_METHOD_NAME)}function Djc({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 Rjc(e){return e.security}function Fjc(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function TYo({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function RYo({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,u=r.discriminant.value,c=r["response-status-code"],l=DYo({context:t,headerToIgnore:a,parameters:o}),p=DYo({context:t,headerToIgnore:a,parameters:s}),d=ane({operationContext:{...e,pathItemParameters:l,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==c))}},context:t,streamFormat:void 0,source:n}),f=ane({operationContext:{...e,pathItemParameters:l,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:c,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Fr.literal({nameOverride:void 0,generatedName:py([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:wg.string(u),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:d,async:f}}function DYo({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=ei(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}Qt();var mKn="stream";function NYo({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:ane({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=FYo({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let l=rne(n.schemaReference);l!=null&&t.excludeSchema(l)}let i=kYo({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let l=rne(n.schemaReference);if(l!=null)return`${l}Streaming`}})(),s=ane({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+mKn}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,mKn]},context:t,streamFormat:r.format,streamTerminator:r.terminator,suffix:mKn,source:t.source,streamRequestNameOverride:o});s.forEach(l=>{l.examples=l.examples.filter(p=>QYo(p,t)!==!1)});let a=FYo({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),u=kYo({operation:e.operation,response:r.response}),c=ane({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:u}},context:t,source:t.source});return c.forEach(l=>{l.examples=l.examples.filter(p=>QYo(p,t)!==!0)}),{streaming:s,nonStreaming:c}}default:xe(r)}}function FYo({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=ei(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=CJt({content:i.content,context:e});if(o==null)return;let s=ei(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&ei(a)&&(a=void 0);let u={...s,properties:{...s.properties,[r.streamConditionProperty]:{...a??{},type:"boolean","x-fern-boolean-literal":n}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{content:{[af.APPLICATION_JSON]:{schema:u}}},schemaReference:ei(o.schema)?o.schema:void 0}}function kYo({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[af.APPLICATION_JSON]:{schema:t}}}}}function QYo(e,t){return e._visit({unknown:r=>{let n=$d.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var VYo=require("crypto");function kjc(e){switch(e){case"unix-seconds":return Jh.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Jh.WebhookTimestampFormat.UnixMillis;case"iso8601":return Jh.WebhookTimestampFormat.Iso8601}}function jYo(e){if(e!=null)return{header:e.header,format:e.format!=null?kjc(e.format):void 0,tolerance:e.tolerance}}function Qjc(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Jh.WebhookPayloadComponent.Body;case"timestamp":return Jh.WebhookPayloadComponent.Timestamp;case"notification-url":return Jh.WebhookPayloadComponent.NotificationUrl;case"message-id":return Jh.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter}}function Njc(e){if(e!=null)switch(e){case"sha256":return Jh.WebhookSignatureAlgorithm.Sha256;case"sha1":return Jh.WebhookSignatureAlgorithm.Sha1;case"sha384":return Jh.WebhookSignatureAlgorithm.Sha384;case"sha512":return Jh.WebhookSignatureAlgorithm.Sha512}}function MYo(e){if(e!=null)switch(e){case"base64":return Jh.WebhookSignatureEncoding.Base64;case"hex":return Jh.WebhookSignatureEncoding.Hex}}function jjc(e){if(e!=null)switch(e){case"rsa-sha256":return Jh.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Jh.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Jh.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Jh.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Jh.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Jh.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Jh.AsymmetricAlgorithm.Ed25519}}function UYo(e){if(e.type==="hmac")return Jh.WebhookSignatureVerification.hmac({header:e.header,algorithm:Njc(e.algorithm),encoding:MYo(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:Qjc(e["payload-format"]),timestamp:jYo(e.timestamp)});if(e.type==="asymmetric"){let t=jjc(e["asymmetric-algorithm"]);return t==null?void 0:Jh.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:t,encoding:MYo(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],timestamp:jYo(e.timestamp)})}}function LYo(e){let t=Vr(e,bn.WEBHOOK_SIGNATURE);if(!(t==null||typeof t=="boolean"))return UYo(t)}function zYo(e,t){let r=Vr(t,bn.WEBHOOK_SIGNATURE);return r!=null?typeof r=="boolean"?LYo(e):UYo(r):LYo(e)}function qYo({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:u}=t,c=[...a,"Payload"],l=[...a,"Response"],p=FJt({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:c,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??Ljc({path:o,method:s,sdkMethodName:u}),f=i.responses?NJt({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:l,source:r}):void 0,m=zYo(n,i);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 g=p.queryParameters.map(v=>({key:v.name,schema:v.schema,readonly:void 0,writeonly:void 0,audiences:[],conflict:{},nameOverride:v.parameterNameOverride,generatedName:py([...c,v.name],e.options.preserveSchemaIds),availability:v.availability})),A=Fr.object({description:i.description,properties:g,nameOverride:void 0,generatedName:py(c,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});return[{summary:i.summary,audiences:Vr(i,bn.AUDIENCES)??[],sdkName:u,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:py(c,e.options.preserveSchemaIds),payload:A,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let h=ei(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([g,A])=>iG({mediaType:g,mediaTypeObject:A,description:h.description,document:n,context:e,requestBreadcrumbs:[...a,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"&&g.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let A,E;return g.type==="multipart"?(A={name:g.name,properties:g.properties,description:g.description,source:g.source},E=Fr.unknown({nameOverride:void 0,generatedName:py(c,e.options.preserveSchemaIds),title:void 0,description:g.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):E=g.schema,{summary:i.summary,audiences:Vr(i,bn.AUDIENCES)??[],sdkName:u,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:py(c,e.options.preserveSchemaIds),payload:E,signatureVerification:m,multipartFormData:A,response:f?.value,description:i.description,examples:Mjc(g.fullExamples),source:r}}).filter(g=>g!=null)}function Mjc(e){if(e==null)return[];let t=[];for(let r of e){let n=ype(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function Ljc({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=Ujc(e);if(n===e.toLowerCase())return e;let i=(0,VYo.createHash)("sha256").update(e).digest("hex").slice(0,8);return zjc(`${n}_${t.toLowerCase()}_${i}`)}function Ujc(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function zjc(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function hKn({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=Vr(r,bn.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=Vjc(r,e),s=YJo(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:qjc({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:qYo({context:e,operationContext:a,source:e.source})};let u=KJo(r);if(u==null&&Gjc({operation:r,context:e})&&(u={type:"stream",format:"sse",terminator:void 0}),u!=null){let p=NYo({context:e,operationContext:a,streamingExtension:u});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let c=$Jo(r);if(c!=null){let p=RYo({context:e,operationContext:a,asyncExtension:c,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:ane({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function Vjc(e,t){let r=Vr(e,bn.SDK_METHOD_NAME),n=Vr(e,bn.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function qjc({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(Ln(`${r}_${n.split("/").join("_")}`));return o}function Gjc({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=ei(n)?t.resolveResponseReference(n):n;if(o.content!=null&&ZJo(o.content))return!0}return!1}function GYo(e,t,r,n){let i=[],o=$Yo(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 u=Wjc({operation:a.operation}),c=hKn({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:u});c&&i.push(c)}return i}function WYo(e,t,r,n){let i=[],o=$Yo(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 u=hKn({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});u&&i.push(u)}return i}function $Yo(e){let t=[];return e.get!=null&&t.push({method:Mw.Get,operation:e.get}),e.post!=null&&t.push({method:Mw.Post,operation:e.post}),e.put!=null&&t.push({method:Mw.Put,operation:e.put}),e.delete!=null&&t.push({method:Mw.Delete,operation:e.delete}),e.patch!=null&&t.push({method:Mw.Patch,operation:e.patch}),e.head!=null&&t.push({method:Mw.Head,operation:e.head}),t}function Wjc({operation:e}){return Vr(e,[bn.WEBHOOK])??!1}function HYo(e){let t=Vr(e,bn.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Vr(e,bn.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function KYo(e){return Vr(e,bn.FERN_BASIC_AUTH)}function YYo(e,t,r,n){if(ei(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return JYo(i,t,r)}return JYo(e,t,r)}function JYo(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=Vr(e,c_.BEARER_FORMAT),i=Vr(e,bn.FERN_HEADER_AUTH);return Nw.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??Vr(e,bn.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=Vr(e,bn.FERN_BEARER_TOKEN);return Nw.bearer({tokenVariableName:n?.name??Vr(e,bn.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=KYo(e),i=HYo(e);return Nw.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return Nw.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return Nw.oauth({scopesEnum:$jc(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 $jc(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=gpe({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=ff(n);if(i.type==="enum")return i}}function XYo(e){return Vr(e,bn.BASE_PATH)}var Hjc=mt.record(mt.string(),mt.object({summary:mt.string().optional(),description:mt.string().optional()}));function ZYo({document:e,context:t}){return jmt(e,bn.GROUPS,Hjc,t.logger)}function eXo({context:e,document:t}){return Vr(t,bn.FERN_VERSION)??void 0}function tXo(e){let t=Vr(e,bn.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?Mmt({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}function rXo(e){let t=Vr(e,bn.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?Mmt({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}function nXo(e,t){let r=Vr(e,bn.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:py([n],t),title:i.title,schema:Mc.string({default:yUe(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}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var Kjc="webhooks";function iXo(e){return Vr(e,Kjc)??{}}var Hmt=class extends CUe{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 m_e({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}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 oXo(e){return Vr(e,bn.RESOLUTIONS)}function sXo({openapi:e}){let t=oXo(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=Jjc({openapi:e,schemaReference:o,schemaName:n.name}),e=aXo({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function Jjc({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 aXo({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(u=>t.startsWith(u)).sort((u,c)=>c.length-u.length)[0];if(i!=null){let u=n[i];if(u!=null){let c=r.replace(i,u);return aXo({openapi:e,replaceReference:t,schemaReference:c,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(u=>u.replaceAll("~1","/")),s=e;for(let u of o.slice(0,-1)){let c=s[u];if(c==null)return e;s=c}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}function cXo({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=sXo({openapi:e}),hJt();let o=new Hmt({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([U,q])=>{let z=YYo(q,n,t,o);return z==null?null:[U,z]}).filter(U=>U!==null)),a=e.security?.filter(U=>U!=null),u=new Set(Object.entries(s).map(([U,q])=>q.type==="basic"||q.type==="bearer"||q.type==="oauth"?"Authorization":q.type==="header"?q.headerName:null).filter(U=>U!=null)),c=nXo(e,r.preserveSchemaIds),l=tXo(e),p=rXo(e),d=r.audiences??[],f=[],m=[],h=new Hmt({document:e,taskContext:t,authHeaders:u,options:r,source:n,namespace:i});h.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([U,q])=>{if(q==null)return;let z=GYo(U,q,e,h);for(let Z of z){let oe=uXo({operation:Z});if(!(d.length>0&&!d.some(V=>oe.includes(V))))switch(Z.type){case"async":f.push(...Z.sync),f.push(...Z.async);break;case"http":f.push(...Z.value);break;case"streaming":f.push(...Z.streaming),Z.nonStreaming&&f.push(...Z.nonStreaming);break;case"webhook":m.push(...Z.value);break;default:xe(Z)}}}),Object.entries(iXo(e)).forEach(([U,q])=>{if(q==null)return;t.logger.debug(`Converting path ${U}`);let z=WYo(U,q,e,h);for(let Z of z){let oe=uXo({operation:Z});d.length>0&&!d.some(V=>oe.includes(V))||m.push(...Z.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([U,q])=>{let z=Vr(q,bn.SDK_NAMESPACE);if(!ei(q)){let Z=Vr(q,bn.IGNORE);if(Z!=null&&Z)return[];if(OYo.has(U))return[U,Va({...q,"x-fern-type-name":`${U}Body`},!1,!1,h,[U],n,z??i)]}return[U,Va(q,!1,!1,h,[U],n,z??i)]}).filter(U=>U.length>0)),A=Yjc(g,h,n),E=Xjc(A,h),v=Z9(),b={};for(let[U,q]of Object.entries(E)){let z=ff(q);if(h.isSchemaExcluded(U))continue;let Z=v.getUniqueSchemaId(U,h.logger,r.resolveSchemaCollisions);b[Z]=z}let I=new bpe(E,h.nonRequestReferencedSchemas,h),w=m.map(U=>{let z=U.examples;if(!r.disableExamples&&z.length===0){let Z=I.buildExample({schema:U.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Z!=null&&(z=[{name:void 0,description:void 0,payload:Z}])}return{...U,payload:ff(U.payload),examples:z}}),x=new yJt(E,h,l),C=f.map(U=>{let q=U.examples,z=q;if(!r.disableExamples&&(q.length===0||q.every(Vmt))){let V=x.buildEndpointExample(U);V.length>0&&(z=[...V,...q.filter(K=>!Vmt(K))])}let Z=U.request,oe=U.response;return{...U,request:Z?.type==="json"||Z?.type==="formUrlEncoded"?{...Z,schema:ff(Z.schema)}:Z,response:oe?.type==="json"?{...oe,schema:ff(oe.schema)}:oe,queryParameters:U.queryParameters.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,explode:V.explode,availability:V.availability,source:V.source})),pathParameters:U.pathParameters.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,variableReference:V.variableReference,availability:V.availability,source:V.source})),headers:U.headers.map(V=>({description:V.description,name:V.name,schema:ff(V.schema),parameterNameOverride:V.parameterNameOverride,env:V.env,availability:V.availability,source:V.source})),examples:z,errors:fl(U.errors,V=>{let K=V.fullExamples?.map(be=>{let Ce=ype(be.value);if(Ce!=null)return{name:be.name,description:be.description,example:Ce}}).filter(ma);if(K?.length===0){let be=I.buildExample({schema:V.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});be!=null&&K.push({name:void 0,description:void 0,example:be})}return{generatedName:V.generatedName,nameOverride:V.nameOverride,schema:ff(V.schema),description:V.description,source:V.source,examples:K}}),retries:U.retries}});x.finalize();let _=ZYo({document:e,context:h});return{apiVersion:eXo({context:h,document:e}),basePath:XYo(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(_??{}).map(([U,q])=>[U,{summary:q.summary??void 0,description:q.description??void 0}])),servers:(e.servers??[]).map(U=>RJt(U,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(U=>[U.name,{id:U.name,description:U.description}])),orderedTagIds:e.tags?.map(U=>U.name)},endpoints:C,webhooks:w,channels:{},groupedSchemas:EUe(i,b),securitySchemes:s,security:a,hasEndpointsMarkedInternal:C.some(U=>U.internal),nonRequestReferencedSchemas:h.getReferencedSchemas(),variables:c,globalHeaders:l,idempotencyHeaders:p}}function Yjc(e,t,r){if(t.options.removeDiscriminantsFromSchemas===yn.RemoveDiscriminantsFromSchemas.Never)return e;let n={};for(let[i,o]of Object.entries(e)){if(o.type!=="object"){n[i]=o;continue}let s={$ref:`#/components/schemas/${i}`},a=t.getReferencesFromDiscriminatedUnion(s);if(a==null){n[i]=o;continue}if(t.getReferencedSchemas().has(i)){n[i]=o;continue}let c={...o,type:"object",properties:o.properties.filter(p=>!a.discriminants.has(p.key)),allOfPropertyConflicts:o.allOfPropertyConflicts.filter(p=>!a.discriminants.has(p.propertyKey)),source:r};n[i]=c;let l=lXo({schema:o,schemas:e});for(let p of[...new Set(l)]){let d=n[p]??e[p];d==null||d.type!=="object"||(n[p]={...d,type:"object",properties:d.properties.filter(f=>!a.discriminants.has(f.key)),allOfPropertyConflicts:d.allOfPropertyConflicts.filter(f=>!a.discriminants.has(f.propertyKey))})}}return n}function Xjc(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 c of i.properties)if(s.discriminants.has(c.key)){let l=s.discriminants.get(c.key);l!=null&&a.push({...c,schema:Fr.literal({nameOverride:void 0,generatedName:py([i.generatedName,l],t.options.preserveSchemaIds),title:void 0,value:wg.string(l),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(c);let u={...i,type:"object",properties:a};r[n]=u}return r}function lXo({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(...lXo({schema:i,schemas:t}))}return r}function jJt(e){return[...new Set(e)]}function uXo({operation:e}){let t=[];switch(e.type){case"async":t=jJt(e.async.flatMap(r=>r.audiences));break;case"http":t=jJt(e.value.flatMap(r=>r.audiences));break;case"streaming":t=jJt(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=jJt(e.value.flatMap(r=>r.audiences));break;default:xe(e)}return t}function T_e({context:e,documents:t,options:r}){let n={apiVersion:void 0,title:void 0,description:void 0,basePath: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:[],idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let s=o.source!=null?o.source:mS.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=cXo({taskContext:e,openApi:o.value,options:iM({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=nMc(n,a,iM({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let a=WJo({document:o.value,taskContext:e,options:iM({options:o.settings,overrides:r}),source:s,asyncApiOptions:Zjc({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(u=>({...u,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=MJt(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath),i++;break}default:xe(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?`
1497
1497
  `+s.stack:"")}return n}function Zjc({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??lJo.naming}}function LJt(e){let t=String(e.description||e.name||e["x-fern-server-name"]||"default").trim(),r=t.toUpperCase();return r==="PRODUCTION"||r==="PRD"||r==="PROD"?"PRD":r==="SANDBOX"||r==="SBX"?"SBX":r==="STAGING"||r==="STG"?"STG":r==="PERFORMANCE"||r==="PRF"||r==="PERF"?"PRF":r==="E2E"||r==="E_2_E"?"E2E":r==="QAL"||r==="QUALITY"?"QAL":t}function AKn(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],u=a&&a.length>2?a:s;if(u&&!i.has(u.toLowerCase())&&u.length>2)return u.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 gKn(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 c of s)a[c]=o[c]??[];let u=JSON.stringify(a);i.has(u)||i.set(u,o)}return Array.from(i.values())}function eMc(e,t){if(rMc(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=LJt(o);r.set(s,o.url)}let n=!0,i=!0;for(let o of t){if(o.type==="grouped")continue;let s=LJt(o),a=r.get(s);a?a===o.url&&(i=!1):n=!1}return n&&i}function yKn(e){return e.defaultUrl??e.url}function tMc(e){if(e.length===0||!e[0])return"api";let t=e[0];return t.type==="grouped"?Object.keys(t.urls)[0]??"api":AKn(yKn(t))}function rMc(e){return e.some(t=>t.type==="grouped")}function nMc(e,t,r){if(!(r?.groupMultiApiEnvironments===!0))return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,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:MJt(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:gKn(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}};if(eMc(e.servers,t.servers)){let o=[],s=[],a=tMc(t.servers),u=new Map;for(let p of e.servers)if(p.type==="grouped"){let d=p.name??"default";u.has(d)||u.set(d,{});let f=u.get(d);if(f)for(let[m,h]of Object.entries(p.urls))f[m]=h}else{let d=AKn(yKn(p)),f=LJt(p);u.has(f)||u.set(f,{});let m=u.get(f);m&&(m[d]={url:p.url,audiences:p.audiences,defaultUrl:p.defaultUrl,urlTemplate:p.urlTemplate,variables:p.variables})}for(let p of t.servers){let d=LJt(p);u.has(d)||u.set(d,{});let f=u.get(d);f&&(f[a]={url:p.url,audiences:p.audiences,defaultUrl:p.defaultUrl,urlTemplate:p.urlTemplate,variables:p.variables})}for(let[p,d]of u.entries()){let f={type:"grouped",name:p,description:`${p} environment`,urls:d};o.push(f)}let c=e.endpoints.map(p=>{let d=p.__apiName;if(d)return{...p,type:"multi-api",apiName:d,servers:[{name:d,url:void 0,audiences:void 0}]};let f=e.servers[0],m=f!=null&&f.type!=="grouped"?AKn(yKn(f)):"api";return{...p,type:"multi-api",apiName:m,servers:[{name:m,url:void 0,audiences:void 0}]}}),l=t.endpoints.map(p=>({...p,type:"multi-api",apiName:a,servers:[{name:a,url:void 0,audiences:void 0}]}));return s=[...c,...l],{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:o,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:s.map(p=>{if(p.type==="multi-api"){let{type:m,apiName:h,servers:g,...A}=p;return{...A,__apiName:h,servers:g}}let{type:d,...f}=p;return f}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:MJt(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:gKn(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,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:MJt(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:gKn(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function MJt(e,t,r){let n=Z9(),i=r?.resolveSchemaCollisions??!1,o={...e.rootSchemas};for(let[s,a]of Object.entries(t.rootSchemas)){let u=n.getUniqueSchemaId(s,void 0,i);o[u]=a}e.rootSchemas=o;for(let[s,a]of Object.entries(t.namespacedSchemas))if(e.namespacedSchemas[s]!=null){let u=e.namespacedSchemas[s];for(let[c,l]of Object.entries(a)){let p=n.getUniqueSchemaId(c,void 0,i);u[p]=l}}else e.namespacedSchemas[s]=a;return e}var Vus=_e(zer(),1),Ver={config:new Vus.Config({apis:{},styleguide:{plugins:[YHn],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function l8({options:e,overrides:t}={}){return{...iM({options:e,overrides:t}),...e_e({options:e,overrides:t})}}var vol={shouldUseTitleAsName:"useTitlesAsName",shouldUseUndiscriminatedUnionsWithLiterals:["shouldUseUndiscriminatedUnionsWithLiterals","discriminatedUnionV2"],shouldUseIdiomaticRequestNames:"shouldUseIdiomaticRequestNames",asyncApiMessageNaming:"asyncApiNaming",shouldUseOptionalAdditionalProperties:"optionalAdditionalProperties",coerceEnumsToLiterals:"coerceEnumsToLiterals",objectQueryParameters:"objectQueryParameters",respectReadonlySchemas:"respectReadonlySchemas",respectNullableSchemas:"respectNullableSchemas",onlyIncludeReferencedSchemas:"onlyIncludeReferencedSchemas",inlinePathParameters:"inlinePathParameters",useBytesForBinaryResponse:"useBytesForBinaryResponse",respectForwardCompatibleEnums:"respectForwardCompatibleEnums",filter:"filter",defaultFormParameterEncoding:"defaultFormParameterEncoding",exampleGeneration:"exampleGeneration",additionalPropertiesDefaultsTo:"additionalPropertiesDefaultsTo",typeDatesAsStrings:"typeDatesAsStrings",preserveSingleSchemaOneOf:"preserveSingleSchemaOneOf",inlineAllOfSchemas:"inlineAllOfSchemas",resolveAliases:"resolveAliases",groupMultiApiEnvironments:"groupMultiApiEnvironments",groupEnvironmentsByHost:"groupEnvironmentsByHost",wrapReferencesToNullableInOptional:"wrapReferencesToNullableInOptional",coerceOptionalSchemasToNullable:"coerceOptionalSchemasToNullable",removeDiscriminantsFromSchemas:"removeDiscriminantsFromSchemas",defaultIntegerFormat:"defaultIntegerFormat",pathParameterOrder:"pathParameterOrder",resolveSchemaCollisions:"resolveSchemaCollisions",inferForwardCompatible:"inferForwardCompatible",coerceConstsTo:"coerceConstsTo"};function Iol(e,t,r){r!==void 0&&(e[t]=r)}function qer(e){let t={};if(e!=null)for(let[r,n]of Object.entries(vol)){let i=e[r],o=Array.isArray(n)?n:[n];for(let s of o)Iol(t,s,i)}return l8({options:t})}function Q3e(e){if(e.settings==null&&e.apiOverride?.auth==null&&e.apiOverride?.["auth-schemes"]==null&&e.apiOverride?.headers==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.apiOverride?.auth!=null&&(t.auth=e.apiOverride.auth),e.apiOverride?.["auth-schemes"]!=null&&(t.authSchemes=e.apiOverride["auth-schemes"]),e.apiOverride?.headers!=null&&(t.headers=e.apiOverride.headers),t}function p8(e){return e.swagger!=null}function nti(e){return e.openapi!=null}Qt();gg();Ci();function Xpe(e,t={}){return{...Object.fromEntries(Wy(e.namedDefinitionFiles).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...Wy(e.importedDefinitions).reduce((r,[n,i])=>({...r,...hpt(Xpe(i.definition,{defaultURL:i.url}),(o,s)=>Nb(n,Ss.of(s)))}),{})}}Qt();gg();Ci();function lgt(e,t={}){return{...Object.fromEntries(Wy(e.packageMarkers).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...Wy(e.importedDefinitions).reduce((r,[n,i])=>({...r,...hpt(lgt(i.definition,{defaultURL:i.url}),(o,s)=>Nb(n,Ss.of(s)))}),{})}}function _ne(e){return{...lgt(e),...Xpe(e)}}function bM(e,t){return _ne(e.definition)[t]?.contents}Qt();gg();function M0(e,t){for(let[r,n]of Wy(_ne(e.definition)))t(r,n.contents,{isPackageMarker:K1(r)===Bp,defaultUrl:n.defaultUrl})}Qt();function l1e(e,t){for(let[r,n]of Wy(lgt(e.definition)))t(r,n.contents)}Qt();var qus=_e(require("path"),1);async function Ger({schema:e,value:t,context:r,filepathBeingParsed:n}){let i=await e.safeParseAsync(t);if(i.success)return i.data;let o=i.error.errors.map(a=>{let u=a.path.length>0?`${a.message} at "${wol(a.path)}"`:a.message;return g5({content:u,prefix:" - "})}),s=[`Failed to parse file: ${qus.default.relative(process.cwd(),n)}`,...o].join(`
1498
1498
  `);return r.failAndThrow(s)}function wol(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}Vt();var pm=class e extends Error{constructor(){super(),Object.setPrototypeOf(this,e.prototype)}};var f8=class e extends Error{log;constructor(t){super(),this.log=t,Object.setPrototypeOf(this,e.prototype)}};var zn={Trace:"trace",Debug:"debug",Info:"info",Warn:"warn",Error:"error"},b_=Object.values(zn);var iti=class{log;enabled;constructor(t,r=!0){this.log=t,this.enabled=r}disable(){this.enabled=!1}enable(){this.enabled=!0}debug(...t){this.enabled&&this.log(zn.Debug,...t)}info(...t){this.enabled&&this.log(zn.Info,...t)}warn(...t){this.enabled&&this.log(zn.Warn,...t)}error(...t){this.enabled&&this.log(zn.Error,...t)}trace(...t){this.enabled&&this.log(zn.Trace,...t)}};function aP(e){return new iti(e)}var oti=Object.freeze(aP(Col));function Col(e,...t){xol(e)(...t)}function xol(e){switch(e){case zn.Trace:return console.trace;case zn.Debug:return console.debug;case zn.Info:return console.info;case zn.Warn:return console.warn;case zn.Error:return console.error}}var Op;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(Op||(Op={}));function sti({logger:e=oti}={}){let t={logger:e,takeOverTerminal:()=>{throw new Error("Not implemented")},failAndThrow:(r,n)=>{let i=[];throw r!=null&&i.push(r),n!=null&&i.push(JSON.stringify(n)),i.length>0&&t.logger.error(...i),new pm},failWithoutThrowing:(r,n)=>{t.failAndThrow(r,n)},getResult:()=>Op.Success,addInteractiveTask:()=>{throw new Error("Not implemented")},runInteractiveTask:()=>{throw new Error("Not implemented")},instrumentPostHogEvent:()=>{throw new Error("Not implemented")}};return t}var Gus=_e(require("path"),1),_ol={dependencies:{}};async function Wus({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return _ol;let n={};for(let[i,o]of Object.entries(t.dependencies))if(Bol(o)){let s=Ut.of(Gus.default.join(e,o));await Xt(s)?n[i]={type:"local",absoluteFilepath:s,path:o}:r.failWithoutThrowing(`Path to ${i} dependency does not exist: ${s}`)}else{let a=i.substring(1).split("/"),u=a[0],c=a[1];u!=null&&c!=null?n[i]={type:"version",organization:u,apiName:c,version:o}:r.failWithoutThrowing(`Failed to parse dependency: ${i}`)}return r.getResult()===Op.Failure&&r.failAndThrow(),{dependencies:n}}var Sol=/^\.\.\/.*$/;function Bol(e){return Sol.test(e)}Vt();var Hus=require("fs/promises");var $us=mt.object({dependencies:mt.record(mt.string(),mt.string())});async function Kus({absolutePathToWorkspace:e,context:t}){let r=We(e,Se.of(uVo));if(!await Xt(r))return;let n=await(0,Hus.readFile)(r),i=wr.load(n.toString());return await Ger({schema:$us,value:i,context:t,filepathBeingParsed:r})}async function ati({absolutePathToWorkspace:e,context:t}){let r=await Kus({absolutePathToWorkspace:e,context:t});return Wus({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}Qt();Her();function ics(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=Jer(e);switch(r){case"dark":return{type:"dark",...Ker(e,t,"dark")};case"light":return{type:"light",...Ker(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:Ker(e,t,"dark"),light:Ker(e,t,"light")};default:xe(r)}}function Jer({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return Uo(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return Uo(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return Uo(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function Ker(e,t,r){let n=$w(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??Uo.random(),i=$w(e.background,t,"background",r);return{accentPrimary:n.toRgb(),background:i?.toRgb(),border:$w(e.border,t,"border",r)?.toRgb(),sidebarBackground:$w(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:$w(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:$w(e.cardBackground,t,"card-background",r)?.toRgb(),accent1:$w(e.accent1,t,"accent-1",r)?.toRgb(),accent2:$w(e.accent2,t,"accent-2",r)?.toRgb(),accent3:$w(e.accent3,t,"accent-3",r)?.toRgb(),accent4:$w(e.accent4,t,"accent-4",r)?.toRgb(),accent5:$w(e.accent5,t,"accent-5",r)?.toRgb(),accent6:$w(e.accent6,t,"accent-6",r)?.toRgb(),accent7:$w(e.accent7,t,"accent-7",r)?.toRgb(),accent8:$w(e.accent8,t,"accent-8",r)?.toRgb(),accent9:$w(e.accent9,t,"accent-9",r)?.toRgb(),accent10:$w(e.accent10,t,"accent-10",r)?.toRgb(),accent11:$w(e.accent11,t,"accent-11",r)?.toRgb(),accent12:$w(e.accent12,t,"accent-12",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function fgt(e,t,r){if(e==null)return;let n=typeof e=="string"?e:e[r];if(n==null&&t==="accent-primary"&&typeof e!="string"&&(n=e[r==="dark"?"light":"dark"]),n!=null)return n}function $w(e,t,r,n){let i=fgt(e,r,n);if(i==null)return;let o=Uo(i);return o.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${n}`}' should be a hex color of the format #FFFFFF`),o}Qt();_g();Vt();var Vor=require("fs/promises");var ZLs=_e(require("path"),1);Qt();Vt();var PMs=require("fs/promises");Ci();var OMs=100;async function lXl({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async n=>{let i=await(0,PMs.readFile)(n,"utf-8");return[Hy(t,n),i]}));return Object.fromEntries(r)}async function TMs({files:e,absolutePathToFernFolder:t}){let r={};for(let n=0;n<e.length;n+=OMs){let i=e.slice(n,n+OMs),o=await lXl({files:i,absolutePathToFernFolder:t});Object.assign(r,o)}return r}function wor({landingPage:e,navigation:t}){return dj([e?.absolutePath,...pXl(t)])}function pXl(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>Ior({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(n=>Ior({item:n}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>Ior({item:t}));case"versioned":return e.versions.flatMap(t=>wor({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:wor({landingPage:t.landingPage,navigation:t.navigation}));default:xe(e)}}function Ior({item:e}){switch(e.type){case"apiSection":return dj([e.overviewAbsolutePath,...e.navigation.flatMap(t=>DMs({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return dj([e.overviewAbsolutePath,...e.contents.flatMap(t=>Ior({item:t}))]);case"changelog":return e.changelog;case"librarySection":return[];default:xe(e)}}function DMs({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?dj([e.overviewAbsolutePath,...e.contents.flatMap(t=>DMs({item:t}))]):[]}Vt();var jor=require("fs/promises"),Bli=_e(f7(),1);function kor({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function Qor({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function YLs({absolutePath:e,readFileFn:t=(r,n)=>(0,jor.readFile)(r,n)}){try{let r=await t(e,"utf-8"),{data:n}=(0,Bli.default)(r);if(n.position==null)return;let i=typeof n.position=="string"?parseFloat(n.position):n.position;return typeof i=="number"&&Number.isFinite(i)?i:void 0}catch{return}}async function Nor({absolutePath:e,readFileFn:t=(r,n)=>(0,jor.readFile)(r,n)}){try{let r=await t(e,"utf-8"),{data:n}=(0,Bli.default)(r);return typeof n.title=="string"&&n.title.trim().length>0?n.title.trim():void 0}catch{return}}async function Oli({directoryPath:e,titleSource:t,getDir:r=ny,readFileFn:n=(i,o)=>(0,jor.readFile)(i,o)}){let i=await r(e),o=t==="frontmatter",s=i.filter(f=>f.type==="file"&&(f.name.toLowerCase().endsWith(".md")||f.name.toLowerCase().endsWith(".mdx"))),a=i.filter(f=>f.type==="directory"),[u,c]=await Promise.all([Promise.all(s.map(f=>YLs({absolutePath:f.absolutePath,readFileFn:n}))),o?Promise.all(s.map(f=>Nor({absolutePath:f.absolutePath,readFileFn:n}))):Promise.resolve(s.map(()=>{}))]),l=s.map((f,m)=>({type:"page",title:c[m]??Qor({name:f.name}),absolutePath:f.absolutePath,slug:kor({name:f.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),p=await Promise.all(a.map(async f=>{let m=await Oli({directoryPath:f.absolutePath,titleSource:t,getDir:r,readFileFn:n}),h=m.find(b=>b.type==="page"&&(b.slug==="index"||b.absolutePath.toLowerCase().endsWith("/index.mdx")||b.absolutePath.toLowerCase().endsWith("/index.md"))),g=h?m.filter(b=>b!==h):m,E=(o&&h?.type==="page"?await Nor({absolutePath:h.absolutePath,readFileFn:n}):void 0)??Qor({name:f.name}),v=h?.type==="page"?await YLs({absolutePath:h.absolutePath,readFileFn:n}):void 0;return{section:{type:"section",title:E,slug:kor({name:f.name}),icon:void 0,contents:g,collapsed:void 0,collapsible:void 0,collapsedByDefault:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:h?.type==="page"?h.absolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0},position:v}})),d=[...l.map((f,m)=>({item:f,title:f.type==="page"?f.title:"",position:u[m]})),...p.map(f=>({item:f.section,title:f.section.type==="section"?f.section.title:"",position:f.position}))];return d.sort((f,m)=>{let h=typeof f.position=="number",g=typeof m.position=="number";if(h&&!g)return-1;if(!h&&g)return 1;if(typeof f.position=="number"&&typeof m.position=="number"){let A=f.position-m.position;return A!==0?A:f.title.localeCompare(m.title,void 0,{sensitivity:"base"})}return f.title.localeCompare(m.title,void 0,{sensitivity:"base"})}),d.map(f=>f.item)}function wtp(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function my(e,t){if(e)return wtp(e)?eb(e,t):e}async function Rli({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:n}){let{instances:i,title:o,tabs:s,products:a,versions:u,navigation:c,navbarLinks:l,footerLinks:p,defaultLanguage:d,metadata:f,redirects:m,logo:h,favicon:g,backgroundImage:A,colors:E,typography:v,layout:b,integrations:I,css:w,js:x,aiChat:C,aiSearch:_,pageActions:R,experimental:U}=e,q=Tbt(e.landingPage,r),z=e.settings?.folderTitleSource,Z=Qtp({tabs:s,products:a,versions:u,navigation:c,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:z}),oe=Z.then(Ge=>TMs({files:wor({navigation:Ge,landingPage:q}),absolutePathToFernFolder:t})),V=Ctp(h,r),K=eb(g,r),be=xtp(A,r),Ce=v!=null?Ntp({rawTypography:v,absoluteFilepathToDocsConfig:r}):void 0,J=_tp(w,r),H=Otp(x,r),ge=srp(f,r),[me,we,Be,le,ue,Fe]=await Promise.all([Z,oe,Ce,J,H,ge]);return{title:o,instances:i,roles:e.roles,libraries:Jtp(e.libraries),pages:we,landingPage:q,navigation:me,navbarLinks:irp(l,r),footerLinks:orp(p),defaultLanguage:d,languages:e.languages,announcement:e.announcement,metadata:Fe,redirects:m?.map(Ge=>({...Ge,permanent:Ge?.permanent})),logo:V,favicon:K,backgroundImage:be,colors:ics(E,n),typography:Be,layout:ktp(b),settings:Ftp(e.settings),theme:Rtp(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,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},integrations:{...I,intercom:I?.intercom?I.intercom:void 0},css:le,js:ue,aiChatConfig:_??C,pageActions:Ptp(R,r),header:eb(e.header,r),footer:eb(e.footer,r),experimental:U}}function Ctp(e,t){return e!=null?{dark:eb(e.dark,t),light:eb(e.light,t),height:e.height,href:e.href!=null?Cr.Url(e.href):void 0,rightText:e.rightText}:void 0}function xtp(e,t){if(e!=null)if(typeof e=="string"){let r=eb(e,t);return{dark:r,light:r}}else{let r=eb(e.dark,t),n=eb(e.light,t);return{dark:r,light:n}}}async function _tp(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async n=>(await(0,Vor.readFile)(eb(n,t))).toString()))}}function Stp(e){return Object.hasOwn(e,"url")}function Btp(e){return Object.hasOwn(e,"path")}async function Otp(e,t){let r=[],n=[];if(e==null)return{files:[]};let i=Array.isArray(e)?e:[e];for(let o of i)typeof o=="string"?n.push({absolutePath:eb(o,t)}):Stp(o)?r.push({strategy:o.strategy,url:Cr.Url(o.url)}):Btp(o)&&n.push({absolutePath:eb(o.path,t),strategy:o.strategy});return{remote:r,files:n}}function Ptp(e,t){return e==null?void 0:{default:e.default!=null?Ttp(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(n=>Dtp(n,t))}}}function Ttp(e){switch(e){case"copy-page":return Cr.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return Cr.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return Cr.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return Cr.docs.v1.commons.PageActionOption.OpenAi;case"claude":return Cr.docs.v1.commons.PageActionOption.Claude;case"cursor":return Cr.docs.v1.commons.PageActionOption.Cursor;case"vscode":return Cr.docs.v1.commons.PageActionOption.Vscode;default:xe(e)}}function Dtp(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:my(e.icon,t),default:e.default}}function Rtp(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function Ftp(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function ktp(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:Mor(e.pageWidth),contentWidth:Mor(e.contentWidth),sidebarWidth:Mor(e.sidebarWidth),headerHeight:Mor(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?Cr.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?Cr.docs.v1.commons.SearchbarPlacement.HeaderTabs:Cr.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?Cr.docs.v1.commons.SwitcherPlacement.Header:Cr.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?Cr.docs.v1.commons.TabsPlacement.Header:Cr.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?Cr.docs.v1.commons.ContentAlignment.Left:Cr.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?Cr.docs.v1.commons.HeaderPosition.Absolute:Cr.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function Mor(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let n=t.match(/^(\d+)rem$/);if(n!=null&&n[1]!=null)return{type:"rem",value:parseFloat(n[1])}}async function XLs({versions:e,absolutePathToFernFolder:t,context:r,folderTitleSource:n}){let i=[];for(let o of e){let s=Ji(t,o.path),a=wr.load((await(0,Vor.readFile)(s)).toString()),u=[],c=hj(a,[],u);u.length>0&&r.logger.warn(`Version file ${o.path} contained null/undefined sections that were ignored: ${u.map(d=>d.join(".")).join(", ")}`);let l=Fw.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(c),p=await Dli({tabs:l.tabs,rawNavigationConfig:l.navigation,absolutePathToFernFolder:t,absolutePathToConfig:s,context:r,folderTitleSource:n});i.push({landingPage:Tbt(l.landingPage,s),version:o.displayName,navigation:p,availability:o.availability,slug:o.slug,hidden:o.hidden,viewers:iC(o.viewers),orphaned:o.orphaned,featureFlags:nC(o.featureFlag),announcement:o.announcement})}return{type:"versioned",versions:i}}async function Qtp({tabs:e,products:t,versions:r,navigation:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:s,folderTitleSource:a}){if(n!=null)return await Dli({tabs:e,rawNavigationConfig:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:s,folderTitleSource:a});if(t!=null){let u=[];for(let c of t){let l=c.image!=null?Ji(i,c.image):void 0;if("path"in c){let p,d=Ji(i,c.path),f=wr.load((await(0,Vor.readFile)(d)).toString()),m=[],h=hj(f,[],m);m.length>0&&s.logger.warn(`Product file ${c.path} contained null/undefined sections that were ignored: ${m.map(A=>A.join(".")).join(", ")}`);let g=Fw.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);c.versions!=null&&c.versions.length>0?p=await XLs({versions:c.versions,absolutePathToFernFolder:i,context:s,folderTitleSource:a}):p=await Dli({tabs:g.tabs,rawNavigationConfig:g.navigation,absolutePathToFernFolder:i,absolutePathToConfig:d,context:s,folderTitleSource:a}),u.push({type:"internal",landingPage:Tbt(g.landingPage,d),product:c.displayName,navigation:p,slug:c.slug,subtitle:c.subtitle,icon:my(c.icon,o)||"fa-solid fa-code",image:l,viewers:iC(c.viewers),orphaned:c.orphaned,featureFlags:nC(c.featureFlag),announcement:c.announcement})}else if("href"in c&&c.href!=null)u.push({type:"external",product:c.displayName,href:c.href,target:c.target,subtitle:c.subtitle,icon:my(c.icon,o)||"fa-solid fa-code",image:l,viewers:iC(c.viewers),orphaned:c.orphaned,featureFlags:nC(c.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:u}}else if(r!=null)return await XLs({versions:r,absolutePathToFernFolder:i,context:s,folderTitleSource:a});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function nC(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function Ntp({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await Pli({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await Pli({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await Pli({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function Pli({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await jtp(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function jtp(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(n=>{typeof n=="string"?r.push({path:n,weight:e.weight,style:e.style}):r.push({path:n.path,weight:n.weight??e.weight,style:n.style??e.style})}),Promise.all(r.map(async n=>({absolutePath:eb(n.path,t),weight:Mtp(n.weight),style:n.style})))}function Mtp(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function Ltp({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o}){let s=e[t.tab];if(s==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(nrp(t)){let a=await Promise.all(t.variants.map(async u=>{let c=await Promise.all(u.layout.map(l=>zor({rawConfig:l,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:u.title,subtitle:u.subtitle,icon:my(u.icon,n),layout:c,slug:u.slug,skipUrlSlug:u.skipSlug,hidden:u.hidden,default:u.default,viewers:iC(u.viewers),orphaned:u.orphaned,featureFlags:nC(u.featureFlag)}}));return{title:s.displayName,icon:my(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"variants",variants:a},viewers:iC(s.viewers),orphaned:s.orphaned,featureFlags:nC(s.featureFlag)}}if(rrp(t)){let a=await Promise.all(t.layout.map(u=>zor({rawConfig:u,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:s.displayName,icon:my(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"layout",layout:a},viewers:iC(s.viewers),orphaned:s.orphaned,featureFlags:nC(s.featureFlag)}}if(s.href!=null)return{title:s.displayName,icon:my(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"link",href:s.href,target:s.target},viewers:iC(s.viewers),orphaned:s.orphaned,featureFlags:nC(s.featureFlag)};if(s.changelog!=null)return{title:s.displayName,icon:my(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"changelog",changelog:await hw(eb(s.changelog,n),"{md,mdx}")},viewers:iC(s.viewers),orphaned:s.orphaned,featureFlags:nC(s.featureFlag)};xe(s)}async function Dli({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o}){return trp(t)?{type:"tabbed",items:await Promise.all(t.map(a=>Ltp({tabs:e,item:a,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}:{type:"untabbed",items:await Promise.all(t.map(s=>zor({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}}var Utp="Changelog";async function ztp({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){let o=eb(e.folder,r);await Xt(o)||n.failAndThrow(`Folder not found: ${e.folder}`),Fli({context:n,sectionTitle:e.folder,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0});let s=e.titleSource??i,a=await Oli({directoryPath:o,titleSource:s}),u=a.find(m=>m.type==="page"&&(m.slug==="index"||m.absolutePath.toLowerCase().endsWith("/index.mdx")||m.absolutePath.toLowerCase().endsWith("/index.md"))),c=u?a.filter(m=>m!==u):a,l=ZLs.default.basename(o),p=s==="frontmatter"&&u?.type==="page"?await Nor({absolutePath:u.absolutePath}):void 0,d=e.title??p??Qor({name:l}),f=e.slug??kor({name:l});return{type:"section",title:d,icon:my(e.icon,r),contents:c,slug:f,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:u?.type==="page"?u.absolutePath:void 0,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag),availability:e.availability}}async function zor({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){if(eUs(e))return Tbt(e,r);if(qtp(e))return Fli({context:n,sectionTitle:e.section,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0}),{type:"section",title:e.section,icon:my(e.icon,r),contents:await Promise.all(e.contents.map(o=>zor({rawConfig:o,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:eb(e.path,r),viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag),availability:e.availability};if(Gtp(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:my(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:Dbt(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?Vtp({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(o=>Uor(o,r,n))??[],overviewAbsolutePath:eb(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)};if(tUs(e))return{type:"link",text:e.link,url:e.href,icon:my(e.icon,r),target:e.target};if(Wtp(e))return{type:"changelog",changelog:await hw(eb(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:my(e.icon,r),title:e.title??Utp,slug:e.slug,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)};if($tp(e))return await ztp({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i});if(Htp(e))return{type:"librarySection",libraryName:e.library,title:e.title??void 0,slug:e.slug??void 0,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)};xe(e)}function Tbt(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:eb(e.path,t),slug:e.slug,icon:my(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag),availability:e.availability}}function Uor(e,t,r){return typeof e=="string"?[{type:"item",value:e}]:eUs(e)?[Tbt(e,t)]:tUs(e)?[{type:"link",text:e.link,url:e.href,icon:my(e.icon,t),target:e.target}]:Ytp(e)?(r!=null&&Fli({context:r,sectionTitle:e.section,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0}),[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:eb(e.summary,t),contents:e.contents?.flatMap(n=>Uor(n,t,r))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,collapsed:e.collapsed??void 0,collapsible:e.collapsible??void 0,collapsedByDefault:e.collapsedByDefault??void 0,availability:e.availability,icon:my(e.icon,t),playground:e.playground,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)}]):Xtp(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:my(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)}]:Ztp(e)?[{type:"operation",operation:e.operation,title:e.title,slug:e.slug,hidden:e.hidden,availability:e.availability,viewers:iC(e.viewers),orphaned:e.orphaned,featureFlags:nC(e.featureFlag)}]:Object.entries(e).map(([n,i])=>erp(i)?{type:"package",title:i.title,package:n,overviewAbsolutePath:eb(i.summary,t),contents:i.contents?.flatMap(o=>Uor(o,t,r))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:my(i.icon,t),playground:i.playground,availability:i.availability,viewers:iC(i.viewers),orphaned:i.orphaned,featureFlags:nC(i.featureFlag)}:{type:"package",title:void 0,package:n,overviewAbsolutePath:void 0,contents:i.flatMap(o=>Uor(o,t,r)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function Vtp({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function eUs(e){return ba(e)&&typeof e.page=="string"&&typeof e.path=="string"}function qtp(e){return e.section!=null}function Gtp(e){return e.api!=null}function tUs(e){return Fw.RawSchemas,ba(e)&&typeof e.link=="string"&&typeof e.href=="string"}function Wtp(e){return ba(e)&&typeof e.changelog=="string"}function $tp(e){return ba(e)&&typeof e.folder=="string"}function Htp(e){return ba(e)&&typeof e.library=="string"}function Ktp(e){return"git"in e}function Jtp(e){if(e==null)return;let t={};for(let[r,n]of Object.entries(e)){if(!Ktp(n.input))throw new Error(`Library '${r}' uses 'path' input which is not yet supported. Please use 'git' input.`);t[r]={input:{git:n.input.git,subpath:n.input.subpath},output:{path:n.output.path},lang:n.lang}}return t}function Ytp(e){return ba(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function Xtp(e){return ba(e)&&typeof e.endpoint=="string"}function Ztp(e){return ba(e)&&typeof e.operation=="string"}function erp(e){return!Array.isArray(e)}function eb(e,t){if(e!=null)return Ji(vn(t),e)}function trp(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function rrp(e){return"layout"in e&&Array.isArray(e.layout)}function nrp(e){return"variants"in e&&Array.isArray(e.variants)}function irp(e,t){return e?.map(r=>{if(r.type==="github"){let i=r.value;return typeof i=="string"?{type:"github",url:Cr.Url(i),viewers:void 0,target:void 0}:{type:"github",url:Cr.Url(i.url),viewers:Tli(i.viewers),target:i.target}}let n=Tli(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:my(r.icon,t),rightIcon:my(r.rightIcon,t),rounded:r.rounded,viewers:n,links:r.links?.map(i=>({href:i.href,target:i.target,url:Cr.Url(i.url??i.href??"/"),text:i.text,icon:my(i.icon,t),rightIcon:my(i.rightIcon,t),rounded:i.rounded,viewers:Tli(i.viewers)}))??[]}:{type:r.type,text:r.text,url:Cr.Url(r.href??r.url??"/"),target:r.target,icon:my(r.icon,t),rightIcon:my(r.rightIcon,t),rounded:r.rounded,viewers:n}})}function Tli(e){if(e!=null)return Array.isArray(e)?e.map(t=>Cr.RoleId(t)):[Cr.RoleId(e)]}function orp(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let n=e[r];n!=null&&t.push({type:r,value:Cr.Url(n)})}),t.length!==0)return t}async function srp(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await Lor(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await Lor(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await Lor(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,"og:dynamic":e.ogDynamic,"og:background-image":await Lor(e.ogBackgroundImage,t),nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function Lor(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=eb(e,t);return await Xt(r)?{type:"filepath",value:r}:{type:"url",value:e}}function iC(e){if(e!=null){if(typeof e=="string")return[Cr.RoleId(e)];if(e.length!==0)return e.map(Cr.RoleId)}}function Dbt(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}function Fli({context:e,sectionTitle:t,collapsed:r,collapsible:n,collapsedByDefault:i}){n!=null&&r!=null&&e.failAndThrow(`Section "${t}": cannot use both "collapsible" and the deprecated "collapsed" property. Please use "collapsible" and "collapsed-by-default" instead.`),i!=null&&n!==!0&&e.failAndThrow(`Section "${t}": "collapsed-by-default" requires "collapsible: true". "collapsed-by-default" has no effect on a non-collapsible section.`)}Vt();var nUs=require("fs/promises");var rUs=mt.strictObject({organization:mt.string(),version:mt.string()});async function dQ({directory:e,context:t}){let r=We(e,Se.of(Ub)),n=await(0,nUs.readFile)(r),i=JSON.parse(n.toString()),o=await Ger({schema:rUs,value:i,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:o,organization:o.organization,version:o.version}}var et={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var tdi=_e(q1(),1);var Rbt={[et.JAVA]:{version:"2.38.1"},[et.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[et.JAVA_MODEL]:{version:"1.0.0"},[et.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[et.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[et.TYPESCRIPT]:{version:"0.0.247"},[et.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[et.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[et.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[et.PYTHON_PYDANTIC]:{version:"1.4.7"},[et.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[et.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[et.GO_MODEL]:{version:"0.23.5"},[et.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[et.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[et.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[et.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[et.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[et.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[et.CSHARP_MODEL]:{version:"0.0.1"},[et.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[et.SWIFT_MODEL]:{version:"0.0.0"},[et.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[et.PHP_MODEL]:{version:"0.0.0"},[et.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[et.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[et.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var Fbt="fernapi",nBe="fern-api";function oC(e){return e=F5e(e),e.includes("/")?e:`${Fbt}/${e}`}function F5e(e){let t=`${nBe}/`;return e.startsWith(t)?`${Fbt}/${e.slice(t.length)}`:e}function kli(e,t){let r=`${nBe}/`;if(e.startsWith(r)){let n=`${Fbt}/${e.slice(r.length)}`;return t.logger.warn(`"${e}" is not a valid generator name. Using "${n}" instead \u2014 the Docker org is "fernapi", not "fern-api".`),n}return e}function Qli(e){let t=`${Fbt}/`;return e.startsWith(t)?e.slice(t.length):e}function Nli(e,t){let r=iBe(e);return r??t.failAndThrow("Unrecognized generator: "+e)}var arp={"fernapi/java-model":et.JAVA_MODEL,"fernapi/fern-typescript-node-sdk":et.TYPESCRIPT_SDK};function iBe(e){e=oC(e);let t=arp[e];if(t!=null&&(e=t),urp(e))return e}function urp(e){return Object.values(et).includes(e)}var Par=_e(g8e(),1),uqs=_e(q1(),1);async function jS({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:n,includeMajor:i,context:o}){let s=uqs.default.parse(n),a="https://registry.buildwithfern.com",u=new Par.FernRegistryClient({environment:a});o?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${i}, prior version: ${s}, FDR origin: ${a}`);let c={generator:jhp(e,o),releaseTypes:[r??Par.FernRegistry.generators.ReleaseType.Ga],cliVersion:t};!i&&s!=null&&(c.generatorMajorVersion=s.major),o?.logger.debug(`[FDR] getLatestGeneratorRelease request: ${JSON.stringify(c)}`);let l=await u.generators.versions.getLatestGeneratorRelease(c);if(l.ok)return o?.logger.debug(`[FDR] getLatestGeneratorRelease response for ${e}: version=${l.body.version}, irVersion=${l.body.irVersion}`),l.body.version;o?.logger.debug(`[FDR] getLatestGeneratorRelease failed for ${e}: ${JSON.stringify(l)}`)}function jhp(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript":case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":case"java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function cqs({generatorsConfiguration:e,groupName:t=e[yn.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:n}){if(t==null)return r.failAndThrow("No group specified.");let i=e.groups??={},o=i[t];if(o==null){let s=i[t]??={generators:[]};await n(s,t)}else await n(o,t);return e}async function rdi({generatorName:e,generatorsConfiguration:t,groupName:r=t[c4e],context:n,cliVersion:i}){let o=Nli(e,n),s=Qli(o),a=Rbt[o];return await cqs({generatorsConfiguration:t,groupName:r,context:n,update:async u=>{u.generators.some(p=>oC(p.name)===o)&&n.failAndThrow(`${e} is already installed in group ${r}.`);let c=await jS({cliVersion:i,generatorName:o,context:n,channel:void 0}),l=c!=null&&tdi.default.valid(c)&&tdi.default.gt(c,a.version)?c:a.version;u.generators.push({name:s,...a,version:l})}})}Qt();Vt();Nre();var Kp=_e(aoe(),1),nhi=_e(Bc(),1),TJs=require("fs/promises"),DJs=_e(require("path"),1);var RJs={shouldUseTitleAsName:void 0,shouldUseUndiscriminatedUnionsWithLiterals:void 0,shouldUseIdiomaticRequestNames:void 0,asyncApiMessageNaming:void 0,onlyIncludeReferencedSchemas:void 0,shouldUseOptionalAdditionalProperties:void 0,coerceEnumsToLiterals:void 0,objectQueryParameters:void 0,respectReadonlySchemas:void 0,respectNullableSchemas:void 0,inlinePathParameters:void 0,useBytesForBinaryResponse:void 0,respectForwardCompatibleEnums:void 0,filter:void 0,exampleGeneration:void 0,defaultFormParameterEncoding:void 0,additionalPropertiesDefaultsTo:void 0,typeDatesAsStrings:void 0,preserveSingleSchemaOneOf:void 0,inlineAllOfSchemas:void 0,resolveAliases:void 0,groupMultiApiEnvironments:void 0,groupEnvironmentsByHost:void 0,wrapReferencesToNullableInOptional:void 0,coerceOptionalSchemasToNullable:void 0,removeDiscriminantsFromSchemas:void 0,pathParameterOrder:void 0,defaultIntegerFormat:void 0,resolveSchemaCollisions:void 0,inferForwardCompatible:void 0,coerceConstsTo:void 0};async function FJs({absolutePathToGeneratorsConfiguration:e,rawGeneratorsConfiguration:t,context:r}){let n=MJs(t.metadata),i=t.readme;u_p(r,t);let o=await Jxp(t);return{absolutePathToConfiguration:e,api:o,rawConfiguration:t,defaultGroup:t["default-group"],groupAliases:t.aliases??{},reviewers:t.reviewers,groups:t.groups!=null?await Promise.all(Object.entries(t.groups).map(([s,a])=>Yxp({absolutePathToGeneratorsConfiguration:e,groupName:s,group:a,maybeTopLevelMetadata:n,maybeTopLevelReviewers:t.reviewers,readme:i,context:r}))):[],whitelabel:t.whitelabel!=null&&t.whitelabel.github!=null?{github:t.whitelabel.github}:void 0,ai:t.ai,replay:t.replay}}function tcr(e){return{...RJs,shouldUseTitleAsName:e?.["use-title"],shouldUseUndiscriminatedUnionsWithLiterals:e?.unions==="v1",asyncApiMessageNaming:e?.["message-naming"],respectNullableSchemas:e?.["respect-nullable-schemas"],wrapReferencesToNullableInOptional:e?.["wrap-references-to-nullable-in-optional"],coerceOptionalSchemasToNullable:e?.["coerce-optional-schemas-to-nullable"],onlyIncludeReferencedSchemas:e?.["only-include-referenced-schemas"],inlinePathParameters:e?.["inline-path-parameters"],shouldUseIdiomaticRequestNames:e?.["idiomatic-request-names"],removeDiscriminantsFromSchemas:QJs(e?.["remove-discriminants-from-schemas"]),pathParameterOrder:e?.["path-parameter-order"]}}function kJs(e){return{...rcr(e),shouldUseUndiscriminatedUnionsWithLiterals:e?.["prefer-undiscriminated-unions-with-literals"],onlyIncludeReferencedSchemas:e?.["only-include-referenced-schemas"],objectQueryParameters:e?.["object-query-parameters"],respectReadonlySchemas:e?.["respect-readonly-schemas"],inlinePathParameters:e?.["inline-path-parameters"],filter:e?.filter,exampleGeneration:e?.["example-generation"],defaultFormParameterEncoding:e?.["default-form-parameter-encoding"],useBytesForBinaryResponse:e?.["use-bytes-for-binary-response"],respectForwardCompatibleEnums:e?.["respect-forward-compatible-enums"],additionalPropertiesDefaultsTo:e?.["additional-properties-defaults-to"],typeDatesAsStrings:e?.["type-dates-as-strings"],preserveSingleSchemaOneOf:e?.["preserve-single-schema-oneof"],inlineAllOfSchemas:e?.["inline-all-of-schemas"],resolveAliases:e?.["resolve-aliases"],groupMultiApiEnvironments:e?.["group-multi-api-environments"],groupEnvironmentsByHost:e?.["group-environments-by-host"],defaultIntegerFormat:e?.["default-integer-format"],pathParameterOrder:e?.["path-parameter-order"]}}function Hxp(e){return{...rcr(e),asyncApiMessageNaming:e?.["message-naming"]}}function rcr(e){return{...RJs,shouldUseTitleAsName:e?.["title-as-schema-name"],shouldUseIdiomaticRequestNames:e?.["idiomatic-request-names"],shouldUseOptionalAdditionalProperties:e?.["optional-additional-properties"],coerceEnumsToLiterals:e?.["coerce-enums-to-literals"],respectNullableSchemas:e?.["respect-nullable-schemas"],wrapReferencesToNullableInOptional:e?.["wrap-references-to-nullable-in-optional"],coerceOptionalSchemasToNullable:e?.["coerce-optional-schemas-to-nullable"],groupEnvironmentsByHost:e?.["group-environments-by-host"],groupMultiApiEnvironments:e!=null&&"group-multi-api-environments"in e?e["group-multi-api-environments"]:void 0,removeDiscriminantsFromSchemas:QJs(e?.["remove-discriminants-from-schemas"]),pathParameterOrder:e?.["path-parameter-order"],resolveSchemaCollisions:e?.["resolve-schema-collisions"],inferForwardCompatible:e?.["infer-forward-compatible"],coerceConstsTo:e?.["coerce-consts-to"]}}function QJs(e){if(e==null||e==="always")return yn.RemoveDiscriminantsFromSchemas.Always;if(e==="never")return yn.RemoveDiscriminantsFromSchemas.Never;throw new Error(`Unknown value for generators.yml API setting: remove-discriminants-from-schemas: ${e}`)}function Cde(e,t){return{...e,...Object.fromEntries(Object.entries(t).filter(([r,n])=>n!==void 0))}}async function PJs(e,t,r){let n=[];if(e!=null)if(typeof e=="string")n.push({schema:{type:"oss",path:e},origin:void 0,overrides:void 0,overlays:void 0,audiences:[],settings:r});else if(yn.isRawProtobufAPIDefinitionSchema(e))n.push({schema:{type:"protobuf",root:e.proto.root,target:e.proto.target??"",localGeneration:e.proto["local-generation"]??!1,fromOpenAPI:e.proto["from-openapi"]??!1,dependencies:e.proto.dependencies??[]},origin:void 0,overrides:e.proto.overrides,overlays:void 0,audiences:[],settings:r});else if(Array.isArray(e))for(let i of e)typeof i=="string"?n.push({schema:{type:"oss",path:i},origin:void 0,overrides:void 0,overlays:void 0,audiences:[],settings:r}):yn.isRawProtobufAPIDefinitionSchema(i)?n.push({schema:{type:"protobuf",root:i.proto.root,target:i.proto.target??"",localGeneration:i.proto["local-generation"]??!1,fromOpenAPI:i.proto["from-openapi"]??!1,dependencies:i.proto.dependencies??[]},origin:void 0,overrides:i.proto.overrides,overlays:void 0,audiences:[],settings:r}):n.push({schema:{type:"oss",path:i.path},origin:i.origin,overrides:i.overrides,overlays:void 0,audiences:i.audiences,settings:Cde(r,tcr(i.settings))});else n.push({schema:{type:"oss",path:e.path},origin:e.origin,overrides:e.overrides,overlays:void 0,audiences:e.audiences,settings:Cde(r,tcr(e.settings))});else{let i=t[yn.API_SETTINGS_KEY],o=t[yn.OPENAPI_LOCATION_KEY],s=t[yn.API_ORIGIN_LOCATION_KEY],a=t[yn.OPENAPI_OVERRIDES_LOCATION_KEY],u=t[yn.ASYNC_API_LOCATION_KEY];o!=null&&(typeof o=="string"?n.push({schema:{type:"oss",path:o},origin:s,overrides:a,overlays:void 0,audiences:[],settings:Cde(r,tcr(i))}):typeof o=="object"&&n.push({schema:{type:"oss",path:o.path},origin:o.origin,overrides:o.overrides,overlays:void 0,audiences:[],settings:Cde(r,kJs(o.settings))})),u!=null&&n.push({schema:{type:"oss",path:u},origin:s,overrides:void 0,overlays:void 0,audiences:[],settings:Cde(r,tcr(i))})}return n}async function Kxp({apiConfiguration:e,rawConfiguration:t,apiSettings:r}){let n={"auth-schemes":t["auth-schemes"],...e};if(yn.isConjureSchema(e.specs))return{type:"conjure",pathToConjureDefinition:e.specs.conjure,...n,settings:r};let i=[],o={};for(let s of e.specs??[]){let a;if(yn.isOpenApiSpecSchema(s))a={schema:{type:"oss",path:s.openapi},origin:s.origin,overrides:s.overrides,overlays:s.overlays,audiences:[],settings:Cde(r,kJs(s.settings))};else if(yn.isAsyncApiSpecSchema(s))a={schema:{type:"oss",path:s.asyncapi},origin:s.origin,overrides:s.overrides,overlays:void 0,audiences:[],settings:Cde(r,Hxp(s.settings))};else if(yn.isProtoSpecSchema(s))a={schema:{type:"protobuf",root:s.proto.root,target:s.proto.target??"",localGeneration:s.proto["local-generation"]??!1,fromOpenAPI:s.proto["from-openapi"]??!1,dependencies:s.proto.dependencies??[]},origin:void 0,overrides:s.proto.overrides,overlays:void 0,audiences:[],settings:r};else if(yn.isOpenRpcSpecSchema(s))a={schema:{type:"openrpc",path:s.openrpc},origin:void 0,overrides:s.overrides,overlays:void 0,audiences:[],settings:r};else if(yn.isGraphQLSpecSchema(s))a={schema:{type:"graphql",path:s.graphql},origin:s.origin,overrides:s.overrides,overlays:void 0,audiences:[],settings:r};else continue;let u=yn.isGraphQLSpecSchema(s)&&"name"in s?s.name:"namespace"in s?s.namespace:void 0;u!=null?(o[u]??=[],o[u].push(a)):i.push(a)}return Object.keys(o).length===0?{type:"singleNamespace",definitions:i,...n,settings:r}:{type:"multiNamespace",rootDefinitions:i,definitions:o,...n,settings:r}}async function Jxp(e){let t=e.api;if(t!=null){if(yn.isApiConfigurationV2Schema(t)){let n=rcr(t.settings);return Kxp({apiConfiguration:t,rawConfiguration:e,apiSettings:n})}if(yn.isNamespacedApiConfiguration(t)){let n={},i={};for(let[o,s]of Object.entries(t.namespaces))n[o]=await PJs(s,e,i);return{type:"multiNamespace",rootDefinitions:void 0,definitions:n}}}return{type:"singleNamespace",definitions:await PJs(t,e,{})}}async function Yxp({absolutePathToGeneratorsConfiguration:e,groupName:t,group:r,maybeTopLevelMetadata:n,maybeTopLevelReviewers:i,readme:o,context:s}){let a=MJs(r.metadata);return{groupName:t,reviewers:r.reviewers,audiences:r.audiences==null?{type:"all"}:{type:"select",audiences:r.audiences},generators:await Promise.all(r.generators.map(u=>Xxp({absolutePathToGeneratorsConfiguration:e,generator:u,maybeTopLevelMetadata:n,maybeGroupLevelMetadata:a,maybeTopLevelReviewers:i,maybeGroupLevelReviewers:r.reviewers,readme:o,context:s})))}}async function Xxp({absolutePathToGeneratorsConfiguration:e,generator:t,maybeGroupLevelMetadata:r,maybeTopLevelMetadata:n,maybeGroupLevelReviewers:i,maybeTopLevelReviewers:o,readme:s,context:a}){let u=kli(t.name,a),c=oC(u);return{raw:t,name:c,version:t.version,config:t.config,outputMode:await r_p({absolutePathToGeneratorsConfiguration:e,generator:t,maybeGroupLevelMetadata:r,maybeTopLevelMetadata:n,maybeGroupLevelReviewers:i,maybeTopLevelReviewers:o}),keywords:t.keywords,smartCasing:t["smart-casing"]??!0,disableExamples:t["disable-examples"]??!1,absolutePathToLocalOutput:t.output?.location==="local-file-system"?Ji(vn(e),t.output.path):void 0,absolutePathToLocalSnippets:t.snippets?.path!=null?Ji(vn(e),t.snippets.path):void 0,language:o_p(c),irVersionOverride:t["ir-version"]??void 0,publishMetadata:e_p({generatorInvocation:t}),readme:s,settings:t.api?.settings??void 0,apiOverride:Zxp({generator:t})}}function Zxp({generator:e}){if(e.api?.specs!=null||e.api?.auth!=null||e.api?.["auth-schemes"]!=null||e.api?.headers!=null)return{specs:e.api?.specs,auth:e.api?.auth,"auth-schemes":e.api?.["auth-schemes"],headers:e.api?.headers}}function e_p({generatorInvocation:e}){let t=e["publish-metadata"];if(t!=null)return{packageDescription:t["package-description"],publisherEmail:t.email,publisherName:t.author,referenceUrl:t["reference-url"]};if(e.metadata!=null)return{packageDescription:e.metadata["package-description"],publisherEmail:e.metadata.email,publisherName:e.metadata.author,referenceUrl:e.metadata["reference-url"]}}function NJs({pypiOutputMetadata:e,maybeGroupLevelMetadata:t,maybeTopLevelMetadata:r}){let n;return e!=null&&(n=a_p(e),n={...r,...t,...n}),n}function t_p({topLevelReviewers:e,groupLevelReviewers:t,outputModeReviewers:r}){let n=new Set,i=new Set,o=[],s=[...e?.teams??[],...t?.teams??[],...r?.teams??[]],a=[...e?.users??[],...t?.users??[],...r?.users??[]];for(let u of s)n.has(u.name)||(o.push(nhi.GithubPullRequestReviewer.team({name:u.name})),n.add(u.name));for(let u of a)i.has(u.name)||(o.push(nhi.GithubPullRequestReviewer.user({name:u.name})),i.add(u.name));return o}async function r_p({absolutePathToGeneratorsConfiguration:e,generator:t,maybeGroupLevelMetadata:r={},maybeTopLevelMetadata:n={},maybeGroupLevelReviewers:i,maybeTopLevelReviewers:o}){let s=t.snippets!=null&&t.snippets.path!=="";if(t.github){let a=xde(t.github)?t.github.uri:t.github.repository,{owner:u,repo:c}=qO(a),l=t.output!=null?i_p(t.output,r,n):void 0,p=s_p(t),d=p!=null?await n_p({absolutePathToGeneratorsConfiguration:e,githubLicense:p}):void 0,f=t.github.mode??"release";switch(f){case"commit":case"release":return Kp.FernFiddle.OutputMode.githubV2(Kp.FernFiddle.GithubOutputModeV2.commitAndRelease({owner:u,repo:c,license:d,publishInfo:l,downloadSnippets:s}));case"pull-request":{let m=t.github,h=t_p({topLevelReviewers:o,groupLevelReviewers:i,outputModeReviewers:m.reviewers});return Kp.FernFiddle.OutputMode.githubV2(Kp.FernFiddle.GithubOutputModeV2.pullRequest({owner:u,repo:c,license:d,publishInfo:l,downloadSnippets:s,reviewers:h,branch:m.branch}))}case"push":return Kp.FernFiddle.OutputMode.githubV2(Kp.FernFiddle.GithubOutputModeV2.push({owner:u,repo:c,branch:t.github.mode==="push"?t.github.branch:void 0,license:d,publishInfo:l,downloadSnippets:s}));default:xe(f)}}if(t.output==null)return Kp.FernFiddle.remoteGen.OutputMode.publish({registryOverrides:{}});switch(t.output.location){case"local-file-system":return Kp.FernFiddle.OutputMode.downloadFiles({downloadSnippets:s});case"npm":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.npmOverride({registryUrl:t.output.url??"https://registry.npmjs.org",packageName:t.output["package-name"],token:t.output.token??"",downloadSnippets:s}));case"maven":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.mavenOverride({registryUrl:jJs(t.output),username:t.output.username??"",password:t.output.password??"",coordinate:t.output.coordinate,signature:t.output.signature!=null?{keyId:t.output.signature.keyId,secretKey:t.output.signature.secretKey,password:t.output.signature.password}:void 0,downloadSnippets:s}));case"postman":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.postman({apiKey:t.output["api-key"],workspaceId:t.output["workspace-id"]}));case"pypi":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.pypiOverride({registryUrl:t.output.url??"https://upload.pypi.org/legacy/",username:t.output.token!=null?"__token__":t.output.password??"",password:t.output.token??t.output.password??"",coordinate:t.output["package-name"],downloadSnippets:s,pypiMetadata:NJs({pypiOutputMetadata:t.output.metadata,maybeGroupLevelMetadata:r,maybeTopLevelMetadata:n})}));case"nuget":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.nugetOverride({registryUrl:t.output.url??"https://nuget.org/",packageName:t.output["package-name"],apiKey:t.output["api-key"]??"",downloadSnippets:s}));case"rubygems":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.rubyGemsOverride({registryUrl:t.output.url??"https://rubygems.org/",packageName:t.output["package-name"],apiKey:t.output["api-key"]??"",downloadSnippets:s}));case"crates":return Kp.FernFiddle.OutputMode.publishV2(Kp.FernFiddle.remoteGen.PublishOutputModeV2.cratesOverride({registryUrl:t.output.url??"https://crates.io/api/v1/crates",packageName:t.output["package-name"],token:t.output.token??"",downloadSnippets:s}));default:xe(t.output)}}async function n_p({absolutePathToGeneratorsConfiguration:e,githubLicense:t}){if(typeof t=="string")switch(t){case"MIT":return Kp.FernFiddle.GithubLicense.basic({id:Kp.FernFiddle.GithubLicenseId.Mit});case"Apache-2.0":return Kp.FernFiddle.GithubLicense.basic({id:Kp.FernFiddle.GithubLicenseId.Apache});default:xe(t)}let r=We(Ut.of(DJs.default.dirname(e)),Se.of(t.custom)),n=await(0,TJs.readFile)(r);return Kp.FernFiddle.GithubLicense.custom({contents:n.toString()})}function i_p(e,t,r){switch(e.location){case"local-file-system":throw new Error("Cannot use local-file-system with github publishing");case"npm":return Kp.FernFiddle.GithubPublishInfo.npm({registryUrl:e.url??"https://registry.npmjs.org",packageName:e["package-name"],token:e.token});case"maven":return Kp.FernFiddle.GithubPublishInfo.maven({registryUrl:jJs(e),coordinate:e.coordinate,credentials:e.username!=null&&e.password!=null?{username:e.username,password:e.password}:void 0,signature:e.signature!=null?{keyId:e.signature.keyId,password:e.signature.password,secretKey:e.signature.secretKey}:void 0});case"postman":return Kp.FernFiddle.GithubPublishInfo.postman({apiKey:e["api-key"],workspaceId:e["workspace-id"]});case"pypi":return Kp.FernFiddle.GithubPublishInfo.pypi({registryUrl:e.url??"https://upload.pypi.org/legacy/",packageName:e["package-name"],credentials:e.token!=null?{username:"__token__",password:e.token}:{username:e.username??"",password:e.password??""},pypiMetadata:NJs({pypiOutputMetadata:e.metadata,maybeGroupLevelMetadata:t,maybeTopLevelMetadata:r})});case"nuget":return Kp.FernFiddle.GithubPublishInfo.nuget({registryUrl:e.url??"https://nuget.org/",packageName:e["package-name"],apiKey:e["api-key"]});case"rubygems":return Kp.FernFiddle.GithubPublishInfo.rubygems({registryUrl:e.url??"https://rubygems.org/",packageName:e["package-name"],apiKey:e["api-key"]});case"crates":return Kp.FernFiddle.GithubPublishInfo.crates({registryUrl:e.url??"https://crates.io/api/v1/crates",packageName:e["package-name"],token:e.token});default:xe(e)}}function o_p(e){if(e.includes("csharp"))return yn.GenerationLanguage.CSHARP;if(e.includes("go"))return yn.GenerationLanguage.GO;if(e.includes("java")||e.includes("spring"))return yn.GenerationLanguage.JAVA;if(e.includes("php"))return yn.GenerationLanguage.PHP;if(e.includes("python")||e.includes("fastapi")||e.includes("pydantic"))return yn.GenerationLanguage.PYTHON;if(e.includes("ruby"))return yn.GenerationLanguage.RUBY;if(e.includes("swift"))return yn.GenerationLanguage.SWIFT;if(e.includes("typescript"))return yn.GenerationLanguage.TYPESCRIPT}function jJs(e){return e.url!=null?e.url:e.signature!=null?"https://oss.sonatype.org/service/local/staging/deploy/maven2/":"https://s01.oss.sonatype.org/content/repositories/releases/"}function s_p(e){return e["publish-metadata"]?.license!=null?e["publish-metadata"].license:e.metadata?.license!=null?e.metadata.license:xde(e.github)&&e.github.license!=null?e.github.license:e.github?.license}function MJs(e){return e!=null?{description:e.description,authors:e.authors?.map(t=>({name:t.name,email:t.email}))}:void 0}function a_p(e){return e!=null?{description:e.description,authors:e.authors?.map(t=>({name:t.name,email:t.email})),keywords:e.keywords,documentationLink:e["documentation-link"],homepageLink:e["homepage-link"]}:void 0}function u_p(e,t){let r=[];t["api-settings"]!=null&&r.push('"api-settings" is deprecated. Please use "api.settings" for global defaults or "api.specs[].settings" for spec-specific settings instead.'),t["async-api"]!=null&&r.push('"async-api" is deprecated. Please use "api.specs[].asyncapi" instead.'),t.openapi!=null&&r.push('"openapi" is deprecated. Please use "api.specs[].openapi" instead.'),t["openapi-overrides"]!=null&&r.push('"openapi-overrides" is deprecated. Please use "api.specs[].overrides" instead.'),t["spec-origin"]&&r.push('"spec-origin" is deprecated. Please use "api.specs[].origin" instead.'),t.api!=null&&(typeof t.api=="string"&&r.push('Using an OpenAPI or AsyncAPI path string for "api" is deprecated. Please use "api.specs[].openapi" or "api.specs[].asyncapi" instead.'),Array.isArray(t.api)?r.push('Using an array for "api" is deprecated. Please use "api.specs[].openapi", "api.specs[].asyncapi", or "api.specs[].proto" instead.'):typeof t.api=="object"&&("path"in t.api&&r.push('Using "api.path" is deprecated. Please use "api.specs[].openapi" or "api.specs[].asyncapi" instead.'),"proto"in t.api&&r.push('Using "api.proto" is deprecated. Please use "api.specs[].proto" instead.'),"namespaces"in t.api&&r.push('Using "api.namespaces" is deprecated. Please use "api.specs[].openapi", "api.specs[].asyncapi", or "api.specs[].proto" with the "namespace" property instead.'))),r.length>0&&(e.logger.warn("Warnings for generators.yml:"),e.logger.warn(" "+r.join(`
1499
1499
  `)))}function xde(e){return e==null?!1:"uri"in e&&"token"in e}Vt();var LJs=require("fs/promises");var UJs=_e(require("path"),1);async function H8e({absolutePathToWorkspace:e,context:t,lenient:r}){let n=await _de({absolutePathToWorkspace:e});if(n==null)return;let i=await(0,LJs.readFile)(n);try{let o=wr.load(i.toString()),s=yn.serialization.GeneratorsConfigurationSchema.parse(o,{allowUnrecognizedEnumValues:r===!0,unrecognizedObjectKeys:r===!0?"passthrough":"fail",allowUnrecognizedUnionMembers:r===!0,skipValidation:!1,breadcrumbsPrefix:void 0,omitUndefined:!1});if(s.ok)return s.value;throw new Error(s.errors.map(a=>a.message).join(`
@@ -1540,7 +1540,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
1540
1540
  `):" "+gia(s[0]):"as no adapter specified";throw new no("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}var Spr={getAdapter:i2p,adapters:xbi};function _bi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new xQ(null,e)}function Bpr(e){return _bi(e),e.headers=ib.from(e.headers),e.data=QEt.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Spr.getAdapter(e.adapter||k6e.adapter,e)(e).then(function(n){return _bi(e),n.data=QEt.call(e,e.transformResponse,n),n.headers=ib.from(n.headers),n},function(n){return NEt(n)||(_bi(e),n&&n.response&&(n.response.data=QEt.call(e,e.transformResponse,n.response),n.response.headers=ib.from(n.response.headers))),Promise.reject(n)})}var Opr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Opr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var Aia={};Opr.transitional=function(t,r,n){function i(o,s){return"[Axios v"+hOe+"] Transitional option '"+o+"'"+s+(n?". "+n:"")}return(o,s,a)=>{if(t===!1)throw new no(i(s," has been removed"+(r?" in "+r:"")),no.ERR_DEPRECATED);return r&&!Aia[s]&&(Aia[s]=!0,console.warn(i(s," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,s,a):!0}};Opr.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function o2p(e,t,r){if(typeof e!="object")throw new no("options must be an object",no.ERR_BAD_OPTION_VALUE);let n=Object.keys(e),i=n.length;for(;i-- >0;){let o=n[i],s=t[o];if(s){let a=e[o],u=a===void 0||s(a,o,e);if(u!==!0)throw new no("option "+o+" must be "+u,no.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new no("Unknown option "+o,no.ERR_BAD_OPTION)}}var qEt={assertOptions:o2p,validators:Opr};var R4=qEt.validators,L6e=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Vyi,response:new Vyi}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;let o=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
1541
1541
  `+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=x6(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&qEt.assertOptions(n,{silentJSONParsing:R4.transitional(R4.boolean),forcedJSONParsing:R4.transitional(R4.boolean),clarifyTimeoutError:R4.transitional(R4.boolean),legacyInterceptorReqResOrdering:R4.transitional(R4.boolean)},!1),i!=null&&(Gt.isFunction(i)?r.paramsSerializer={serialize:i}:qEt.assertOptions(i,{encode:R4.function,serialize:R4.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),qEt.assertOptions(r,{baseUrl:R4.spelling("baseURL"),withXsrfToken:R4.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&Gt.merge(o.common,o[r.method]);o&&Gt.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),r.headers=ib.concat(s,o);let a=[],u=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;u=u&&h.synchronous;let g=r.transitional||zde;g&&g.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});let c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let l,p=0,d;if(!u){let m=[Bpr.bind(this),void 0];for(m.unshift(...a),m.push(...c),d=m.length,l=Promise.resolve(r);p<d;)l=l.then(m[p++],m[p++]);return l}d=a.length;let f=r;for(;p<d;){let m=a[p++],h=a[p++];try{f=m(f)}catch(g){h.call(this,g);break}}try{l=Bpr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=c.length;p<d;)l=l.then(c[p++],c[p++]);return l}getUri(t){t=x6(this.defaults,t);let r=fOe(t.baseURL,t.url,t.allowAbsoluteUrls);return pOe(r,t.params,t.paramsSerializer)}};Gt.forEach(["delete","get","head","options"],function(t){L6e.prototype[t]=function(r,n){return this.request(x6(n||{},{method:t,url:r,data:(n||{}).data}))}});Gt.forEach(["post","put","patch"],function(t){function r(n){return function(o,s,a){return this.request(x6(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}L6e.prototype[t]=r(),L6e.prototype[t+"Form"]=r(!0)});var GEt=L6e;var Sbi=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 xQ(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}}},yia=Sbi;function Bbi(e){return function(r){return e.apply(null,r)}}function Obi(e){return Gt.isObject(e)&&e.isAxiosError===!0}var Pbi={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(Pbi).forEach(([e,t])=>{Pbi[t]=e});var bia=Pbi;function Eia(e){let t=new GEt(e),r=TEt(GEt.prototype.request,t);return Gt.extend(r,GEt.prototype,t,{allOwnKeys:!0}),Gt.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Eia(x6(e,i))},r}var wv=Eia(k6e);wv.Axios=GEt;wv.CanceledError=xQ;wv.CancelToken=yia;wv.isCancel=NEt;wv.VERSION=hOe;wv.toFormData=Ude;wv.AxiosError=no;wv.Cancel=wv.CanceledError;wv.all=function(t){return Promise.all(t)};wv.spread=Bbi;wv.isAxiosError=Obi;wv.mergeConfig=x6;wv.AxiosHeaders=ib;wv.formToJSON=e=>Ipr(Gt.isHTMLForm(e)?new FormData(e):e);wv.getAdapter=Spr.getAdapter;wv.HttpStatusCode=bia;wv.default=wv;var Xb=wv;var{Axios:hiy,AxiosError:via,CanceledError:giy,isCancel:Aiy,CancelToken:yiy,VERSION:biy,all:Eiy,Cancel:viy,isAxiosError:Iiy,spread:wiy,toFormData:Ciy,AxiosHeaders:xiy,HttpStatusCode:_iy,formToJSON:Siy,getAdapter:Biy,mergeConfig:Oiy}=Xb;var Doa=require("fs"),X6e=require("fs/promises");var Roa=require("os"),Foa=_e(require("path"),1),koa=require("stream/promises");var Xia=_e(require("events"),1),CP=_e(require("fs"),1),ofr=require("events"),_0i=_e(require("stream"),1),Zia=require("string_decoder"),B0i=_e(require("path"),1),SOe=_e(require("fs"),1),afr=require("path"),roa=require("events"),tfr=_e(require("assert"),1),Yde=require("buffer"),_ia=_e(require("zlib"),1),noa=_e(require("zlib"),1),_Oe=require("path"),coa=require("path"),mvt=_e(require("fs"),1),O6=_e(require("fs"),1),u0i=_e(require("path"),1),moa=require("path"),g0i=_e(require("path"),1),Q0i=_e(require("fs"),1),voa=_e(require("assert"),1),N0i=require("crypto"),Xp=_e(require("fs"),1),xv=_e(require("path"),1),j0i=_e(require("fs"),1),Avt=_e(require("fs"),1),J6e=_e(require("path"),1),rF=_e(require("fs"),1),_oa=_e(require("fs/promises"),1),hvt=_e(require("path"),1),M0i=require("path"),tF=_e(require("fs"),1),U0i=_e(require("path"),1),s2p=Object.defineProperty,a2p=(e,t)=>{for(var r in t)s2p(e,r,{get:t[r],enumerable:!0})},Iia=typeof process=="object"&&process?process:{stdout:null,stderr:null},u2p=e=>!!e&&typeof e=="object"&&(e instanceof TOe||e instanceof _0i.default||c2p(e)||l2p(e)),c2p=e=>!!e&&typeof e=="object"&&e instanceof ofr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==_0i.default.Writable.prototype.pipe,l2p=e=>!!e&&typeof e=="object"&&e instanceof ofr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",Coe=Symbol("EOF"),xoe=Symbol("maybeEmitEnd"),Vde=Symbol("emittedEnd"),Ppr=Symbol("emittingEnd"),WEt=Symbol("emittedError"),Tpr=Symbol("closed"),wia=Symbol("read"),Dpr=Symbol("flush"),Cia=Symbol("flushChunk"),_6=Symbol("encoding"),U6e=Symbol("decoder"),EC=Symbol("flowing"),$Et=Symbol("paused"),G6e=Symbol("resume"),vC=Symbol("buffer"),wP=Symbol("pipes"),IC=Symbol("bufferLength"),Tbi=Symbol("bufferPush"),Rpr=Symbol("bufferShift"),VS=Symbol("objectMode"),Z0=Symbol("destroyed"),Dbi=Symbol("error"),Rbi=Symbol("emitData"),xia=Symbol("emitEnd"),Fbi=Symbol("emitEnd2"),xH=Symbol("async"),kbi=Symbol("abort"),Fpr=Symbol("aborted"),HEt=Symbol("signal"),AOe=Symbol("dataListeners"),_Q=Symbol("discarded"),KEt=e=>Promise.resolve().then(e),p2p=e=>e(),f2p=e=>e==="end"||e==="finish"||e==="prefinish",d2p=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,m2p=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),eoa=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[G6e](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},h2p=class extends eoa{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)}},g2p=e=>!!e.objectMode,A2p=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",TOe=class extends ofr.EventEmitter{[EC]=!1;[$Et]=!1;[wP]=[];[vC]=[];[VS];[_6];[xH];[U6e];[Coe]=!1;[Vde]=!1;[Ppr]=!1;[Tpr]=!1;[WEt]=null;[IC]=0;[Z0]=!1;[HEt];[Fpr]=!1;[AOe]=0;[_Q]=!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");g2p(t)?(this[VS]=!0,this[_6]=null):A2p(t)?(this[_6]=t.encoding,this[VS]=!1):(this[VS]=!1,this[_6]=null),this[xH]=!!t.async,this[U6e]=this[_6]?new Zia.StringDecoder(this[_6]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[vC]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[wP]});let{signal:r}=t;r&&(this[HEt]=r,r.aborted?this[kbi]():r.addEventListener("abort",()=>this[kbi]()))}get bufferLength(){return this[IC]}get encoding(){return this[_6]}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[VS]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[xH]}set async(e){this[xH]=this[xH]||!!e}[kbi](){this[Fpr]=!0,this.emit("abort",this[HEt]?.reason),this.destroy(this[HEt]?.reason)}get aborted(){return this[Fpr]}set aborted(e){}write(e,t,r){if(this[Fpr])return!1;if(this[Coe])throw new Error("write after end");if(this[Z0])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[xH]?KEt:p2p;if(!this[VS]&&!Buffer.isBuffer(e)){if(m2p(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(d2p(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[VS]?(this[EC]&&this[IC]!==0&&this[Dpr](!0),this[EC]?this.emit("data",e):this[Tbi](e),this[IC]!==0&&this.emit("readable"),r&&n(r),this[EC]):e.length?(typeof e=="string"&&!(t===this[_6]&&!this[U6e]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[_6]&&(e=this[U6e].write(e)),this[EC]&&this[IC]!==0&&this[Dpr](!0),this[EC]?this.emit("data",e):this[Tbi](e),this[IC]!==0&&this.emit("readable"),r&&n(r),this[EC]):(this[IC]!==0&&this.emit("readable"),r&&n(r),this[EC])}read(e){if(this[Z0])return null;if(this[_Q]=!1,this[IC]===0||e===0||e&&e>this[IC])return this[xoe](),null;this[VS]&&(e=null),this[vC].length>1&&!this[VS]&&(this[vC]=[this[_6]?this[vC].join(""):Buffer.concat(this[vC],this[IC])]);let t=this[wia](e||null,this[vC][0]);return this[xoe](),t}[wia](e,t){if(this[VS])this[Rpr]();else{let r=t;e===r.length||e===null?this[Rpr]():typeof r=="string"?(this[vC][0]=r.slice(e),t=r.slice(0,e),this[IC]-=e):(this[vC][0]=r.subarray(e),t=r.subarray(0,e),this[IC]-=e)}return this.emit("data",t),!this[vC].length&&!this[Coe]&&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[Coe]=!0,this.writable=!1,(this[EC]||!this[$Et])&&this[xoe](),this}[G6e](){this[Z0]||(!this[AOe]&&!this[wP].length&&(this[_Q]=!0),this[$Et]=!1,this[EC]=!0,this.emit("resume"),this[vC].length?this[Dpr]():this[Coe]?this[xoe]():this.emit("drain"))}resume(){return this[G6e]()}pause(){this[EC]=!1,this[$Et]=!0,this[_Q]=!1}get destroyed(){return this[Z0]}get flowing(){return this[EC]}get paused(){return this[$Et]}[Tbi](e){this[VS]?this[IC]+=1:this[IC]+=e.length,this[vC].push(e)}[Rpr](){return this[VS]?this[IC]-=1:this[IC]-=this[vC][0].length,this[vC].shift()}[Dpr](e=!1){do;while(this[Cia](this[Rpr]())&&this[vC].length);!e&&!this[vC].length&&!this[Coe]&&this.emit("drain")}[Cia](e){return this.emit("data",e),this[EC]}pipe(e,t){if(this[Z0])return e;this[_Q]=!1;let r=this[Vde];return t=t||{},e===Iia.stdout||e===Iia.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[wP].push(t.proxyErrors?new h2p(this,e,t):new eoa(this,e,t)),this[xH]?KEt(()=>this[G6e]()):this[G6e]()),e}unpipe(e){let t=this[wP].find(r=>r.dest===e);t&&(this[wP].length===1?(this[EC]&&this[AOe]===0&&(this[EC]=!1),this[wP]=[]):this[wP].splice(this[wP].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[_Q]=!1,this[AOe]++,!this[wP].length&&!this[EC]&&this[G6e]();else if(e==="readable"&&this[IC]!==0)super.emit("readable");else if(f2p(e)&&this[Vde])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[WEt]){let n=t;this[xH]?KEt(()=>n.call(this,this[WEt])):n.call(this,this[WEt])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[AOe]=this.listeners("data").length,this[AOe]===0&&!this[_Q]&&!this[wP].length&&(this[EC]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[AOe]=0,!this[_Q]&&!this[wP].length&&(this[EC]=!1)),t}get emittedEnd(){return this[Vde]}[xoe](){!this[Ppr]&&!this[Vde]&&!this[Z0]&&this[vC].length===0&&this[Coe]&&(this[Ppr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Tpr]&&this.emit("close"),this[Ppr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==Z0&&this[Z0])return!1;if(e==="data")return!this[VS]&&!r?!1:this[xH]?(KEt(()=>this[Rbi](r)),!0):this[Rbi](r);if(e==="end")return this[xia]();if(e==="close"){if(this[Tpr]=!0,!this[Vde]&&!this[Z0])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[WEt]=r,super.emit(Dbi,r);let i=!this[HEt]||this.listeners("error").length?super.emit("error",r):!1;return this[xoe](),i}else if(e==="resume"){let i=super.emit("resume");return this[xoe](),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[xoe](),n}[Rbi](e){for(let r of this[wP])r.dest.write(e)===!1&&this.pause();let t=this[_Q]?!1:super.emit("data",e);return this[xoe](),t}[xia](){return this[Vde]?!1:(this[Vde]=!0,this.readable=!1,this[xH]?(KEt(()=>this[Fbi]()),!0):this[Fbi]())}[Fbi](){if(this[U6e]){let t=this[U6e].end();if(t){for(let r of this[wP])r.dest.write(t);this[_Q]||super.emit("data",t)}}for(let t of this[wP])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[VS]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[VS]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[VS])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[_6]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Z0,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[_Q]=!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[Coe])return t();let n,i,o=c=>{this.off("data",s),this.off("end",a),this.off(Z0,u),t(),i(c)},s=c=>{this.off("error",o),this.off("end",a),this.off(Z0,u),this.pause(),n({value:c,done:!!this[Coe]})},a=()=>{this.off("error",o),this.off("data",s),this.off(Z0,u),t(),n({done:!0,value:void 0})},u=()=>o(new Error("stream destroyed"));return new Promise((c,l)=>{i=l,n=c,this.once(Z0,u),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[_Q]=!1;let e=!1,t=()=>(this.pause(),this.off(Dbi,t),this.off(Z0,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(Dbi,t),this.once(Z0,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[Z0])return e?this.emit("error",e):this.emit(Z0),this;this[Z0]=!0,this[_Q]=!0,this[vC].length=0,this[IC]=0;let t=this;return typeof t.close=="function"&&!this[Tpr]&&t.close(),e?this.emit("error",e):this.emit(Z0),this}static get isStream(){return u2p}},y2p=CP.default.writev,Zde=Symbol("_autoClose"),T6=Symbol("_close"),JEt=Symbol("_ended"),gm=Symbol("_fd"),Qbi=Symbol("_finished"),Ooe=Symbol("_flags"),Nbi=Symbol("_flush"),i0i=Symbol("_handleChunk"),o0i=Symbol("_makeBuf"),svt=Symbol("_mode"),kpr=Symbol("_needDrain"),K6e=Symbol("_onerror"),Y6e=Symbol("_onopen"),jbi=Symbol("_onread"),W6e=Symbol("_onwrite"),eme=Symbol("_open"),P6=Symbol("_path"),$de=Symbol("_pos"),_H=Symbol("_queue"),$6e=Symbol("_read"),Mbi=Symbol("_readSize"),Boe=Symbol("_reading"),YEt=Symbol("_remain"),Lbi=Symbol("_size"),qpr=Symbol("_write"),yOe=Symbol("_writing"),Gpr=Symbol("_defaultFlag"),BOe=Symbol("_errored"),S0i=class extends TOe{[BOe]=!1;[gm];[P6];[Mbi];[Boe]=!1;[Lbi];[YEt];[Zde];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[BOe]=!1,this[gm]=typeof t.fd=="number"?t.fd:void 0,this[P6]=e,this[Mbi]=t.readSize||16*1024*1024,this[Boe]=!1,this[Lbi]=typeof t.size=="number"?t.size:1/0,this[YEt]=this[Lbi],this[Zde]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[gm]=="number"?this[$6e]():this[eme]()}get fd(){return this[gm]}get path(){return this[P6]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[eme](){CP.default.open(this[P6],"r",(e,t)=>this[Y6e](e,t))}[Y6e](e,t){e?this[K6e](e):(this[gm]=t,this.emit("open",t),this[$6e]())}[o0i](){return Buffer.allocUnsafe(Math.min(this[Mbi],this[YEt]))}[$6e](){if(!this[Boe]){this[Boe]=!0;let e=this[o0i]();if(e.length===0)return process.nextTick(()=>this[jbi](null,0,e));CP.default.read(this[gm],e,0,e.length,null,(t,r,n)=>this[jbi](t,r,n))}}[jbi](e,t,r){this[Boe]=!1,e?this[K6e](e):this[i0i](t,r)&&this[$6e]()}[T6](){if(this[Zde]&&typeof this[gm]=="number"){let e=this[gm];this[gm]=void 0,CP.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[K6e](e){this[Boe]=!0,this[T6](),this.emit("error",e)}[i0i](e,t){let r=!1;return this[YEt]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[YEt]<=0)&&(r=!1,this[T6](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[gm]=="number"&&this[$6e](),!1;case"error":return this[BOe]?!1:(this[BOe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},b2p=class extends S0i{[eme](){let e=!0;try{this[Y6e](null,CP.default.openSync(this[P6],"r")),e=!1}finally{e&&this[T6]()}}[$6e](){let e=!0;try{if(!this[Boe]){this[Boe]=!0;do{let t=this[o0i](),r=t.length===0?0:CP.default.readSync(this[gm],t,0,t.length,null);if(!this[i0i](r,t))break}while(!0);this[Boe]=!1}e=!1}finally{e&&this[T6]()}}[T6](){if(this[Zde]&&typeof this[gm]=="number"){let e=this[gm];this[gm]=void 0,CP.default.closeSync(e),this.emit("close")}}},sfr=class extends Xia.default{readable=!1;writable=!0;[BOe]=!1;[yOe]=!1;[JEt]=!1;[_H]=[];[kpr]=!1;[P6];[svt];[Zde];[gm];[Gpr];[Ooe];[Qbi]=!1;[$de];constructor(e,t){t=t||{},super(t),this[P6]=e,this[gm]=typeof t.fd=="number"?t.fd:void 0,this[svt]=t.mode===void 0?438:t.mode,this[$de]=typeof t.start=="number"?t.start:void 0,this[Zde]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[$de]!==void 0?"r+":"w";this[Gpr]=t.flags===void 0,this[Ooe]=t.flags===void 0?r:t.flags,this[gm]===void 0&&this[eme]()}emit(e,...t){if(e==="error"){if(this[BOe])return!1;this[BOe]=!0}return super.emit(e,...t)}get fd(){return this[gm]}get path(){return this[P6]}[K6e](e){this[T6](),this[yOe]=!0,this.emit("error",e)}[eme](){CP.default.open(this[P6],this[Ooe],this[svt],(e,t)=>this[Y6e](e,t))}[Y6e](e,t){this[Gpr]&&this[Ooe]==="r+"&&e&&e.code==="ENOENT"?(this[Ooe]="w",this[eme]()):e?this[K6e](e):(this[gm]=t,this.emit("open",t),this[yOe]||this[Nbi]())}end(e,t){return e&&this.write(e,t),this[JEt]=!0,!this[yOe]&&!this[_H].length&&typeof this[gm]=="number"&&this[W6e](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[JEt]?(this.emit("error",new Error("write() after end()")),!1):this[gm]===void 0||this[yOe]||this[_H].length?(this[_H].push(e),this[kpr]=!0,!1):(this[yOe]=!0,this[qpr](e),!0)}[qpr](e){CP.default.write(this[gm],e,0,e.length,this[$de],(t,r)=>this[W6e](t,r))}[W6e](e,t){e?this[K6e](e):(this[$de]!==void 0&&typeof t=="number"&&(this[$de]+=t),this[_H].length?this[Nbi]():(this[yOe]=!1,this[JEt]&&!this[Qbi]?(this[Qbi]=!0,this[T6](),this.emit("finish")):this[kpr]&&(this[kpr]=!1,this.emit("drain"))))}[Nbi](){if(this[_H].length===0)this[JEt]&&this[W6e](null,0);else if(this[_H].length===1)this[qpr](this[_H].pop());else{let e=this[_H];this[_H]=[],y2p(this[gm],e,this[$de],(t,r)=>this[W6e](t,r))}}[T6](){if(this[Zde]&&typeof this[gm]=="number"){let e=this[gm];this[gm]=void 0,CP.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},toa=class extends sfr{[eme](){let e;if(this[Gpr]&&this[Ooe]==="r+")try{e=CP.default.openSync(this[P6],this[Ooe],this[svt])}catch(t){if(t?.code==="ENOENT")return this[Ooe]="w",this[eme]();throw t}else e=CP.default.openSync(this[P6],this[Ooe],this[svt]);this[Y6e](null,e)}[T6](){if(this[Zde]&&typeof this[gm]=="number"){let e=this[gm];this[gm]=void 0,CP.default.closeSync(e),this.emit("close")}}[qpr](e){let t=!0;try{this[W6e](null,CP.default.writeSync(this[gm],e,0,e.length,this[$de])),t=!1}finally{if(t)try{this[T6]()}catch{}}}},E2p=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"]]),v2p=e=>!!e.sync&&!!e.file,I2p=e=>!e.sync&&!!e.file,w2p=e=>!!e.sync&&!e.file,C2p=e=>!e.sync&&!e.file,x2p=e=>!!e.file,_2p=e=>E2p.get(e)||e,O0i=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=_2p(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},gvt=(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):s=[];let u=O0i(o);if(i?.(u,s),v2p(u)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(u,s)}else if(I2p(u)){let c=t(u,s),l=a||void 0;return l?c.then(()=>l(),l):c}else if(w2p(u)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(u,s)}else if(C2p(u)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(u,s)}else throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:n,validate:i}),S2p=noa.default.constants||{ZLIB_VERNUM:4736},OH=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},S2p)),B2p=Yde.Buffer.concat,Sia=Object.getOwnPropertyDescriptor(Yde.Buffer,"concat"),O2p=e=>e,Ubi=Sia?.writable===!0||Sia?.set!==void 0?e=>{Yde.Buffer.concat=e?O2p:B2p}:e=>{},OOe=Symbol("_superWrite"),Qpr=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"}},zbi=Symbol("flushFlag"),P0i=class extends TOe{#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 _ia[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new _ia[t](e)}catch(r){throw new Qpr(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 Qpr(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,tfr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(Yde.Buffer.alloc(0),{[zbi]: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}[OOe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=Yde.Buffer.from(e,t)),this.#e)return;(0,tfr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},Ubi(!0);let s;try{let u=typeof e[zbi]=="number"?e[zbi]:this.#r;s=this.#o._processChunk(e,u),Ubi(!1)}catch(u){Ubi(!1),this.#s(new Qpr(u,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",u=>this.#s(new Qpr(u,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let u=s[0];a=this[OOe](Yde.Buffer.from(u));for(let c=1;c<s.length;c++)a=this[OOe](s[c])}else a=this[OOe](Yde.Buffer.from(s));return r&&r(),a}},ioa=class extends P0i{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||OH.Z_NO_FLUSH,e.finishFlush=e.finishFlush||OH.Z_FINISH,e.fullFlushFlag=OH.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(OH.Z_SYNC_FLUSH),(0,tfr.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)}}}},P2p=class extends ioa{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[OOe](e){return this.#e?(this.#e=!1,e[9]=255,super[OOe](e)):super[OOe](e)}},T2p=class extends ioa{constructor(e){super(e,"Unzip")}},ooa=class extends P0i{constructor(e,t){e=e||{},e.flush=e.flush||OH.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||OH.BROTLI_OPERATION_FINISH,e.fullFlushFlag=OH.BROTLI_OPERATION_FLUSH,super(e,t)}},D2p=class extends ooa{constructor(e){super(e,"BrotliCompress")}},R2p=class extends ooa{constructor(e){super(e,"BrotliDecompress")}},soa=class extends P0i{constructor(e,t){e=e||{},e.flush=e.flush||OH.ZSTD_e_continue,e.finishFlush=e.finishFlush||OH.ZSTD_e_end,e.fullFlushFlag=OH.ZSTD_e_flush,super(e,t)}},F2p=class extends soa{constructor(e){super(e,"ZstdCompress")}},k2p=class extends soa{constructor(e){super(e,"ZstdDecompress")}},Q2p=(e,t)=>{if(Number.isSafeInteger(e))e<0?j2p(e,t):N2p(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},N2p=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},j2p=(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]=aoa(i):i===0?t[n-1]=0:(r=!0,t[n-1]=uoa(i))}},M2p=e=>{let t=e[0],r=t===128?U2p(e.subarray(1,e.length)):t===255?L2p(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},L2p=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=aoa(o):o===0?s=o:(n=!0,s=uoa(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},U2p=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},aoa=e=>(255^e)&255,uoa=e=>(255^e)+1&255,z2p={};a2p(z2p,{code:()=>T0i,isCode:()=>Wpr,isName:()=>V2p,name:()=>ufr});var Wpr=e=>ufr.has(e),V2p=e=>T0i.has(e),ufr=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"]]),T0i=new Map(Array.from(ufr).map(e=>[e[1],e[0]])),POe=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(e,t=0,r,n){Buffer.isBuffer(e)?this.decode(e,t||0,r,n):e&&this.#t(e)}decode(e,t,r,n){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");this.path=r?.path??bOe(e,t,100),this.mode=r?.mode??n?.mode??Hde(e,t+100,8),this.uid=r?.uid??n?.uid??Hde(e,t+108,8),this.gid=r?.gid??n?.gid??Hde(e,t+116,8),this.size=r?.size??n?.size??Hde(e,t+124,12),this.mtime=r?.mtime??n?.mtime??Vbi(e,t+136,12),this.cksum=Hde(e,t+148,12),n&&this.#t(n,!0),r&&this.#t(r);let i=bOe(e,t+156,1);if(Wpr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=bOe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=r?.uname??n?.uname??bOe(e,t+265,32),this.gname=r?.gname??n?.gname??bOe(e,t+297,32),this.devmaj=r?.devmaj??n?.devmaj??Hde(e,t+329,8)??0,this.devmin=r?.devmin??n?.devmin??Hde(e,t+337,8)??0,e[t+475]!==0){let s=bOe(e,t+345,155);this.path=s+"/"+this.path}else{let s=bOe(e,t+345,130);s&&(this.path=s+"/"+this.path),this.atime=r?.atime??n?.atime??Vbi(e,t+476,12),this.ctime=r?.ctime??n?.ctime??Vbi(e,t+488,12)}let o=256;for(let s=t;s<t+148;s++)o+=e[s];for(let s=t+156;s<t+512;s++)o+=e[s];this.cksumValid=o===this.cksum,this.cksum===void 0&&o===256&&(this.nullBlock=!0)}#t(e,t=!1){Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t||r==="linkpath"&&t||r==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=q2p(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=EOe(e,t,100,i)||this.needPax,this.needPax=Kde(e,t+100,8,this.mode)||this.needPax,this.needPax=Kde(e,t+108,8,this.uid)||this.needPax,this.needPax=Kde(e,t+116,8,this.gid)||this.needPax,this.needPax=Kde(e,t+124,12,this.size)||this.needPax,this.needPax=qbi(e,t+136,12,this.mtime)||this.needPax,e[t+156]=this.#e.charCodeAt(0),this.needPax=EOe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=EOe(e,t+265,32,this.uname)||this.needPax,this.needPax=EOe(e,t+297,32,this.gname)||this.needPax,this.needPax=Kde(e,t+329,8,this.devmaj)||this.needPax,this.needPax=Kde(e,t+337,8,this.devmin)||this.needPax,this.needPax=EOe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=EOe(e,t+345,155,o)||this.needPax:(this.needPax=EOe(e,t+345,130,o)||this.needPax,this.needPax=qbi(e,t+476,12,this.atime)||this.needPax,this.needPax=qbi(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,Kde(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ufr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(T0i.get(e));if(Wpr(t)||t==="Unsupported")this.#e=t;else if(Wpr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},q2p=(e,t)=>{let r=e,n="",i,o=_Oe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=_Oe.posix.dirname(r),r=_Oe.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=_Oe.posix.join(_Oe.posix.basename(n),r),n=_Oe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},bOe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),Vbi=(e,t,r)=>G2p(Hde(e,t,r)),G2p=e=>e===void 0?void 0:new Date(e*1e3),Hde=(e,t,r)=>Number(e[t])&128?M2p(e.subarray(t,t+r)):$2p(e,t,r),W2p=e=>isNaN(e)?void 0:e,$2p=(e,t,r)=>W2p(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),H2p={12:8589934591,8:2097151},Kde=(e,t,r,n)=>n===void 0?!1:n>H2p[r]||n<0?(Q2p(n,e.subarray(t,t+r)),!0):(K2p(e,t,r,n),!1),K2p=(e,t,r,n)=>e.write(J2p(n,r),t,r,"ascii"),J2p=(e,t)=>Y2p(Math.floor(e).toString(8),t),Y2p=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",qbi=(e,t,r,n)=>n===void 0?!1:Kde(e,t,r,n.getTime()/1e3),X2p=new Array(156).join("\0"),EOe=(e,t,r,n)=>n===void 0?!1:(e.write(n+X2p,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),rfr=class loa{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 POe({path:("PaxHeader/"+(0,coa.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+`
1542
1542
  `,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 loa(Z2p(eQp(t),r),n)}},Z2p=(e,t)=>t?Object.assign({},t,e):e,eQp=e=>e.replace(/\n$/,"").split(`
1543
- `).reduce(tQp,Object.create(null)),tQp=(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},rQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Zl=rQp!=="win32"?e=>e:e=>e&&e.replace(/\\/g,"/"),poa=class extends TOe{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=Zl(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?Zl(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=Zl(e.path)),e.linkpath&&(e.linkpath=Zl(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},cfr=(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))},nQp=1024*1024,s0i=Buffer.from([31,139]),a0i=Buffer.from([40,181,47,253]),iQp=Math.max(s0i.length,a0i.length),F4=Symbol("state"),vOe=Symbol("writeEntry"),_oe=Symbol("readEntry"),Gbi=Symbol("nextEntry"),Bia=Symbol("processEntry"),SH=Symbol("extendedHeader"),XEt=Symbol("globalExtendedHeader"),qde=Symbol("meta"),Oia=Symbol("emitMeta"),Dg=Symbol("buffer"),Soe=Symbol("queue"),Gde=Symbol("ended"),Wbi=Symbol("emittedEnd"),IOe=Symbol("emit"),Cv=Symbol("unzip"),Npr=Symbol("consumeChunk"),jpr=Symbol("consumeChunkSub"),$bi=Symbol("consumeBody"),Pia=Symbol("consumeMeta"),Tia=Symbol("consumeHeader"),ZEt=Symbol("consuming"),Hbi=Symbol("bufferConcat"),Mpr=Symbol("maybeEnd"),z6e=Symbol("writing"),Wde=Symbol("aborted"),Lpr=Symbol("onDone"),wOe=Symbol("sawValidEntry"),Upr=Symbol("sawNullBlock"),zpr=Symbol("sawEOF"),Dia=Symbol("closeStream"),oQp=()=>!0,dvt=class extends roa.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Soe]=[];[Dg];[_oe];[vOe];[F4]="begin";[qde]="";[SH];[XEt];[Gde]=!1;[Cv];[Wde]=!1;[wOe];[Upr]=!1;[zpr]=!1;[z6e]=!1;[ZEt]=!1;[Wbi]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(Lpr,()=>{(this[F4]==="begin"||this[wOe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(Lpr,e.ondone):this.on(Lpr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||nQp,this.filter=typeof e.filter=="function"?e.filter:oQp;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[Dia]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){cfr(this,e,t,r)}[Tia](e,t){this[wOe]===void 0&&(this[wOe]=!1);let r;try{r=new POe(e,t,this[SH],this[XEt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[Upr]?(this[zpr]=!0,this[F4]==="begin"&&(this[F4]="header"),this[IOe]("eof")):(this[Upr]=!0,this[IOe]("nullBlock"));else if(this[Upr]=!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[vOe]=new poa(r,this[SH],this[XEt]);if(!this[wOe])if(i.remain){let o=()=>{i.invalid||(this[wOe]=!0)};i.on("end",o)}else this[wOe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[IOe]("ignoredEntry",i),this[F4]="ignore",i.resume()):i.size>0&&(this[qde]="",i.on("data",o=>this[qde]+=o),this[F4]="meta"):(this[SH]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[IOe]("ignoredEntry",i),this[F4]=i.remain?"ignore":"header",i.resume()):(i.remain?this[F4]="body":(this[F4]="header",i.end()),this[_oe]?this[Soe].push(i):(this[Soe].push(i),this[Gbi]())))}}}[Dia](){queueMicrotask(()=>this.emit("close"))}[Bia](e){let t=!0;if(!e)this[_oe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[_oe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[Gbi]()),t=!1);return t}[Gbi](){do;while(this[Bia](this[Soe].shift()));if(!this[Soe].length){let e=this[_oe];!e||e.flowing||e.size===e.remain?this[z6e]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[$bi](e,t){let r=this[vOe];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[F4]="header",this[vOe]=void 0,r.end()),i.length}[Pia](e,t){let r=this[vOe],n=this[$bi](e,t);return!this[vOe]&&r&&this[Oia](r),n}[IOe](e,t,r){!this[Soe].length&&!this[_oe]?this.emit(e,t,r):this[Soe].push([e,t,r])}[Oia](e){switch(this[IOe]("meta",this[qde]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[SH]=rfr.parse(this[qde],this[SH],!1);break;case"GlobalExtendedHeader":this[XEt]=rfr.parse(this[qde],this[XEt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[SH]??Object.create(null);this[SH]=t,t.path=this[qde].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[SH]||Object.create(null);this[SH]=t,t.linkpath=this[qde].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[Wde]=!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[Wde])return r?.(),!1;if((this[Cv]===void 0||this.brotli===void 0&&this[Cv]===!1)&&e){if(this[Dg]&&(e=Buffer.concat([this[Dg],e]),this[Dg]=void 0),e.length<iQp)return this[Dg]=e,r?.(),!0;for(let s=0;this[Cv]===void 0&&s<s0i.length;s++)e[s]!==s0i[s]&&(this[Cv]=!1);let i=!1;if(this[Cv]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<a0i.length;s++)if(e[s]!==a0i[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Cv]===!1&&o)if(e.length<512)if(this[Gde])this.brotli=!0;else return this[Dg]=e,r?.(),!0;else try{new POe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Cv]===void 0||this[Cv]===!1&&(this.brotli||i)){let s=this[Gde];this[Gde]=!1,this[Cv]=this[Cv]===void 0?new T2p({}):i?new k2p({}):new R2p({}),this[Cv].on("data",u=>this[Npr](u)),this[Cv].on("error",u=>this.abort(u)),this[Cv].on("end",()=>{this[Gde]=!0,this[Npr]()}),this[z6e]=!0;let a=!!this[Cv][s?"end":"write"](e);return this[z6e]=!1,r?.(),a}}this[z6e]=!0,this[Cv]?this[Cv].write(e):this[Npr](e),this[z6e]=!1;let n=this[Soe].length?!1:this[_oe]?this[_oe].flowing:!0;return!n&&!this[Soe].length&&this[_oe]?.once("drain",()=>this.emit("drain")),r?.(),n}[Hbi](e){e&&!this[Wde]&&(this[Dg]=this[Dg]?Buffer.concat([this[Dg],e]):e)}[Mpr](){if(this[Gde]&&!this[Wbi]&&!this[Wde]&&!this[ZEt]){this[Wbi]=!0;let e=this[vOe];if(e&&e.blockRemain){let t=this[Dg]?this[Dg].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Dg]&&e.write(this[Dg]),e.end()}this[IOe](Lpr)}}[Npr](e){if(this[ZEt]&&e)this[Hbi](e);else if(!e&&!this[Dg])this[Mpr]();else if(e){if(this[ZEt]=!0,this[Dg]){this[Hbi](e);let t=this[Dg];this[Dg]=void 0,this[jpr](t)}else this[jpr](e);for(;this[Dg]&&this[Dg]?.length>=512&&!this[Wde]&&!this[zpr];){let t=this[Dg];this[Dg]=void 0,this[jpr](t)}this[ZEt]=!1}(!this[Dg]||this[Gde])&&this[Mpr]()}[jpr](e){let t=0,r=e.length;for(;t+512<=r&&!this[Wde]&&!this[zpr];)switch(this[F4]){case"begin":case"header":this[Tia](e,t),t+=512;break;case"ignore":case"body":t+=this[$bi](e,t);break;case"meta":t+=this[Pia](e,t);break;default:throw new Error("invalid state: "+this[F4])}t<r&&(this[Dg]?this[Dg]=Buffer.concat([e.subarray(t),this[Dg]]):this[Dg]=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[Wde]||(this[Cv]?(e&&this[Cv].write(e),this[Cv].end()):(this[Gde]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[Mpr]())),this}},avt=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)},sQp=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},foa=(e,t)=>{let r=new Map(t.map(o=>[avt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,afr.parse)(o).root||".",u;if(o===a)u=!1;else{let c=r.get(o);c!==void 0?u=c:u=i((0,afr.dirname)(o),a)}return r.set(o,u),u};e.filter=n?(o,s)=>n(o,s)&&i(avt(o)):o=>i(avt(o))},aQp=e=>{let t=new dvt(e),r=e.file,n;try{n=SOe.default.openSync(r,"r");let i=SOe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=SOe.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 u=SOe.default.readSync(n,a,0,o,s);if(u===0)break;s+=u,t.write(a.subarray(0,u))}t.end()}}finally{if(typeof n=="number")try{SOe.default.closeSync(n)}catch{}}},uQp=(e,t)=>{let r=new dvt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),SOe.default.stat(i,(a,u)=>{if(a)s(a);else{let c=new S0i(i,{readSize:n,size:u.size});c.on("error",s),c.pipe(r)}})})},lfr=gvt(aQp,uQp,e=>new dvt(e),e=>new dvt(e),(e,t)=>{t?.length&&foa(e,t),e.noResume||sQp(e)}),doa=(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:cQp,parse:Ria}=moa.win32,D0i=e=>{let t="",r=Ria(e);for(;cQp(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=Ria(e)}return[t,e]},pfr=["|","<",">","?",":"],R0i=pfr.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),lQp=new Map(pfr.map((e,t)=>[e,R0i[t]])),pQp=new Map(R0i.map((e,t)=>[e,pfr[t]])),Fia=e=>pfr.reduce((t,r)=>t.split(r).join(lQp.get(r)),e),fQp=e=>R0i.reduce((t,r)=>t.split(r).join(pQp.get(r)),e),hoa=(e,t)=>t?(e=Zl(e).replace(/^\.(\/|$)/,""),avt(t)+"/"+e):Zl(e),dQp=16*1024*1024,kia=Symbol("process"),Qia=Symbol("file"),Nia=Symbol("directory"),c0i=Symbol("symlink"),jia=Symbol("hardlink"),evt=Symbol("header"),$pr=Symbol("read"),l0i=Symbol("lstat"),Hpr=Symbol("onlstat"),p0i=Symbol("onread"),f0i=Symbol("onreadlink"),d0i=Symbol("openfile"),m0i=Symbol("onopenfile"),Jde=Symbol("close"),nfr=Symbol("mode"),h0i=Symbol("awaitDrain"),Kbi=Symbol("ondrain"),BH=Symbol("prefix"),goa=class extends TOe{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=O0i(t);super(),this.path=Zl(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||dQp,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Zl(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Zl(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]=D0i(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=fQp(this.path.replace(/\\/g,"/")),e=e.replace(/\\/g,"/")),this.absolute=Zl(r.absolute||u0i.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[Hpr](i):this[l0i]()}warn(e,t,r={}){return cfr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[l0i](){O6.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Hpr](t)})}[Hpr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=gQp(e),this.emit("stat",e),this[kia]()}[kia](){switch(this.type){case"File":return this[Qia]();case"Directory":return this[Nia]();case"SymbolicLink":return this[c0i]();default:return this.end()}}[nfr](e){return doa(e,this.type==="Directory",this.portable)}[BH](e){return hoa(e,this.prefix)}[evt](){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 POe({path:this[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](this.linkpath):this.linkpath,mode:this[nfr](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 rfr({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[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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)}[Nia](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[evt](),this.end()}[c0i](){O6.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[f0i](t)})}[f0i](e){this.linkpath=Zl(e),this[evt](),this.end()}[jia](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Zl(u0i.default.relative(this.cwd,e)),this.stat.size=0,this[evt](),this.end()}[Qia](){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[jia](t);this.linkCache.set(e,this.absolute)}if(this[evt](),this.stat.size===0)return this.end();this[d0i]()}[d0i](){O6.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[m0i](t)})}[m0i](e){if(this.fd=e,this.#e)return this[Jde]();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[$pr]()}[$pr](){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");O6.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[Jde](()=>this.emit("error",o));this[p0i](s)})}[Jde](e=()=>{}){this.fd!==void 0&&O6.default.close(this.fd,e)}[p0i](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[Jde](()=>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[Jde](()=>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[Kbi]():this[h0i](()=>this[Kbi]())}[h0i](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)}[Kbi](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Jde](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[$pr]()}},mQp=class extends goa{sync=!0;[l0i](){this[Hpr](O6.default.lstatSync(this.absolute))}[c0i](){this[f0i](O6.default.readlinkSync(this.absolute))}[d0i](){this[m0i](O6.default.openSync(this.absolute,"r"))}[$pr](){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=O6.default.readSync(t,r,n,i,o);this[p0i](s),e=!1}finally{if(e)try{this[Jde](()=>{})}catch{}}}[h0i](e){e()}[Jde](e=()=>{}){this.fd!==void 0&&O6.default.closeSync(this.fd),e()}},hQp=class extends TOe{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 cfr(this,e,t,r)}constructor(e,t={}){let r=O0i(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=Zl(e.path),this.mode=e.mode!==void 0?this[nfr](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?Zl(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=D0i(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 POe({path:this[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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 rfr({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[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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)}[BH](e){return hoa(e,this.prefix)}[nfr](e){return doa(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}},gQp=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",AQp=class H6e{tail;head;length=0;static create(t=[]){return new H6e(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++)bQp(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)EQp(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 H6e;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 H6e;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 H6e;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 H6e;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=yQp(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};function yQp(e,t,r){let n=t,i=t?t.next:e.head,o=new F0i(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function bQp(e,t){e.tail=new F0i(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function EQp(e,t){e.head=new F0i(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var F0i=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}},Mia=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Lia=Buffer.alloc(1024),Kpr=Symbol("onStat"),tvt=Symbol("ended"),S6=Symbol("queue"),COe=Symbol("current"),xOe=Symbol("process"),rvt=Symbol("processing"),Jbi=Symbol("processJob"),B6=Symbol("jobs"),Ybi=Symbol("jobDone"),Jpr=Symbol("addFSEntry"),Uia=Symbol("addTarEntry"),A0i=Symbol("stat"),y0i=Symbol("readdir"),Ypr=Symbol("onreaddir"),Xpr=Symbol("pipe"),zia=Symbol("entry"),Xbi=Symbol("entryOpt"),Zpr=Symbol("writeEntryClass"),Aoa=Symbol("write"),Zbi=Symbol("ondrain"),ffr=class extends TOe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Zpr];onWriteEntry;[S6];[B6]=0;[rvt]=!1;[tvt]=!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=Zl(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[Zpr]=goa,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 P2p(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new D2p(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new F2p(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[Zbi]()),this.on("resume",()=>t.resume())}else this.on("drain",this[Zbi]);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[S6]=new AQp,this[B6]=0,this.jobs=Number(e.jobs)||4,this[rvt]=!1,this[tvt]=!1}[Aoa](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[tvt]=!0,this[xOe](),r&&r(),this}write(e){if(this[tvt])throw new Error("write after end");return e instanceof poa?this[Uia](e):this[Jpr](e),this.flowing}[Uia](e){let t=Zl(g0i.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new Mia(e.path,t);r.entry=new hQp(e,this[Xbi](r)),r.entry.on("end",()=>this[Ybi](r)),this[B6]+=1,this[S6].push(r)}this[xOe]()}[Jpr](e){let t=Zl(g0i.default.resolve(this.cwd,e));this[S6].push(new Mia(e,t)),this[xOe]()}[A0i](e){e.pending=!0,this[B6]+=1;let t=this.follow?"stat":"lstat";mvt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[B6]-=1,r?this.emit("error",r):this[Kpr](e,n)})}[Kpr](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)?t.isFile()&&t.nlink>1&&e===this[COe]&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync&&this[Jbi](e):e.ignore=!0,this[xOe]()}[y0i](e){e.pending=!0,this[B6]+=1,mvt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[B6]-=1,t)return this.emit("error",t);this[Ypr](e,r)})}[Ypr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[xOe]()}[xOe](){if(!this[rvt]){this[rvt]=!0;for(let e=this[S6].head;e&&this[B6]<this.jobs;e=e.next)if(this[Jbi](e.value),e.value.ignore){let t=e.next;this[S6].removeNode(e),e.next=t}this[rvt]=!1,this[tvt]&&!this[S6].length&&this[B6]===0&&(this.zip?this.zip.end(Lia):(super.write(Lia),super.end()))}}get[COe](){return this[S6]&&this[S6].head&&this[S6].head.value}[Ybi](e){this[S6].shift(),this[B6]-=1,this[xOe]()}[Jbi](e){if(!e.pending){if(e.entry){e===this[COe]&&!e.piped&&this[Xpr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[Kpr](e,t):this[A0i](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[Ypr](e,t):this[y0i](e),!e.readdir)return}if(e.entry=this[zia](e),!e.entry){e.ignore=!0;return}e===this[COe]&&!e.piped&&this[Xpr](e)}}}[Xbi](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}}[zia](e){this[B6]+=1;try{return new this[Zpr](e.path,this[Xbi](e)).on("end",()=>this[Ybi](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[Zbi](){this[COe]&&this[COe].entry&&this[COe].entry.resume()}[Xpr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[Jpr](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={}){cfr(this,e,t,r)}},k0i=class extends ffr{sync=!0;constructor(e){super(e),this[Zpr]=mQp}pause(){}resume(){}[A0i](e){let t=this.follow?"statSync":"lstatSync";this[Kpr](e,mvt.default[t](e.absolute))}[y0i](e){this[Ypr](e,mvt.default.readdirSync(e.absolute))}[Xpr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[Jpr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[Aoa](n)})}},vQp=(e,t)=>{let r=new k0i(e),n=new toa(e.file,{mode:e.mode||438});r.pipe(n),yoa(r,t)},IQp=(e,t)=>{let r=new ffr(e),n=new sfr(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 boa(r,t),i},yoa=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?lfr({file:B0i.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},boa=async(e,t)=>{for(let r=0;r<t.length;r++){let n=String(t[r]);n.charAt(0)==="@"?await lfr({file:B0i.default.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{e.add(i)}}):e.add(n)}e.end()},wQp=(e,t)=>{let r=new k0i(e);return yoa(r,t),r},CQp=(e,t)=>{let r=new ffr(e);return boa(r,t),r},Eoa=gvt(vQp,IQp,wQp,CQp,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),xQp=process.env.__FAKE_PLATFORM__||process.platform,_Qp=xQp==="win32",{O_CREAT:SQp,O_TRUNC:BQp,O_WRONLY:OQp}=j0i.default.constants,Ioa=Number(process.env.__FAKE_FS_O_FILENAME__)||j0i.default.constants.UV_FS_O_FILEMAP||0,PQp=_Qp&&!!Ioa,TQp=512*1024,DQp=Ioa|BQp|SQp|OQp,woa=PQp?e=>e<TQp?DQp:"w":()=>"w",b0i=(e,t,r)=>{try{return Avt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},ifr=(e,t,r,n)=>{Avt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},RQp=(e,t,r,n,i)=>{if(t.isDirectory())Coa(J6e.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=J6e.default.resolve(e,t.name);ifr(s,r,n,i)});else{let o=J6e.default.resolve(e,t.name);ifr(o,r,n,i)}},Coa=(e,t,r,n)=>{Avt.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 ifr(e,t,r,n);let s=o.length,a=null,u=c=>{if(!a){if(c)return n(a=c);if(--s===0)return ifr(e,t,r,n)}};for(let c of o)RQp(e,c,t,r,u)})},FQp=(e,t,r,n)=>{t.isDirectory()&&xoa(J6e.default.resolve(e,t.name),r,n),b0i(J6e.default.resolve(e,t.name),r,n)},xoa=(e,t,r)=>{let n;try{n=Avt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return b0i(e,t,r);throw o}for(let i of n)FQp(e,i,t,r);return b0i(e,t,r)},Soa=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"}},dfr=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"}},kQp=(e,t)=>{rF.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new Soa(e,r?.code||"ENOTDIR")),t(r)})},QQp=(e,t,r)=>{e=Zl(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,u=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),c=t.preserve,l=t.unlink,p=Zl(t.cwd),d=(m,h)=>{m?r(m):h&&u?Coa(h,s,a,g=>d(g)):o?rF.default.chmod(e,i,r):r()};if(e===p)return kQp(e,d);if(c)return _oa.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Zl(hvt.default.relative(p,e)).split("/");E0i(p,f,i,l,p,void 0,d)},E0i=(e,t,r,n,i,o,s)=>{if(!t.length)return s(null,o);let a=t.shift(),u=Zl(hvt.default.resolve(e+"/"+a));rF.default.mkdir(u,r,Boa(u,t,r,n,i,o,s))},Boa=(e,t,r,n,i,o,s)=>a=>{a?rF.default.lstat(e,(u,c)=>{if(u)u.path=u.path&&Zl(u.path),s(u);else if(c.isDirectory())E0i(e,t,r,n,i,o,s);else if(n)rF.default.unlink(e,l=>{if(l)return s(l);rF.default.mkdir(e,r,Boa(e,t,r,n,i,o,s))});else{if(c.isSymbolicLink())return s(new dfr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,E0i(e,t,r,n,i,o,s))},NQp=e=>{let t=!1,r;try{t=rF.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new Soa(e,r??"ENOTDIR")}},jQp=(e,t)=>{e=Zl(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),u=t.preserve,c=t.unlink,l=Zl(t.cwd),p=m=>{m&&a&&xoa(m,o,s),i&&rF.default.chmodSync(e,n)};if(e===l)return NQp(l),p();if(u)return p(rF.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Zl(hvt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),h=l;m&&(h+="/"+m);m=d.shift()){h=Zl(hvt.default.resolve(h));try{rF.default.mkdirSync(h,n),f=f||h}catch{let g=rF.default.lstatSync(h);if(g.isDirectory())continue;if(c){rF.default.unlinkSync(h),rF.default.mkdirSync(h,n),f=f||h;continue}else if(g.isSymbolicLink())return new dfr(h,h+"/"+d.join("/"))}}return p(f)},e0i=Object.create(null),Via=1e4,V6e=new Set,MQp=e=>{V6e.has(e)?V6e.delete(e):e0i[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),V6e.add(e);let t=e0i[e],r=V6e.size-Via;if(r>Via/10){for(let n of V6e)if(V6e.delete(n),delete e0i[n],--r<=0)break}return t},LQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,UQp=LQp==="win32",zQp=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t[t.length-1];return n!==void 0&&(r=(0,M0i.join)(n,r)),t.push(r||"/"),t},[]),VQp=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=UQp?["win32 parallelization disabled"]:e.map(n=>avt((0,M0i.join)(MQp(n))));let r=new Set(e.map(n=>zQp(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[i.length-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 u of a)i.add(u)}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 u=s[0];typeof u=="function"&&i.add(u)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},qQp=()=>process.umask(),qia=Symbol("onEntry"),v0i=Symbol("checkFs"),Gia=Symbol("checkFs2"),I0i=Symbol("isReusable"),k4=Symbol("makeFs"),w0i=Symbol("file"),C0i=Symbol("directory"),efr=Symbol("link"),Wia=Symbol("symlink"),$ia=Symbol("hardlink"),ovt=Symbol("ensureNoSymlink"),Hia=Symbol("unsupported"),Kia=Symbol("checkPath"),t0i=Symbol("stripAbsolutePath"),Xde=Symbol("mkdir"),wC=Symbol("onError"),Vpr=Symbol("pending"),Jia=Symbol("pend"),q6e=Symbol("unpend"),r0i=Symbol("ended"),n0i=Symbol("maybeClose"),x0i=Symbol("skip"),uvt=Symbol("doChown"),cvt=Symbol("uid"),lvt=Symbol("gid"),pvt=Symbol("checkedCwd"),GQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,fvt=GQp==="win32",WQp=1024,$Qp=(e,t)=>{if(!fvt)return Xp.default.unlink(e,t);let r=e+".DELETE."+(0,N0i.randomBytes)(16).toString("hex");Xp.default.rename(e,r,n=>{if(n)return t(n);Xp.default.unlink(r,t)})},HQp=e=>{if(!fvt)return Xp.default.unlinkSync(e);let t=e+".DELETE."+(0,N0i.randomBytes)(16).toString("hex");Xp.default.renameSync(e,t),Xp.default.unlinkSync(t)},Yia=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,L0i=class extends dvt{[r0i]=!1;[pvt]=!1;[Vpr]=0;reservations=new VQp;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[r0i]=!0,this[n0i]()},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;e.preserveOwner===void 0&&typeof e.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!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:WQp,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||fvt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Zl(xv.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:qQp():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[qia](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[n0i](){this[r0i]&&this[Vpr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[t0i](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=D0i(r),s=o.replace(/\\/g,"/").split("/");if(s.includes("..")||fvt&&/^[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=xv.default.posix.dirname(e.path),u=xv.default.posix.normalize(xv.default.posix.join(a,s.join("/")));if(u.startsWith("../")||u==="..")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}[Kia](e){let t=Zl(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Zl(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[t0i](e,"path")||!this[t0i](e,"linkpath"))return!1;if(xv.default.isAbsolute(e.path)?e.absolute=Zl(xv.default.resolve(e.path)):e.absolute=Zl(xv.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:Zl(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}=xv.default.win32.parse(String(e.absolute));e.absolute=n+Fia(String(e.absolute).slice(n.length));let{root:i}=xv.default.win32.parse(e.path);e.path=i+Fia(e.path.slice(i.length))}return!0}[qia](e){if(!this[Kia](e))return e.resume();switch(voa.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[v0i](e);default:return this[Hia](e)}}[wC](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[q6e](),t.resume())}[Xde](e,t,r){QQp(Zl(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)}[uvt](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}[cvt](e){return Yia(this.uid,e.uid,this.processUid)}[lvt](e){return Yia(this.gid,e.gid,this.processGid)}[w0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new sfr(String(e.absolute),{flags:woa(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Xp.default.close(n.fd,()=>{}),n.write=()=>!0,this[wC](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Xp.default.close(n.fd,()=>{}),this[wC](a,e),t();return}--i===0&&n.fd!==void 0&&Xp.default.close(n.fd,u=>{u?this[wC](u,e):this[q6e](),t()})};n.on("finish",()=>{let a=String(e.absolute),u=n.fd;if(typeof u=="number"&&e.mtime&&!this.noMtime){i++;let c=e.atime||new Date,l=e.mtime;Xp.default.futimes(u,c,l,p=>p?Xp.default.utimes(a,c,l,d=>o(d&&p)):o())}if(typeof u=="number"&&this[uvt](e)){i++;let c=this[cvt](e),l=this[lvt](e);typeof c=="number"&&typeof l=="number"&&Xp.default.fchown(u,c,l,p=>p?Xp.default.chown(a,c,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[wC](a,e),t()}),e.pipe(s)),s.pipe(n)}[C0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[Xde](String(e.absolute),r,n=>{if(n){this[wC](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[q6e](),e.resume())};e.mtime&&!this.noMtime&&(i++,Xp.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[uvt](e)&&(i++,Xp.default.chown(String(e.absolute),Number(this[cvt](e)),Number(this[lvt](e)),o)),o()})}[Hia](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Wia](e,t){let r=Zl(xv.default.relative(this.cwd,xv.default.resolve(xv.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[ovt](e,this.cwd,r,()=>this[efr](e,String(e.linkpath),"symlink",t),n=>{this[wC](n,e),t()})}[$ia](e,t){let r=Zl(xv.default.resolve(this.cwd,String(e.linkpath))),n=Zl(String(e.linkpath)).split("/");this[ovt](e,this.cwd,n,()=>this[efr](e,r,"link",t),i=>{this[wC](i,e),t()})}[ovt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=xv.default.resolve(t,o);Xp.default.lstat(s,(a,u)=>{if(a)return n();if(u?.isSymbolicLink())return i(new dfr(s,xv.default.resolve(s,r.join("/"))));this[ovt](e,s,r,n,i)})}[Jia](){this[Vpr]++}[q6e](){this[Vpr]--,this[n0i]()}[x0i](e){this[q6e](),e.resume()}[I0i](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!fvt}[v0i](e){this[Jia]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Gia](e,r))}[Gia](e,t){let r=s=>{t(s)},n=()=>{this[Xde](this.cwd,this.dmode,s=>{if(s){this[wC](s,e),r();return}this[pvt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Zl(xv.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[Xde](s,this.dmode,a=>{if(a){this[wC](a,e),r();return}o()})}o()},o=()=>{Xp.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[x0i](e),r();return}if(s||this[I0i](e,a))return this[k4](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let u=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,c=l=>this[k4](l??null,e,r);return u?Xp.default.chmod(String(e.absolute),Number(e.mode),c):c()}if(e.absolute!==this.cwd)return Xp.default.rmdir(String(e.absolute),u=>this[k4](u??null,e,r))}if(e.absolute===this.cwd)return this[k4](null,e,r);$Qp(String(e.absolute),u=>this[k4](u??null,e,r))})};this[pvt]?i():n()}[k4](e,t,r){if(e){this[wC](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[w0i](t,r);case"Link":return this[$ia](t,r);case"SymbolicLink":return this[Wia](t,r);case"Directory":case"GNUDumpDir":return this[C0i](t,r)}}[efr](e,t,r,n){Xp.default[r](t,String(e.absolute),i=>{i?this[wC](i,e):(this[q6e](),e.resume()),n()})}},nvt=e=>{try{return[null,e()]}catch(t){return[t,null]}},Ooa=class extends L0i{sync=!0;[k4](e,t){return super[k4](e,t,()=>{})}[v0i](e){if(!this[pvt]){let i=this[Xde](this.cwd,this.dmode);if(i)return this[wC](i,e);this[pvt]=!0}if(e.absolute!==this.cwd){let i=Zl(xv.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[Xde](i,this.dmode);if(o)return this[wC](o,e)}}let[t,r]=nvt(()=>Xp.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[x0i](e);if(t||this[I0i](e,r))return this[k4](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?nvt(()=>{Xp.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[k4](s,e)}let[i]=nvt(()=>Xp.default.rmdirSync(String(e.absolute)));this[k4](i,e)}let[n]=e.absolute===this.cwd?[]:nvt(()=>HQp(String(e.absolute)));this[k4](n,e)}[w0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Xp.default.closeSync(i)}catch(u){a=u}(s||a)&&this[wC](s||a,e),t()},i;try{i=Xp.default.openSync(String(e.absolute),woa(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[wC](s,e)),e.pipe(o)),o.on("data",s=>{try{Xp.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,u=e.mtime;try{Xp.default.futimesSync(i,a,u)}catch(c){try{Xp.default.utimesSync(String(e.absolute),a,u)}catch{s=c}}}if(this[uvt](e)){let a=this[cvt](e),u=this[lvt](e);try{Xp.default.fchownSync(i,Number(a),Number(u))}catch(c){try{Xp.default.chownSync(String(e.absolute),Number(a),Number(u))}catch{s=s||c}}}n(s)})}[C0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[Xde](String(e.absolute),r);if(n){this[wC](n,e),t();return}if(e.mtime&&!this.noMtime)try{Xp.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[uvt](e))try{Xp.default.chownSync(String(e.absolute),Number(this[cvt](e)),Number(this[lvt](e)))}catch{}t(),e.resume()}[Xde](e,t){try{return jQp(Zl(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}}[ovt](e,t,r,n,i){if(this.preservePaths||!r.length)return n();let o=t;for(let s of r){o=xv.default.resolve(o,s);let[a,u]=nvt(()=>Xp.default.lstatSync(o));if(a)return n();if(u.isSymbolicLink())return i(new dfr(o,xv.default.resolve(t,r.join("/"))))}n()}[efr](e,t,r,n){let i=`${r}Sync`;try{Xp.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[wC](o,e)}}},KQp=e=>{let t=new Ooa(e),r=e.file,n=Q0i.default.statSync(r),i=e.maxReadSize||16*1024*1024;new b2p(r,{readSize:i,size:n.size}).pipe(t)},JQp=(e,t)=>{let r=new L0i(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),Q0i.default.stat(i,(a,u)=>{if(a)s(a);else{let c=new S0i(i,{readSize:n,size:u.size});c.on("error",s),c.pipe(r)}})})},Poa=gvt(KQp,JQp,e=>new Ooa(e),e=>new L0i(e),(e,t)=>{t?.length&&foa(e,t)}),YQp=(e,t)=>{let r=new k0i(e),n=!0,i,o;try{try{i=tF.default.openSync(e.file,"r+")}catch(u){if(u?.code==="ENOENT")i=tF.default.openSync(e.file,"w+");else throw u}let s=tF.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=tF.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let u=new POe(a);if(!u.cksumValid)break;let c=512*Math.ceil((u.size||0)/512);if(o+c+512>s.size)break;o+=c,e.mtimeCache&&u.mtime&&e.mtimeCache.set(String(u.path),u.mtime)}n=!1,XQp(e,r,o,i,t)}finally{if(n)try{tF.default.closeSync(i)}catch{}}},XQp=(e,t,r,n,i)=>{let o=new toa(e.file,{fd:n,start:r});t.pipe(o),eNp(t,i)},ZQp=(e,t)=>{t=Array.from(t);let r=new ffr(e),n=(i,o,s)=>{let a=(d,f)=>{d?tF.default.close(i,m=>s(d)):s(null,f)},u=0;if(o===0)return a(null,0);let c=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||typeof f>"u")return a(d);if(c+=f,c<512&&f)return tF.default.read(i,l,c,l.length-c,u+c,p);if(u===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,u);let m=new POe(l);if(!m.cksumValid)return a(null,u);let h=512*Math.ceil((m.size??0)/512);if(u+h+512>o||(u+=h+512,u>=o))return a(null,u);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),c=0,tF.default.read(i,l,0,512,u,p)};tF.default.read(i,l,0,512,u,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(u,c)=>{if(u&&u.code==="ENOENT"&&s==="r+")return s="w+",tF.default.open(e.file,s,a);if(u||!c)return o(u);tF.default.fstat(c,(l,p)=>{if(l)return tF.default.close(c,()=>o(l));n(c,p.size,(d,f)=>{if(d)return o(d);let m=new sfr(e.file,{fd:c,start:f});r.pipe(m),m.on("error",o),m.on("close",i),tNp(r,t)})})};tF.default.open(e.file,s,a)})},eNp=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?lfr({file:U0i.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},tNp=async(e,t)=>{for(let r=0;r<t.length;r++){let n=String(t[r]);n.charAt(0)==="@"?await lfr({file:U0i.default.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>e.add(i)}):e.add(n)}e.end()},ivt=gvt(YQp,ZQp,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!x2p(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")}),Tiy=gvt(ivt.syncFile,ivt.asyncFile,ivt.syncNoFile,ivt.asyncNoFile,(e,t=[])=>{ivt.validate?.(e,t),rNp(e)}),rNp=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 Qoa=_e(Aw(),1);var nNp=Eoe();async function Noa({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:n,cliVersion:i,settings:o,loadAPIWorkspace:s}){let a,u={type:Uc.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},c=t.dependencies[e];return c==null?u={type:Uc.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${lNp(c)}`},async l=>{switch(c.type){case"version":a=await uNp({context:l,dependency:c,cliVersion:i,settings:o,loadAPIWorkspace:s});return;case"local":a=await aNp({context:l,dependency:c,cliVersion:i,settings:o,loadAPIWorkspace:s});return;default:xe(c)}}),a!=null?{didSucceed:!0,definition:a}:{didSucceed:!1,failure:u}}var joa="dependencies";var iNp="metadata.json",oNp=".fern";function sNp(e){return We(Ut.of((0,Roa.homedir)()),Se.of(oNp),Se.of(joa),Se.of(e.organization),Se.of(e.apiName),Se.of(e.version))}async function aNp({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){if(i==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let o=await i({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!o.didSucceed){t.failWithoutThrowing("Failed to load api definition",o.failures);return}t.logger.info("Modifying source filepath ...");let s=await o.workspace.getDefinition({context:t,relativePathToDependency:Se.of(e.path)},n);return t.logger.info("Loaded..."),s}async function uNp({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){let o=sNp(e),s=We(o,Se.of(joa)),a=We(o,Se.of(iNp)),u;if(!await Xt(s)||!await Xt(a)){t.logger.info("Downloading manifest...");let p=await nNp.definitionRegistry.get(z0i.FernFiddle.OrganizationId(e.organization),z0i.FernFiddle.ApiId(e.apiName),e.version);if(!p.ok){p.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:h=>{t.failWithoutThrowing("Failed to download API manifest",h)}});return}let d=p.body.yamlSchemaVersion!=null?parseInt(p.body.yamlSchemaVersion):void 0,f=cOe(r),m=cOe(p.body.cliVersion);if(d!=null){if(d>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${p.body.cliVersion}`);return}else if(d<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(f.major!==m.major||f.minor!==m.minor){t.failWithoutThrowing(`CLI version is ${p.body.cliVersion}. Expected ${f.major}.${f.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+p.body.definitionS3DownloadUrl),await(0,X6e.mkdir)(s,{recursive:!0});try{await cNp({s3PreSignedReadUrl:p.body.definitionS3DownloadUrl,absolutePathToLocalOutput:s})}catch(h){t.failWithoutThrowing("Failed to download API",h);return}u=p.body,await(0,X6e.writeFile)(a,JSON.stringify(u))}else u=JSON.parse((await(0,X6e.readFile)(a)).toString());if(t.logger.info("Parsing..."),i==null){t.failWithoutThrowing("Failed to load API");return}let c=await i({absolutePathToWorkspace:s,context:t,cliVersion:u.cliVersion,workspaceName:void 0});if(!c.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",c.failures);return}if(c.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await c.workspace.getDefinition({context:t},n)}async function cNp({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await Xb.get(e,{responseType:"stream"}),n=await Qoa.default.dir(),i=Foa.default.join(n.path,"api.tgz");await(0,koa.pipeline)(r.data,(0,Doa.createWriteStream)(i)),await Poa({file:i,cwd:t})}function lNp(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:xe(e)}}async function Moa({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:n,settings:i,loadAPIWorkspace:o}){let s={},a={},u={};return await Promise.all(Wy(t.packageMarkers).map(async([c,l])=>{if(l.contents.export==null)s[c]=l;else{let{export:p,...d}=l.contents;if(Wd(d)>0)u[c]={type:Uc.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:c};else{let f=vn(c);if(RO(t.namedDefinitionFiles).some(h=>h!==c&&h.startsWith(f)))u[c]={type:Uc.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:f};else{let h=await Noa({dependencyName:typeof l.contents.export=="string"?l.contents.export:l.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:n,settings:i,loadAPIWorkspace:o});h.didSucceed?a[vn(c)]={definition:h.definition,url:typeof l.contents.export=="object"?l.contents.export.url:void 0}:u[c]=h.failure}}}})),Wd(u)>0?{didSucceed:!1,failures:u}:{didSucceed:!0,packageMarkers:s,importedDefinitions:a}}Qt();Vt();var Loa=_e(require("path"),1);var V0i={};Y(V0i,{additionalProperties:()=>mNp,default:()=>gNp,definitions:()=>hNp,properties:()=>fNp,required:()=>dNp,type:()=>pNp});var pNp="object",fNp={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},dNp=["name"],mNp=!1,hNp={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}},"url-templates":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"default-urls":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}}},{type:"null"}]}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},gNp={type:pNp,properties:fNp,required:dNp,additionalProperties:mNp,definitions:hNp};var q0i={};Y(q0i,{additionalProperties:()=>bNp,default:()=>vNp,definitions:()=>ENp,properties:()=>yNp,type:()=>ANp});var ANp="object",yNp={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},bNp=!1,ENp={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},vNp={type:ANp,properties:yNp,additionalProperties:bNp,definitions:ENp};var G0i={};Y(G0i,{additionalProperties:()=>CNp,default:()=>_Np,definitions:()=>xNp,properties:()=>wNp,type:()=>INp});var INp="object",wNp={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},CNp=!1,xNp={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},_Np={type:INp,properties:wNp,additionalProperties:CNp,definitions:xNp};var W0i=new Map,$0i=new Map,H0i=new Map;function Uoa({files:e,absolutePathToDefinition:t,skipValidation:r}){let n,i={},o={},s={};for(let[a,u]of Wy(e)){let c=u.contents,l=p=>{s[a]={type:Uc.JSONSCHEMA_VALIDATION,error:p}};if(a===Lb){let p=W0i.get(u.rawContents);if(p!=null&&(p.validated||r))n={defaultUrl:p.value["default-url"],contents:p.value,rawContents:u.rawContents};else if(r){let d=$d.serialization.RootApiFileSchema.parseOrThrow(c);W0i.set(u.rawContents,{value:d,validated:!1}),n={defaultUrl:d["default-url"],contents:d,rawContents:u.rawContents}}else{let d=x5(c,V0i);if(d.success){let f=$d.serialization.RootApiFileSchema.parseOrThrow(c);W0i.set(u.rawContents,{value:f,validated:!0}),n={defaultUrl:f["default-url"],contents:f,rawContents:u.rawContents}}else l(d)}}else if(Loa.default.basename(a)===Bp){let p=H0i.get(u.rawContents);if(p!=null&&(p.validated||r))o[a]={defaultUrl:typeof p.value.export=="object"?p.value.export.url:void 0,contents:p.value,rawContents:u.rawContents};else if(r){let d=$d.serialization.PackageMarkerFileSchema.parseOrThrow(c);H0i.set(u.rawContents,{value:d,validated:!1}),o[a]={defaultUrl:typeof d.export=="object"?d.export.url:void 0,contents:d,rawContents:u.rawContents}}else{let d=x5(c,G0i);if(d.success){let f=$d.serialization.PackageMarkerFileSchema.parseOrThrow(c);H0i.set(u.rawContents,{value:f,validated:!0}),o[a]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:u.rawContents}}else l(d)}}else{let p=$0i.get(u.rawContents);if(p!=null&&(p.validated||r))i[a]={defaultUrl:void 0,contents:p.value,rawContents:u.rawContents,absoluteFilePath:We(t,a)};else if(r){let d=$d.serialization.DefinitionFileSchema.parseOrThrow(c);$0i.set(u.rawContents,{value:d,validated:!1}),i[a]={defaultUrl:void 0,contents:d,rawContents:u.rawContents,absoluteFilePath:We(t,a)}}else{let d=x5(c,q0i);if(d.success){let f=$d.serialization.DefinitionFileSchema.parseOrThrow(c);$0i.set(u.rawContents,{value:f,validated:!0}),i[a]={defaultUrl:void 0,contents:f,rawContents:u.rawContents,absoluteFilePath:We(t,a)}}else l(d)}}}return n==null?{didSucceed:!1,failures:{[Se.of(Lb)]:{type:Uc.FILE_MISSING},...s}}:Object.keys(s).length>0?{didSucceed:!1,failures:s}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:n,packageMarkers:o}}var qS=class extends U5{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...n}){super(n),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){let n=t||this.context;return(await this.toFernWorkspace({context:n},r)).definition}async toFernWorkspace({context:t,skipValidation:r},n,i,o){let s=(0,zoa.default)(n??{}),a=this.fernWorkspaces[s];if(a==null){let u=t||this.context,c=We(this.absoluteFilePath,Se.of(Hh)),l=await ati({absolutePathToWorkspace:this.absoluteFilePath,context:u}),p=await ora(c,"{yml,yaml}"),d=await sra(p);if(!d.didSucceed)return Glr(d.failures,u.logger),u.failAndThrow();let f=Uoa({files:d.files,absolutePathToDefinition:c,skipValidation:r});if(!f.didSucceed)return Glr(f.failures,u.logger),u.failAndThrow();let m=await Moa({dependenciesConfiguration:l,structuralValidationResult:f,context:u,cliVersion:this.cliVersion,settings:n,loadAPIWorkspace:this.loadAPIWorkspace});if(!m.didSucceed)return Glr(m.failures,u.logger),u.failAndThrow();let h={absoluteFilePath:c,rootApiFile:f.rootApiFile,namedDefinitionFiles:f.namedDefinitionFiles,packageMarkers:m.packageMarkers,importedDefinitions:m.importedDefinitions};n?.auth!=null&&(h={...h,rootApiFile:{...h.rootApiFile,contents:{...h.rootApiFile.contents,auth:n?.auth}}}),a=new LD({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:h,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[s]=a}return a}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};Vt();var cla=require("fs/promises");var Yca=_e(Jca(),1);async function F6(e){return(await(0,Yca.convertObj)(e,{})).openapi}var nla=require("fs/promises");var ila=require("path");Qt();var Xca=require("fs/promises");async function yVe({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,Xca.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=wr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return Apt({data:t,overrides:i,allowNullKeys:n})}var Zca=require("fs/promises");var vdr=require("path");function ela(e){return e.startsWith("http://")||e.startsWith("https://")}async function j3p(e,t){let r=t.get(e);if(r!==void 0)return r;let n=await(0,Zca.readFile)(e,"utf-8"),i=wr.load(n);return t.set(e,i),i}function tla(e,t){let r=new Map;if(e==null||typeof e!="object"||Array.isArray(e))return r;let n=e;function i(s,a){if(!(s==null||typeof s!="object"||Array.isArray(s)))for(let[u,c]of Object.entries(s)){if(!M3p(c))continue;let l=c.$ref,{jsonPointer:p,absolutePath:d}=rla(l,t);r.set(`${d}#${p}`,`${a}/${u}`)}}i(n.channels,"#/channels"),i(n.operations,"#/operations");let o=n.components;if(o!=null&&typeof o=="object"&&!Array.isArray(o)){let s=o;i(s.schemas,"#/components/schemas"),i(s.messages,"#/components/messages"),i(s.parameters,"#/components/parameters")}return r}function rla(e,t){let r=e.indexOf("#"),n=r>=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"",o=(0,vdr.resolve)(t,n);return{filePath:n,jsonPointer:i,absolutePath:o}}function M3p(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e.$ref;return typeof t=="string"&&t.length>0&&!t.startsWith("#")&&!ela(t)}function L3p(e,t,r,n){if(e===r)return"#"+t;let i=`${e}#${t}`,o=n.get(i);if(o!==void 0)return o;for(let[s,a]of n){let u=s.indexOf("#"),c=s.slice(0,u),l=s.slice(u+1);if(c===e&&t.startsWith(l+"/")){let p=t.slice(l.length);return a+p}}return null}async function pIt(e,t,r,n,i=!1,o=new Set,s=new Map){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return Promise.all(e.map(l=>pIt(l,t,r,n,i,o,s)));let a=e,u=a.$ref;if(typeof u=="string"&&!u.startsWith("#")&&!ela(u)){let{jsonPointer:l,absolutePath:p}=rla(u,t),d={};for(let[v,b]of Object.entries(a))v!=="$ref"&&(d[v]=b);let f=Object.keys(d).length>0;if(i){let v=L3p(p,l,r,n);if(v!==null)return{$ref:v,...d}}let m=`${p}#${l}`;if(o.has(m))throw new Error(`Circular $ref detected: "${u}" (resolved to "${m}")`);let h=new Set(o);h.add(m);let g=await j3p(p,s);if(l!==""){let v=l.split("/").filter(I=>I!==""),b=g;for(let I of v){let w=I.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof b!="object"||b==null)throw new Error(`Cannot navigate JSON Pointer "${l}" in "${p}": expected an object but found ${typeof b} at key "${w}"`);let x=b[w];if(x===void 0)throw new Error(`Cannot navigate JSON Pointer "${l}" in "${p}": key "${w}" not found`);b=x}g=b}let A=(0,vdr.dirname)(p),E=await pIt(g,A,r,n,!0,h,s);return f&&E!=null&&typeof E=="object"&&!Array.isArray(E)?{...E,...d}:E}let c={};for(let[l,p]of Object.entries(a))c[l]=await pIt(p,t,r,n,i,o,s);return c}async function Yvi({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,nla.readFile)(t)).toString(),i=await wr.load(n),o=(0,ila.dirname)(t),s=tla(i,o),a=await pIt(i,o,t,s),u=[];r!=null&&(Array.isArray(r)?u=r:u=[r]);let c=a;for(let l of u)c=await yVe({absoluteFilePathToOverrides:l,context:e,data:c});return c}Vt();var ula=require("fs/promises");Qt();var wdr=require("fs/promises");var Idr=_e(require("path"),1),ola=_e(Aw(),1),Xvi;async function U3p(){return Xvi===void 0&&(Xvi=(await ola.default.dir({prefix:"fern-overlay-"})).path),Xvi}async function sla({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:n}){let i=await z3p(e,n);if(!V3p(i,n))return r;n.logger.debug(`Applying overlay "${i.info.title}" v${i.info.version}`);let o=wLn({data:r,overlay:i}),s=await U3p(),a=Idr.default.basename(t),u=`${Idr.default.parse(a).name}.overlaid.json`,c=Idr.default.join(s,u);return await(0,wdr.writeFile)(c,JSON.stringify(o,null,2),"utf8"),n.logger.info(`Wrote overlaid OpenAPI spec to: ${c}`),o}async function z3p(e,t){let r;try{r=await(0,wdr.readFile)(e,"utf8")}catch(n){return t.failAndThrow(`Failed to read overlay file at ${e}: ${n}`)}try{try{return JSON.parse(r)}catch{return wr.load(r,{json:!0})}}catch(n){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${n}`)}}function V3p(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let n=e.actions[r];if(!n?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(n.update===void 0&&!n.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var mIt=_e(zer(),1);Vt();var ala=_e(zer(),1),fIt=_e(require("path"),1),dIt=class extends ala.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let n=super.resolveExternalRef(t,r);if(n.startsWith("http://")||n.startsWith("https://")||l9(Ut.of(n)))return n;if(this.absolutePathToOpenAPIOverlays!=null){let i=fIt.default.resolve(fIt.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(l9(Ut.of(i)))return i}return this.absolutePathToOpenAPIOverrides!=null?fIt.default.resolve(fIt.default.dirname(this.absolutePathToOpenAPIOverrides),r):n}};async function Cdr({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:n}){return(n!=null?await(0,mIt.bundle)({...Ver,doc:{source:new mIt.Source(e,"<openapi>"),parsed:n},externalRefResolver:new dIt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,mIt.bundle)({...Ver,ref:e,externalRefResolver:new dIt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}function q3p(e,t){if(t.includes(e))return e;for(let r of t){let n=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${n}$`).test(e))return r}}var G3p=["examples","example",bn.EXAMPLES,c_.REDOCLY_CODE_SAMPLES_CAMEL,c_.REDOCLY_CODE_SAMPLES_KEBAB];async function k6({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:n,loadAiExamples:i=!1}){let o=await Cdr({absolutePathToOpenAPI:t}),s=[];r!=null?Array.isArray(r)?s=r:s=[r]:typeof o=="object"&&o[bn.OPENAPI_OVERIDES_FILEPATH]!=null&&(s=[We(vn(t),Se.of(o[bn.OPENAPI_OVERIDES_FILEPATH]))]);let a=o;for(let c of s)a=await yVe({absoluteFilePathToOverrides:c,context:e,data:a,allowNullKeys:G3p}),a=await Cdr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:c,parsed:a});if(n!=null&&(a=await sla({absoluteFilePathToOverlay:n,absoluteFilePathToOpenAPI:t,context:e,data:a})),i){let c=We(vn(t),Se.of("ai_examples_override.yml"));try{let l=await(0,ula.readFile)(c,"utf-8"),p=wr.load(l);if(p?.paths&&a.paths){for(let[d,f]of Object.entries(p.paths))if(f&&typeof f=="object")for(let[m,h]of Object.entries(f)){let g=m.toLowerCase(),A=a.paths[d];if(!A&&a.paths){let E=q3p(d,Object.keys(a.paths));E&&(A=a.paths[E],e.logger.debug(`Matched override path "${d}" to OpenAPI path "${E}" using pattern matching`))}if(A&&typeof A=="object"){let v=A[g];if(v&&typeof v=="object"){let b=v;!b["x-fern-examples"]&&h["x-fern-examples"]&&(b["x-fern-examples"]=h["x-fern-examples"],e.logger.debug(`Added AI examples for ${m.toUpperCase()} ${d} from override file`))}}}}e.logger.debug(`Processed AI examples from ${c}`)}catch{}}return a!==o&&s.length===0||n!=null?await Cdr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverlays:n,parsed:a}):a}var Q6=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:n=!1}){return(await Promise.all(r.map(o=>this.loadDocument({context:t,spec:o,loadAiExamples:n})))).filter(o=>o!=null)}async loadDocument({context:t,spec:r,loadAiExamples:n}){try{let i=(await(0,cla.readFile)(r.absoluteFilepath)).toString(),o=ha(this.absoluteFilePath,r.source.file);r.source.relativePathToDependency!=null&&(o=We(r.source.relativePathToDependency,o));let s=r.source.type==="protobuf"?mS.protobuf({file:o}):mS.openapi({file:o});if(i.includes("openapi")||i.includes("swagger"))try{let a=await k6({absolutePathToOpenAPI:r.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:r.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:r.absoluteFilepathToOverlays,loadAiExamples:n});if(nti(a))return{type:"openapi",value:a,source:s,namespace:r.namespace,settings:iM({options:r.settings})};if(p8(a))return(!a.schemes||a.schemes.length===0)&&(a.schemes=["https"]),{type:"openapi",value:await F6(a),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.debug(`Failed to parse OpenAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("asyncapi"))try{return{type:"asyncapi",value:await Yvi({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.error(`Failed to parse AsyncAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("openrpc"))try{return{type:"asyncapi",value:await Yvi({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.error(`Failed to parse OpenRPC document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}t.logger.warn(`${r.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`);return}catch(i){t.logger.error(`Failed to read or process file ${r.absoluteFilepath}: ${i}. Skipping...`);return}}};var io=class e{breadcrumbs=[];context;static STRING=qt.TypeReference.primitive({v1:"STRING",v2:qt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=qt.TypeReference.container(qt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};Ci();Vt();var pla=require("fs/promises");var Zvi=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:u}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:u}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:u})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,u=>{a++,!((!u.children||u.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(u,u.path):(s.children.push({...u,path:u.path.slice(o.length+1)}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,u=n.length;this.iterFragments(o,c=>{a.has(c.position)||(u--,a.add(c.position),this._path.length===1?this.resolveNode(c,`${o}.${u}`):(s.children.push({...c,path:u.toString()}),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 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}}},lla=Zvi;var Sv;(function(e){e.WARNING="warning",e.ERROR="error"})(Sv||(Sv={}));var M4=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new eIi({logger:t,relativePathToFile:Se.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||Sv.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===Sv.ERROR?t++:(n.level===Sv.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??Sv.WARNING;if(!(n===Sv.WARNING&&!t))switch(n){case Sv.ERROR:if(this.logger.log(zn.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(zn.Debug,` - at location (${o})`)}break;case Sv.WARNING:if(this.logger.log(zn.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(zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(zn.Warn,` - resolution: ${r.resolution}`);break}}}},eIi=class{logger;relativePathToFile;map=new lla;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,pla.readFile)(this.relativePathToFile,"utf-8");wr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(zn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var kA=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=PI({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((i,o)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||o===0&&i==="components"||o===1&&i==="schemas"||t[0]==="paths"&&(o===0||o===1&&["get","post","put","delete","patch"].includes(i)||o===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=Ln(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:Sv.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:Sv.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 c=t.$ref.split("#"),l=c[0];if(n=c[1],!l)return{resolved:!1};s=l;let p=await fetch(l);if(!p.ok)return{resolved:!1};try{let d=await p.text();try{o=JSON.parse(d),r=o}catch{o=wr.load(d),r=o}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let u=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(c=>c.replace(/~1/g,"/"));for(let c of u){if(typeof r!="object"||r==null)return{resolved:!1};r=r[c]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let c=new Set;c.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,c,s)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let u=r,c=s.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of c){if(typeof u!="object"||u===null)return t;u=u[l]}if(u!=null){let l=await this.resolveNestedExternalReferences(u,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return qt.ObjectPropertyAccess.ReadOnly;if(i)return qt.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 kI.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}let i=new kI.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:JE.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 Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Na=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]}};Ci();var kI={};Y(kI,{AudienceExtension:()=>bVe,FernAvailabilityExtension:()=>xdr,FernEnumExtension:()=>EVe,FernIgnoreExtension:()=>VOe,FernOptionalExtension:()=>_dr,FernTypeExtension:()=>Pdr,FernTypeNameExtension:()=>Tdr,SdkGroupNameExtension:()=>Sdr,SdkMethodNameExtension:()=>Bdr,ServerFromOperationNameExtension:()=>Odr});var bVe=class extends Na{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 xdr=class extends Na{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 JE.InDevelopment;case"PRE_RELEASE":case"BETA":return JE.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return JE.GeneralAvailability;case"DEPRECATED":return JE.Deprecated;default:return}}};var W3p=mt.object({snake:mt.string().optional(),camel:mt.string().optional(),screamingSnake:mt.string().optional(),pascal:mt.string().optional()}),$3p=mt.object({description:mt.string().optional(),name:mt.string().optional(),casing:W3p.optional()}),fla=mt.record($3p);var EVe=class extends Na{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=fla.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 VOe=class extends Na{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 _dr=class extends Na{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 Sdr=class extends Na{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 Bdr=class extends Na{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 Odr=class extends Na{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 Pdr=class extends Na{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 Tdr=class extends Na{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var N6=class extends io{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new LBe(n),this.ir={auth:{docs:void 0,requirement:qt.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:qt.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new VOe({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 VOe({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(u=>u.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(u=>u.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(u=>u.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n};let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i));let o=this.context.exampleGenerationArgs,s=hhi({ir:i,exampleGeneration:o});if(this.context.generateV1Examples){let a=N0t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let o of Object.values(t.services)){let s=[];for(let a of o.endpoints)r.has(a.id)&&s.push(a);o.endpoints=s}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([o])=>n.has(o))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([o,s])=>{let a=s.filter(u=>u.id!=null&&i.has(u.id));return[o,a]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:o}){let s=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),a=this.getOrCreatePackage({group:n}),u=[...s].map(p=>this.context.casingsGenerator.generateName(p)),c=u[u.length-1];a.service==null&&(a.service=o??`service_${s.map(p=>Ln(p)).join("/")}`),this.ir.services[a.service]==null&&(this.ir.services[a.service]=this.createNewService({allParts:u,finalpart:c,endpointGroupDisplayName:i})),this.ir.services[a.service]?.endpoints.push(t);let l=this.ir.services[a.service];l!=null&&(this.irGraph.addEndpoint(l,t),this.irGraph.markEndpointForAudience(l.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let o=i?.join(".")??r,s=this.getOrCreatePackage({group:i});this.ir.webhookGroups[o]==null&&(this.ir.webhookGroups[o]=[]),this.ir.webhookGroups[o].push(t),s.webhooks=o;let a=this.context.createFernFilepath();this.irGraph.addWebhook(a,t),n!=null&&this.irGraph.markWebhookForAudiences(a,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=Ln(i?.join(".")),s=Ln(r),a=this.context.namespace?`${Ln(this.context.namespace)}/`:"",u=o?`channel_${a}${o}`:`channel_${a}${s}`,c=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[u]:t},u!==""?c.websocket==null&&(c.websocket=u):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,u,t),n!=null&&this.irGraph.markChannelForAudiences(l,u,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(u=>u===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:hy(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>Ln(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 u=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=u}return n}};var qf={};Y(qf,{AbstractConverters:()=>rIi,ExampleConverter:()=>tE,SchemaConverters:()=>tIi,ServersConverter:()=>BQ});var rIi={};Y(rIi,{AbstractMediaTypeObjectConverter:()=>Fdr,AbstractParameterConverter:()=>kdr});Ci();Qt();var H3p=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function K3p(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 dla(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var tE=class e extends io{MAX_DEPTH=12;EXAMPLE_STRING=Ai.STRING;EXAMPLE_NUMBER=Ai.DOUBLE;EXAMPLE_BOOLEAN=Ai.BOOLEAN;EXAMPLE_INTEGER=Ai.INT;EXAMPLE_DATE=Ai.DATE;EXAMPLE_DATE_TIME=Ai.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:u=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=u}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let u;return s!=null?typeof s=="boolean"?u=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:u=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(u=i),a!==void 0&&u!==void 0?(t<a||t>u)&&(t=a+(u-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):u!==void 0&&t>u&&(t=u-Math.abs(u*.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(u=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:u,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(u=>u?.isValid??!1)&&!r,a=!r&&o.some(u=>u.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(u=>u.validExample),errors:s?[]:o.flatMap(u=>u.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=Object.entries(t.properties??{}).map(([p,d])=>{if(typeof d!="object")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:p,resolvedSchema:t}))return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let f=!(p in r)||!("nullable"in d)&&r[p]==null||"nullable"in d&&d.nullable===!0&&r[p]===void 0,m=!t.required?.includes(p);if(f&&m){if(this.example===void 0&&this.generateOptionalProperties){let h=this.maybeResolveSchemaExample(d),g=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:p,result:g.convert()}}return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let h=r[p],g=h!==void 0?h:this.maybeResolveSchemaExample(d),E=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:p,result:E}}}),i=(t.allOf??[]).map((p,d)=>{let f=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],skipErrorCollector:!0});return f&&this.isConstraintOnlySchema(f)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...p,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),o=this.example!==void 0&&(n.some(({result:p})=>p.usedProvidedExample)||i.some(p=>p.usedProvidedExample)),s=Object.fromEntries(n.map(({key:p,result:d})=>[p,d.validExample]).filter(([p,d])=>d!==void 0));for(let p of i)if(typeof p.validExample=="object"&&p.validExample!==null){let d=p.validExample;s={...s,...Object.fromEntries(Object.entries(d).filter(([f,m])=>m!==void 0))}}let a=[],u=this.collectAllPropertyKeys(t),c=Object.keys(r).filter(p=>!u.has(p));if(c.length>0)if(t.additionalProperties===!1)c.forEach(p=>{let d=[...this.breadcrumbs,p].join("."),f={message:`Found unexpected property '${p}' in example. This property does not exist in the schema${d?` at path: ${d}`:""}`,path:[...this.breadcrumbs,p]};a.push({key:p,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[f]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)c.forEach(p=>{a.push({key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[p],errors:[]}})});else{let p=t.additionalProperties;c.forEach(d=>{let m=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:p,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();a.push({key:d,result:m})})}for(let{key:p,result:d}of a)d.validExample!==void 0&&s[p]===void 0&&(s[p]=d.validExample);let l=n.every(p=>p.result.isValid)&&i.every(p=>p.isValid)&&a.every(({result:p})=>p.isValid);if(Object.keys(s).length===0){let p=i.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));p&&(s=p.validExample)}return{isValid:l,coerced:!1,usedProvidedExample:o,validExample:s,errors:[...n.flatMap(({result:p})=>p.errors),...i.flatMap(p=>p.errors),...a.flatMap(({result:p})=>p.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,u)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${u}]`],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??this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let h=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});h&&d.push(h)}if(d.length>0&&d.every(m=>K3p(m))){let m=d.findIndex(h=>dla(h)!==void 0);if(m!==-1){let h=n[m],g=d[m];if(h&&g){let A=dla(g),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...h,oneOf:void 0}:h,example:A,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,h=i??this.maybeResolveSchemaExample(m),A=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(A.isValid&&!A.coerced&&A.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:A.validExample,errors:[]};if(A.isValid&&!A.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:A.usedProvidedExample,validExample:A.validExample,errors:[]};o.push(A),A.isValid&&A.usedProvidedExample&&a===null&&(a=A),A.isValid&&s===null&&(s=A)}let u=a??s,c=u!==null,l=u?.validExample??o[0]?.validExample,p=u?.usedProvidedExample??!1;return{isValid:c,coerced:!1,usedProvidedExample:p,validExample:l,errors:c?[]: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(H3p);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let u of a)n.add(u)}}}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 u of a)n.add(u)}}}return n}};var tIi={};Y(tIi,{ArraySchemaConverter:()=>CVe,EnumSchemaConverter:()=>yme,ObjectSchemaConverter:()=>IVe,OneOfSchemaConverter:()=>qOe,PrimitiveSchemaConverter:()=>wVe,SchemaConverter:()=>bme,SchemaOrReferenceConverter:()=>HS});Ci();function mla(e){return D0({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Rr.primitive({v1:"BASE_64",v2:Qn.base64({})});case"BOOLEAN":return Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})});case"DATE":return Rr.primitive({v1:"DATE",v2:Qn.date({})});case"DATE_TIME":return Rr.primitive({v1:"DATE_TIME",v2:Qn.dateTime({})});case"DATE_TIME_RFC_2822":return Rr.primitive({v1:"DATE_TIME_RFC_2822",v2:Qn.dateTimeRfc2822({})});case"FLOAT":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:void 0,validation:void 0})});case"DOUBLE":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:void 0,validation:void 0})});case"UINT":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:void 0,validation:void 0})});case"UINT_64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:void 0,validation:void 0})});case"INTEGER":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:void 0,validation:void 0})});case"LONG":return Rr.primitive({v1:"LONG",v2:Qn.long({default:void 0,validation:void 0})});case"STRING":return Rr.primitive({v1:"STRING",v2:Qn.string({default:void 0,validation:void 0})});case"UUID":return Rr.primitive({v1:"UUID",v2:Qn.uuid({})});case"BIG_INTEGER":return Rr.primitive({v1:"BIG_INTEGER",v2:Qn.bigInteger({default:void 0})});default:return}},unknown:()=>Rr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Rr.container(zs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Rr.container(zs.list(t))},optional:t=>{if(t!=null)return Rr.container(zs.optional(t))},nullable:t=>{if(t!=null)return Rr.container(zs.nullable(t))},set:t=>{if(t!=null)return Rr.container(zs.set(t))},literal:t=>Rr.container(zs.literal(t._visit({string:r=>ww.string(r),boolean:r=>ww.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var yme=class extends io{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:$a.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}};var Ddr=class extends io{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=Rr.container(zs.map({keyType:io.STRING,valueType:Rr.unknown()}));return{type:$a.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new HS({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Rr.container(zs.map({keyType:io.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return{type:$a.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};Qt();function vVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let o=[],s={},a={},u=new Set;for(let[c,l]of Object.entries(e??{})){let p=[...r,"properties",c];if(typeof l!="object"){i.collect({message:`Schema property ${c} should be an object`,path:p});continue}let d=Y3p(r,l,n)??n.convertBreadcrumbsToName(p),f="nullable"in l?l.nullable:!1,h=new HS({context:n,breadcrumbs:p,schemaOrReference:l,schemaIdOverride:d,wrapAsOptional:!t.includes(c),wrapAsNullable:f}).convert();if(h!=null){o.push({name:n.casingsGenerator.generateNameAndWireValue({name:c,wireValue:c}),valueType:h.type,docs:l.description,availability:h.availability,propertyAccess:n.getPropertyAccess(l),v2Examples:h.schema?.typeDeclaration?.v2Examples??J3p({propertySchema:l,breadcrumbs:p,context:n,propertyId:d})}),s={...s,...h.inlinedTypes},h.schema?.typeDeclaration.referencedTypes!=null&&h.schema.typeDeclaration.referencedTypes.forEach(g=>{u.add(g)});for(let g of h.schema?.audiences??[])a[g]==null&&(a[g]=new Set),a[g].add(c)}}for(let c of Object.keys(s))u.add(c);return{convertedProperties:o,propertiesByAudience:a,inlinedTypesFromProperties:s,referencedTypes:u}}function J3p({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 c={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new tE({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:h}=m.convert();c[f]=h}return{userSpecifiedExamples:c,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new tE({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:u}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:u}}}function Y3p(e,t,r){return r.isReferenceObject(t)?void 0:new kI.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var IVe=class extends io{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:$a.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=vVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),s=[],a=i,u=this.schema.required!=null&&this.schema.required.length>0,c=n,l=o;for(let[p,d]of(this.schema.allOf??[]).entries()){let f=[...this.breadcrumbs,"allOf",p.toString()],m;if(this.context.isReferenceObject(d)){let b=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:f});if(b==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${p}] reference could not be resolved. Skipping: ${JSON.stringify(d)}`);continue}if(m=b,typeof m.additionalProperties=="boolean"&&m.additionalProperties&&(t=!0),!u||Object.keys(m.properties??{}).every(I=>!this.schema.required?.includes(I))){this.addTypeReferenceToExtends({reference:d,breadcrumbs:f,extends_:s,referencedTypes:a});continue}}else m=d;typeof m.additionalProperties=="boolean"&&m.additionalProperties&&(t=!0);let h=m.oneOf??m.anyOf;if(h!=null&&m.type==null&&m.properties==null){let b=new Set(r.map(I=>I.name.wireValue));for(let[I,w]of h.entries()){let x=[...f,m.oneOf!=null?"oneOf":"anyOf",I.toString()],C=this.context.isReferenceObject(w)?this.context.resolveMaybeReference({schemaOrReference:w,breadcrumbs:x}):w;if(C==null)continue;let _={};for(let[V,K]of Object.entries(C.properties??{}))!this.context.isReferenceObject(K)&&"not"in K||(_[V]=K);let R=Object.keys(_).filter(V=>!b.has(V));if(R.length===0)continue;let U={};for(let V of R){let K=_[V];K!=null&&(U[V]=K,b.add(V))}let{convertedProperties:q,inlinedTypesFromProperties:z,referencedTypes:Z,propertiesByAudience:oe}=vVe({properties:U,required:[],breadcrumbs:x,context:this.context,errorCollector:this.context.errorCollector});r.push(...q),c={...c,...z},l={...l,...oe},Z.forEach(V=>{a.add(V)})}continue}let{convertedProperties:g,inlinedTypesFromProperties:A,referencedTypes:E,propertiesByAudience:v}=vVe({properties:m.properties??{},required:[...this.schema.required??[],...m.required??[]],breadcrumbs:f,context:this.context,errorCollector:this.context.errorCollector});r.push(...g),c={...c,...A},l={...l,...v},E.forEach(b=>{a.add(b)})}for(let p of Object.keys(c))a.add(p);return{type:$a.object({properties:r,extends:s.map(p=>this.context.typeReferenceToDeclaredTypeName(p)).filter(ma),extendedProperties:[],extraProperties:t}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:c}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}};var Rdr=class extends Na{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 qOe=class extends io{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 Rdr({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null)return this.convertAsDiscriminatedUnion();if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let u of t){let c;if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(c=l.value)}else c=u;c!=null&&(c.enum!=null&&c.enum.length>1&&(c.type==="string"||c.type==null)?r=c:c.type==="string"&&c.enum==null&&(n=!0))}if(r==null||!n)return;let o=new EVe({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new yme({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let[c,l]of Object.entries(this.schema.discriminator.mapping??{})){let p=this.context.getTypeIdFromSchemaReference({$ref:l}),d=[...this.breadcrumbs,"discriminator","mapping",c],f=this.context.resolveReference({reference:{$ref:l},breadcrumbs:d}),m={$ref:l};f.resolved&&f.value.properties!=null&&t in f.value.properties&&(m=this.filterDiscriminantFromSchema(f.value,t));let h=new HS({context:this.context,schemaOrReference:m,schemaIdOverride:p??void 0,breadcrumbs:d});p!=null&&n.add(p);let g=h.convert();if(g?.type!=null&&p!=null){for(let v of Object.keys(g?.inlinedTypes??{}))n.add(v);for(let v of g.schema?.typeDeclaration.referencedTypes??[])n.add(v);let A=this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:c}),E=l.match(/\/schemas\/([^/]+)/)?.[1]??p;r.push({docs:void 0,discriminantValue:A,availability:g.availability,displayName:c,shape:Cw.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(E),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:c})}),i={...i,...g.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=vVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let u=[];for(let[c,l]of(this.schema.allOf??[]).entries()){let p=[...this.breadcrumbs,"allOf",c.toString()];if(this.context.isReferenceObject(l)){let d=this.context.convertReferenceToTypeReference({reference:l,breadcrumbs:p});if(d.ok){let m=this.context.typeReferenceToDeclaredTypeName(d.reference);m!=null&&u.push(m)}let f=this.context.getTypeIdFromSchemaReference(l);f!=null&&n.add(f);continue}}for(let c of Object.keys({...i,...a}))n.add(c);return{type:$a.union({baseProperties:o,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:u,types:r,discriminatorContext:void 0}),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={},i=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(o=>!this.context.isReferenceObject(o));for(let[o,s]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(s)){let d;if(this.context.isReferenceObjectWithIdentifier(s))d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:s.summary??s.title??s.name??s.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(s)!=null){let m=this.getDiscriminatorKeyForRef(s);d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:m,displayNameOverrideSource:"discriminator_key"})}else d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:s.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});d.ok&&t.push({type:d.reference,docs:s.description});let f=this.context.getTypeIdFromSchemaReference(s);f!=null&&r.add(f);continue}let a=this.extendSubSchema(s),u=this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),c=s.title,p=new bme({context:this.context,id:u,nameOverride:c,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`],schema:a??s}).convert();if(p!=null){let d=p.convertedSchema.typeDeclaration.shape;if(d.type==="alias"&&this.typeReferenceIsWrappedPrimitive(d.aliasOf))t.push({type:d.aliasOf,docs:s.description});else if(d.type==="object"&&d.properties.length===0&&d.extends.length===0)t.push({type:Rr.container(zs.map({keyType:io.STRING,valueType:Rr.unknown()})),docs:s.description});else{t.push({type:this.context.createNamedTypeReference(u,c),docs:s.description});let f=this.context.getNamespacedSchemaId(u);n={...n,...p.inlinedTypes,[f]:p.convertedSchema}}p.convertedSchema.typeDeclaration.referencedTypes.forEach(f=>{r.add(f)})}}return{type:$a.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new HS({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:$a.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 Rr.container(zs.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 wVe=class extends io{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 Rr.container(zs.literal(ww.string(t)));if(this.schema.format==="date-time-rfc-2822")return Rr.primitive({v1:Ho.DateTimeRfc2822,v2:Qn.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Rr.primitive({v1:Ho.Date,v2:Qn.date({})});if(this.schema.format==="date-time")return Rr.primitive({v1:Ho.DateTime,v2:Qn.dateTime({})})}return Rr.primitive({v1:"STRING",v2:Qn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Rr.primitive({v1:"LONG",v2:Qn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Rr.primitive({v1:"LONG",v2:Qn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Rr.primitive({v1:"INTEGER",v2:Qn.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?Rr.container(zs.literal(ww.boolean(t))):Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}};var X3p=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],bme=class e extends io{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let o=this.tryConvertArraySchema();if(o!=null)return o;let s=this.tryConvertTypeArraySchema();if(s!=null)return s;let a=this.tryConvertOneOfAnyOfSchema();if(a!=null)return a;let u=this.tryConvertMapSchema();if(u!=null)return u;let c=this.tryConvertDiscriminatorMappingSchema();if(c!=null)return c;let l=this.tryConvertObjectAllOfSchema();if(l!=null)return l;let p=this.tryConvertUntypedSchema();if(p!=null)return p;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new kI.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new yme({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.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let i=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(i?.convertedSchema.typeDeclaration?.shape.type!=="object")return i}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let i of this.schema.allOf??[]){if(this.context.isReferenceObject(i))return;let o=i.oneOf??i.anyOf;if(o!=null&&i.type==null&&i.properties==null){let s={};for(let a of o){let u=this.context.isReferenceObject(a)?this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:this.breadcrumbs}):a;if(u!=null)for(let[c,l]of Object.entries(u.properties??{}))!this.context.isReferenceObject(l)&&"not"in l||c in s||(s[c]=l)}if(Object.keys(s).length>0){let a=r.properties??{};r.properties={...a,...s}}continue}r=DNe(r,i,(s,a)=>{if(a===i)return s;if(Array.isArray(s)&&Array.isArray(a))return[...s,...a]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new wVe({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new CVe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new qOe({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 Ddr({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 qOe({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 IVe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:Rr.unknown(),resolvedType:Rr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new kI.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=mla(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...X3p,...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 tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}};var HS=class extends io{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];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:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new bme({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 Rr.container(zs.optional(t))}wrapInNullable(t){return Rr.container(zs.nullable(t))}};var CVe=class e extends io{static LIST_UNKNOWN=Rr.container(zs.list(Rr.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 HS({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),{typeReference:Rr.container(zs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Fdr=class extends io{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 u=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(u==null)return;t.schema=u}let s=new HS({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(([u,c])=>{if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[u,l.value.value??l.value]:null}return[u,c.value??c]}).filter(u=>u!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new HS({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[u,c]of s){let l=this.context.resolveExampleWithValue(c),p=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:u,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let u=Ln(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[u]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:u})}return i}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:u}=a.convert();return u}};var kdr=class extends io{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??io.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??io.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??io.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},n=this.parameter.example,i=this.parameter.examples;for(let[o,s]of Object.entries(i??{})){let a=this.context.resolveExampleWithValue(s);a!=null&&(r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:a,exampleName:o}))}if(n!=null){let o=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:n,exampleName:o})}if(Object.keys(r.userSpecifiedExamples).length===0){let o=`${this.parameter.name}_example`;r.autogeneratedExamples[o]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:o})}return r}generateOrValidateExample({schema:t,example:r}){let n=new tE({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}};Qt();var Qdr=class extends Na{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 hla="Base",Z3p="x-fern-default-url",BQ=class e extends io{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(u=>{let c=e.getServerName({server:u,context:this.context});return{id:c,name:this.context.casingsGenerator.generateName(c)}}).filter((u,c,l)=>l.findIndex(p=>p.id===u.id)===c),s=[i,...o],a=this.servers.map(u=>{let c=e.getServerName({server:u,context:this.context}),l=this.endpointLevelServers?.map(h=>[e.getServerName({server:h,context:this.context}),this.getServerUrl(h)]),p=e.getServerAudiences({server:u,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:u,endpointServers:this.endpointLevelServers??[]});return{id:c,name:this.context.casingsGenerator.generateName(c),urls:{[n]:this.getServerUrl(u),...Object.fromEntries(l??[])},docs:u.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,environments:iy.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(ma);return{value:{defaultEnvironment:r[0]?.id,environments:iy.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 Qdr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new bVe({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?hla:e.getServerExtensionName({server:this.servers[0],context:this.context})??hla}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 u=this.extractFernDefaultUrlFromServer(r);u!=null&&(i[t]=u),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let u of n){let c=e.getServerName({server:u,context:this.context});if(u.variables!=null&&Object.keys(u.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(u);l!=null&&(i[c]=l),o[c]=this.maybeRemoveTrailingSlashIfNotEmpty(u.url),s[c]=this.convertServerVariables(u.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[Z3p];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 GOe=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new tE({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 c=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!c.isValid){i=!1;let l=t.exampleSource==="human"?Sv.WARNING:Sv.ERROR;r.push(...c.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}c.coerced&&(o=!0,n.push({level:Sv.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:c.validExample}}let u=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&u!==void 0){let c=this.validateExample({example:t.responseExample,schema:u,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!c.isValid){i=!1;let l=t.exampleSource==="human"?Sv.WARNING:Sv.ERROR;r.push(...c.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}c.coerced&&(o=!0,n.push({level:Sv.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:c.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:u}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),c={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:u},l=this.validateEndpointExample({exampleToValidate:c}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf)return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let u of a)n.add(u)}}}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 u of a)n.add(u)}}}return n}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[u,c]of Object.entries(t.paths)){if(!c)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=c[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:h,responseSchemas:g}=this.getSchemasForOperation({operation:d}),A=this.extractExamplesFromOperation({operation:d,path:u,method:p});for(let E of A){n++;let v={endpointPath:u,method:p,exampleName:E.name,exampleSource:E.source,requestExample:E.request,responseExample:E.response,requestSchema:m,responseSchema:h,responseStatusCode:E.statusCode,responseSchemas:g},b=this.validateEndpointExample({exampleToValidate:v});f.push(b),b.isValid?i++:(o++,E.source==="human"?s.push(b):E.source==="ai"&&a.push(b))}f.length>0&&r.push({endpointPath:u,method:p,results:f,hasInvalidExamples:f.some(E=>!E.isValid),invalidExampleCount:f.filter(E=>!E.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 u=s.content?.["application/json"];u?.schema&&(i[o]=u.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[u,c]of Object.entries(a.examples)){let l=this.context.isReferenceObject(c)?this.context.resolveExample(c):c;l&&typeof l=="object"&&"value"in l&&i.push({name:u,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let c=a.content?.["application/json"];if(c?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=c.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:c.example,statusCode:s})}if(c?.examples)for(let[l,p]of Object.entries(c.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}};var Ndr={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"},ezp=new Set(Object.values(Ndr));Ci();var tzp=mt.object({type:mt.string(),channelId:mt.string().optional(),messageId:mt.string(),value:mt.any()}),rzp=mt.object({summary:mt.string().optional(),description:mt.string().optional(),"query-parameters":mt.record(mt.string()).optional(),headers:mt.record(mt.string()).optional(),messages:mt.array(tzp)}),gla=mt.array(rzp);var jdr=class extends Na{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=gla.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 xVe=class extends io{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 jdr({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(u=>({type:n==="v2"?u.type:u.messageId,body:u.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var nzp="x-fern-server-name",j6=class e extends io{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,environments:iy.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[nzp];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var Eme=class extends qf.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 kI.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 qf.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 Mdr=class extends Na{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 _Ve=class extends Na{channel;key="x-fern-display-name";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 Ldr=class extends xVe{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 _Ve({breadcrumbs:this.breadcrumbs,channel: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 u=[];s!=null&&u.push(s),a!=null&&u.push(a);let l=new Mdr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=hy(p),m=Ln(this.channelPath),h=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:!1,headers:n,queryParameters:r,pathParameters:t,messages:u,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})}},audiences:h,inlinedTypes:this.inlinedTypes}}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 u=MCe(Ln(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:u}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let c=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(c!=null){let p=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:c,schemaIdOverride:u}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let c=i,l=Rr.named({fernFilepath:t.createFernFilepath(),name:c.typeDeclaration.name.name,typeId:c.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=Zx.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish";return{type:d,displayName:d,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}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 Eme({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0}}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let u=new Eme({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0}}).convert();u!=null&&u.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},r.push(u.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return j6.getServerName(t,n)}return t}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 u=new Eme({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1}}).convert();u!=null&&u.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},r.push(u.parameter))}}}};var Udr=class extends j6{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 nIi="$message.",Ala="#/channels/",yla="#/servers/",zdr=class extends xVe{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 _Ve({breadcrumbs:this.breadcrumbs,channel: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((d,[f,m])=>{try{this.getChannelPathFromOperation(m)===this.channelPath&&(d[f]=m)}catch{}return d},{}),a=[];for(let[d,f]of Object.entries(s))for(let m of f.messages){let h=this.context.convertReferenceToTypeReference({reference:m});if(h.ok){let g=Zx.reference({bodyType:h.reference,docs:f.description});a.push({type:d,displayName:d,origin:f.action==="send"?"client":"server",body:g,availability:this.context.getAvailability({node:f,breadcrumbs:this.breadcrumbs}),docs:f.description,methodName:void 0})}}let u=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),c=this.transformToValidPath(this.channel.address??this.channelPath),l=hy(c),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:u,path:l,auth:!1,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:c,baseUrl:u,asyncApiVersion:"v3"})}},audiences:p,inlinedTypes:this.inlinedTypes}}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:u,parameterKey:c}=a,p=new Eme({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:c,in:u},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(nIi)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${nIi} prefix`,path:this.breadcrumbs});return}let i=r.substring(nIi.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(yla)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(yla.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 j6.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 j6.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(Ala))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(Ala.length)}};var Vdr=class extends j6{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 hIt=class extends N6{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.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 u=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(u==null)continue;let c=`${r}_${i}`;this.convertSchema({id:c,breadcrumbs:s,schema:u})}}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 qf.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 Vdr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Udr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new kI.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 zdr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new Ldr({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 gIt=class extends kA{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\/(.+)$/),u=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 c=a[1],l=a[2];return o=`${c}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return u&&u[1]?(o=u[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;return i==="reference_identifier"?a=n??s.value.title:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.title??n),{ok:!0,reference:Rr.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;return i==="reference_identifier"?a=n??s.value.name:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.name??n),{ok:!0,reference:Rr.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;return i==="reference_identifier"?a=n??s.value.messageId??s.value.name:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.messageId??s.value.name??n),{ok:!0,reference:Rr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};Qt();Vt();var xla=_e(qdr(),1);var Gdr=class extends Na{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Wdr=class extends Na{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 bla({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?io.OPTIONAL_STRING:io.STRING,env:r.env,v2Examples:r.optional?void 0:szp({header:r,context:t}),availability:void 0,docs:void 0}))}function szp({header:e,context:t}){let r=new tE({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}Ci();var $dr=class extends qf.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let n=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),o=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:n}).convert();o!=null&&(t=o.type,r=o.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};Qt();var Hdr=class extends qf.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:u,streamingExtension:c,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:u}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=c,this.queryParameters=l??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(af.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=af.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=af.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;let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:Tf.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:Tf.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes})}:{requestBody:Tf.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.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:Tf.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[o.name.wireValue];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:Tf.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?XE.file(OD.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):XE.file(OD.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):XE.bodyProperty({...t,contentType:n?.contentType??r,style:uzp({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i==null||this.context.isReferenceObject(i))return;let o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:n,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(u==null)return;let c=u.schema?.typeDeclaration.shape;if(c?.type==="object")return{requestBody:Tf.inlinedRequestBody({contentType:i,docs:void 0,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:c.extendedProperties,extends:c.extends,properties:c.properties,extraProperties:c.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:u.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=>n.name.wireValue.toLowerCase()));return t.some(n=>r.has(n.name.wireValue.toLowerCase()))}},azp={"application/json":"json"};function uzp({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return azp[e.contentType]}}var czp=/{([^}]+)}/g,lzp=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),SVe=class extends io{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o}convertHttpMethod(){switch(this.method){case"get":return Gh.Get;case"post":return Gh.Post;case"put":return Gh.Put;case"delete":return Gh.Delete;case"patch":return Gh.Patch;case"head":return Gh.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let o of this.operation.parameters){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t});if(s==null)continue;let u=new $dr({context:this.context,breadcrumbs:t,parameter:s}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let c=u.parameter.name.name.originalName,l=u.parameter.name.wireValue,p=!1,d=this.context.authOverrides?.["auth-schemes"];if(d!=null){for(let m of Object.values(d))if(mzp(m)&&m.header.toLowerCase()===l.toLowerCase()){p=!0;break}}let f=this.context.globalHeaderNames;if(f!=null){for(let m of f)if(m.toLowerCase()===l.toLowerCase()){p=!0;break}}!lzp.has(c.toLowerCase())&&!p&&i.push(u.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}checkMissingPathParameters(t){let n=[...this.path.matchAll(czp)].map(i=>i[1]).filter(i=>!t.some(o=>o.name.originalName===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:io.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode: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[u,c]of Object.entries(s.content)){let p=new Hdr({context:this.context,breadcrumbs:t,contentType:u,mediaType:c,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new kI.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new kI.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?Ln(this.operation.summary):Ln(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let n=Ela(t),i=Ela(r);return Qb(n,i)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:n,methodName:r,methodNameTokens:i})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,u)=>a!==i[u]))return{group:[t],method:n};let s=i.slice(r.length);return{group:[t],method:Ln(s.join("_"))}}generateStringParameterExample({example:t}){let r=new qf.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}};function Ela(e){let t=pzp(e)?fzp(e):dzp(e);return t=t.map(r=>r.toLowerCase()),t=dj(t),t}function pzp(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function fzp(e){return e.split(/(?=[A-Z])/)}function dzp(e){return e.split(/[^a-zA-Z0-9]+/)}function mzp(e){return e?.header!=null}var BVe=class extends SVe{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let u=a[0]?.requestBody;if(u==null)return;let c,l;if(u.type==="inlinedRequestBody")c=xw.inlinedPayload({name:u.name,extends:u.extends,properties:u.properties});else if(u.type==="reference")c=xw.reference({payloadType:u.requestBodyType,docs:u.docs});else if(u.type==="fileUpload")l={name:u.name,properties:u.properties,docs:u.docs,v2Examples:u.v2Examples,contentType:u.contentType},c=xw.inlinedPayload({name:u.name,extends:[],properties:[]});else return;let p=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:c,signatureVerification:void 0,fileUploadPayload:l,responses:p.length>0?p:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(u.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(u.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 sIi=_e(qdr(),1);var vla=["get","post","put","delete","patch","head"];var Kdr=class extends Na{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 hzp=mt.object({cursor:mt.string(),next_cursor:mt.string(),results:mt.string()}),gzp=mt.object({offset:mt.string(),results:mt.string(),step:mt.string().optional(),"has-next-page":mt.string().optional()}),Azp=mt.object({next_uri:mt.string(),results:mt.string()}),yzp=mt.object({next_path:mt.string(),results:mt.string()}),iIi=mt.union([mt.boolean(),hzp,gzp,Azp,yzp]);var oIi="$request.",Ime="$response.",Jdr=class extends Na{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=iIi.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=iIi.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:kA.maybeTrimPrefix(r.cursor,oIi),nextCursor:kA.maybeTrimPrefix(r.next_cursor,Ime),results:kA.maybeTrimPrefix(r.results,Ime)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:kA.maybeTrimPrefix(n.next_uri,Ime),results:kA.maybeTrimPrefix(n.results,Ime)};let i=t;if("next_path"in i)return{type:"path",nextPath:kA.maybeTrimPrefix(i.next_path,Ime),results:kA.maybeTrimPrefix(i.results,Ime)};let o=t;return{type:"offset",offset:kA.maybeTrimPrefix(o.offset,oIi),results:kA.maybeTrimPrefix(o.results,Ime),step:o.step!=null?kA.maybeTrimPrefix(o.step,oIi):void 0,hasNextPage:o["has-next-page"]!=null?kA.maybeTrimPrefix(o["has-next-page"],Ime):void 0}}};var bzp="$request.",Ezp=mt.object({"stream-condition":mt.string().optional(),format:mt.enum(["sse","json"]).optional(),"stream-description":mt.string().optional(),"stream-request-name":mt.string().optional(),"response-stream":mt.any(),response:mt.any(),terminator:mt.string().optional()}),vzp=mt.union([mt.boolean(),Ezp]),Ydr=class extends Na{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=vzp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:kA.maybeTrimPrefix(r.data["stream-condition"],bzp),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response}}};var Xdr=class extends Na{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}}};Ci();Qt();var emr=require("fs"),Ila=require("path");function Izp(e){return ba(e)&&typeof e.$ref=="string"}function wzp(e,t){if(e!=null){if(typeof e=="string")return e;if(Izp(e)){let r=(0,Ila.resolve)(t??process.cwd(),e.$ref);if((0,emr.existsSync)(r))try{return(0,emr.readFileSync)(r,"utf-8")}catch{return}}}}var Zdr=class extends Na{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=ba(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 u of s){if(!ba(u))continue;let c=u,l=c.lang,p=c.label,d=c.source;if(typeof l!="string")continue;let f=wzp(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}};Qt();var rmr=require("fs"),wla=require("path");function Czp(e){return ba(e)&&typeof e.$ref=="string"}function xzp(e,t){if(e!=null){if(typeof e=="string")return e;if(Czp(e)){let r=(0,wla.resolve)(t??process.cwd(),e.$ref);if((0,rmr.existsSync)(r))try{return(0,rmr.readFileSync)(r,"utf-8")}catch{return}}}}function _zp(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!ba(n))continue;let o=xzp(n.code,t);o!=null&&r.push({...n,code:o})}return r}var tmr=class extends Na{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(!ba(o))return o;let a=o["code-samples"];if(a!=null){let u=_zp(a,this.baseDir);return{...o,"code-samples":u}}return o}).filter(o=>{let s=$d.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 AIt=class extends Na{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}}};Qt();var yIt=class extends qf.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300){let o={schema:{type:"object",description:"Empty response body"}},s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:"application/json",resolveSchema:!0});if(s!=null)return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:s})}}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:Zu.json(P0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:Zu.streaming(jb.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:Zu.streaming(jb.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:Zu.streaming(jb.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:Zu.json(P0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:Zu.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:Zu.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:Zu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return af.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=io.OPTIONAL_STRING;if(s!=null){let c=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});c!=null&&(c.type==="number"||c.type==="integer"?a=Rr.primitive({v1:c.type==="integer"?"INTEGER":"DOUBLE",v2:c.type==="integer"?Qn.integer({default:void 0,validation:void 0}):Qn.double({default:void 0,validation:void 0})}):c.type==="boolean"&&(a=Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})})))}let u=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:u,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,u]of Object.entries(s??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:c}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};var nmr=class extends qf.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:u}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=u}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:Rr.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:Cla(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),u=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),c=this.getIdForErrorExample({key:o,example:u,usedExampleNames:n});n.add(c),a!=null&&(i[c]=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 Ndr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?Cla(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=io.OPTIONAL_STRING;if(s!=null){let c=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});c!=null&&(c.type==="number"||c.type==="integer"?a=Rr.primitive({v1:c.type==="integer"?"INTEGER":"DOUBLE",v2:c.type==="integer"?Qn.integer({default:void 0,validation:void 0}):Qn.double({default:void 0,validation:void 0})}):c.type==="boolean"&&(a=Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})})))}let u=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:u,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,u]of Object.entries(s??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:c}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};function Cla(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var imr=class e extends SVe{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,idempotent:s,idToAuthScheme:a,topLevelServers:u,pathLevelServers:c,streamingExtension:l}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o}),this.idempotent=s,this.idToAuthScheme=a,this.topLevelServers=u,this.pathLevelServers=c,this.streamingExtension=l}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),{headers:o,pathParameters:s,queryParameters:a}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:a}),c=u?.[0]?.requestBody,l=u?.[0]?.streamRequestBody,p={requestBodies:u?.map(K=>K.requestBody)},d=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),f=d?.response,m=d?.streamResponse,h=d!=null?d.errors:[],g={},A=h.map(K=>K.error),E=hy(this.path),v=this.getEndpointBaseUrl(),b=this.getEndpointBaseUrls(),I=this.convertExamples({httpPath:E,httpMethod:t,baseUrl:v}),w=new Set(this.operation.security?.flatMap(K=>Object.keys(K))??[]),x=this.authSchemeToHeaders(Array.from(w));x.length>0&&o.push(...x);for(let K of h){let be=K.error,Ce=K.errorType,J=be.error.errorId,H=K.examples;g[J]={name:be.error,displayName:K.displayName,discriminantValue:{name:be.error.name,wireValue:J},type:Ce,statusCode:K.statusCode,isWildcardStatusCode:K.isWildcardStatusCode,docs:be.docs,examples:[],v2Examples:{userSpecifiedExamples:H??{},autogeneratedExamples:{}},headers:K.headers}}let C=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],R=new AIt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),z=new AIt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??R,Z={displayName:this.operation.summary,method:t,baseUrl:v,v2BaseUrls:b,path:E,pathParameters:s,queryParameters:a,headers:o.filter((K,be,Ce)=>be===Ce.findIndex(J=>J.name.wireValue===K.name.wireValue)),responseHeaders:d?.responseHeaders,sdkRequest:void 0,errors:A,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:E,allPathParameters:s,pagination:void 0,transport:void 0,source:rS.openapi(),audiences:C,retries:void 0,apiPlayground:z},oe=this.context.namespace!=null?[this.context.namespace]:[],V=r?.map(K=>Ln(K));return oe.push(...V??[]),{audiences:C,group:r,groupDisplayName:i,errors:g,endpoint:{...Z,id:`endpoint_${oe.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:c,v2RequestBodies:p,response:f,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:I.examples},v2Responses:{responses:d?.v2Responses}},streamEndpoint:m!=null&&m.body!=null?{...Z,id:`endpoint_${oe.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:l,v2RequestBodies:void 0,response:m,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:I.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:m.body,docs:m.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1;for(let[a,u]of Object.entries(this.operation.responses)){let c=/^[45]XX$/i.test(a),l,p=!1;if(c)l=parseInt(a.charAt(0))*100,p=!0;else{if(l=parseInt(a),isNaN(l)||l<200||l>=300&&l<400)continue;p=l>=400&&l<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),l>=200&&l<300){let d=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,a]});if(d==null)continue;let m=new yIt({context:this.context,breadcrumbs:[...t,a],responseBody:d,group:r??[],method:n,statusCode:a,streamingExtension:i}).convert();m!=null&&(this.inlinedTypes={...this.inlinedTypes,...m.inlinedTypes},s||(s=!0,o.response={statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.responseBody,docs:d.description},o.streamResponse={statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.streamResponseBody,docs:d.description},m.headers!=null&&(o.responseHeaders=m.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.responseBody,docs:d.description}])}if(p){let d=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,a]});if(d==null)continue;let m=new nmr({context:this.context,breadcrumbs:[...t,a],responseError:d,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:l,isWildcardStatusCode:c?!0:void 0}).convert();m!=null&&(this.inlinedTypes={...this.inlinedTypes,...m.inlinedTypes},o.errors.push(m))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new yIt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():this.operation.security??this.context.spec.security}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:io.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples: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 tmr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new Zdr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return c.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:c}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:c}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(c=>!(c.response!=null&&"stream"in c.response)),s=i.filter(c=>c.response!=null&&"stream"in c.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),u=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:u}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let u=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:u,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 qt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return qt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new kI.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${bn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return BQ.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(n=>{let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return BQ.getServerName({server:o,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let n=t?.[t.length-1];if(n!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===n?r:void 0}};var omr=class extends io{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s}convert(){let t=[],r=[],n={};for(let i of vla){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 c=new Ydr({breadcrumbs:s,operation:o,context:this.context}).convert();c==null&&this.operationHasTextEventStreamResponse(o)&&(c={type:"stream",format:"sse",terminator:void 0});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:c});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new Xdr({breadcrumbs:n,operation:t,context:i}).convert()?new BVe({context:this.context,breadcrumbs:n,operation:t,method:sIi.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new Jdr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let u=new Kdr({breadcrumbs:n,operation:t,context:this.context}).convert();return new imr({context:this.context,breadcrumbs:n,operation:t,method:sIi.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:u,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}};var smr=class extends io{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",n=t?.env;return ud.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:n,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",n=t?.password?.name??"password",i=t?.username?.env,o=t?.password?.env;return ud.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(n),usernameEnvVar:i,passwordEnvVar:o,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",n=t?.env,i=t?.prefix;return ud.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:io.OPTIONAL_STRING,prefix:i,headerEnvVar:n,docs:this.securityScheme.description})}break}case"oauth2":return ud.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var bIt=class extends N6{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.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Wdr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=bla({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertBasePath(){let r=new Gdr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=hy(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=uhi({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new smr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let i=k0t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return i!=null&&this.addEnvironmentsToIr({environmentConfig:i.environmentsConfig,audiences:i.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let n=new BQ({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 qf.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 BVe({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:xla.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[n,i]of Object.entries(this.context.spec.paths??{})){if(i==null)continue;let s=new omr({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:i,path:n}).convert();if(s!=null){for(let a of s.endpoints){if(a.streamEndpoint!=null&&this.addEndpointToIr({endpoint:a.streamEndpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),this.addEndpointToIr({endpoint:a.endpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),a.servers)for(let u of a.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(a.errors)for(let[u,c]of Object.entries(a.errors))r[u]=c}for(let a of s.webhooks){let u=this.context.getGroup({groupParts:a.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:a.webhook,operationId:u.join("."),group:u,audiences:a.audiences})}this.addTypesToIr(s.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security&&delete i.security}}}};var amr=class extends Na{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 koe=class extends kA{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.getRawSchemaNameFromReference(t)??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let u;i==="reference_identifier"?u=n??a.value.title:i==="discriminator_key"?u=a.value.title??n:i==="schema_identifier"&&(u=a.value.title);let c;if(o.includes("/")){let p=new qf.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(c={[o]:p.convertedSchema})}return{ok:!0,reference:Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:u}),inlinedTypes:c}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new amr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=i}return this.tagToDisplayName[t]??t}};var Szp=mt.object({description:mt.string().optional(),required:mt.boolean().optional(),deprecated:mt.boolean().optional(),allowEmptyValue:mt.boolean().optional(),style:mt.string().optional(),explode:mt.boolean().optional(),allowReserved:mt.boolean().optional(),schema:mt.any().optional(),example:mt.any().optional(),examples:mt.record(mt.string(),mt.any()).optional(),content:mt.record(mt.string(),mt.any()).optional()}),Bzp=Szp.extend({name:mt.string(),in:mt.string()}),Ozp=mt.array(Bzp),umr=class extends Na{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 Ozp.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var cmr=class extends io{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let c of this.pathParameters)r+=`/{${c.name.originalName}}`;let n=hy(r),i=[];for(let[c,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let h=this.context.resolveReference({reference:l});if(h.resolved)p=h.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new qf.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let c=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(c!=null){let l=new qf.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:c.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:c.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?Tf.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:Zu.json(P0.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:rS.openrpc(),audiences:a,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return BQ.getServerName({server:s,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let n of this.method.examples??[]){let i;if(this.context.isReferenceObject(n)){let u=this.context.resolveReference({reference:n});if(u.resolved)i=u.value;else continue}else i=n;let o;if(i.result)if(this.context.isReferenceObject(i.result)){let u=this.context.resolveReference({reference:i.result});u.resolved&&(o=u.value)}else o=i.result;let s=i.name??`Example ${r+1}`,a=[];if(i.params&&Array.isArray(i.params)){a=[];for(let u of i.params)if(this.context.isReferenceObject(u)){let c=this.context.resolveReference({reference:u});if(c.resolved)a.push(c.value);else continue}else a.push(u)}t[s]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:a.map(u=>u.value)??void 0},response:{docs:void 0,statusCode:void 0,body:o?.value?qt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:i.examplePairedRequest?.id||"1",result:o.value}):void 0},codeSamples:[]}}++r}return t}};var lmr=class extends qf.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 qf.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 EIt=class extends N6{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 BQ({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 qf.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 umr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[u,c]of n.entries()){let p=new lmr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${u}]`],parameter:c}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let u of this.context.spec.methods??[]){let c=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:["methods"]});if(c==null)continue;let p=new cmr({context:this.context,breadcrumbs:["methods"],method:c,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}};var vIt=class extends kA{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;return i==="reference_identifier"?a=n??s.value.title:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.title??n),{ok:!0,reference:Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};var Mma=require("fs/promises");var _la=require("fs/promises");async function aIi({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,_la.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=wr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await yVe({absoluteFilePathToOverrides:a,context:e,data:s});return s}Vt();var efa=_e(Zpa(),1);function I8p(e,t){if(!t)return;if(e.catch(()=>{}),t.aborted){e.kill();return}let r=()=>{e.kill()};t.addEventListener("abort",r,{once:!0}),e.finally(()=>t.removeEventListener("abort",r)).catch(()=>{})}function L4(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let u=i.reduce((p,d)=>({...p,[d]:"<redacted>"}),o),c=[t,...r].join(" ");for(let[p,d]of Object.entries(u))c=c.replaceAll(p,d);e?.debug(`+ ${c}`);let l=(0,efa.default)(t,r,a);return I8p(l,s),l}async function cc(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let u=L4(e,t,r,{doNotPipeOutput:n,secrets:i,substitutions:o,signal:s,...a});n||(u.stdout?.pipe(process.stdout),u.stderr?.pipe(process.stderr));let c=await u;return c.stdout==null&&(c.stdout=""),c.stderr==null&&(c.stderr=""),c}function wme(e,{logger:t,...r}={}){return(n,i)=>cc(t,e,n,{...r,...i})}var xP=require("fs/promises"),lfa=_e(require("path"),1),xIi=_e(Aw(),1);Vt();var WOe=require("fs/promises"),tfa=_e(Aw(),1);function SIt(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var _It,CIi;async function BIt(e,t,r=5e3){return _It!==void 0?_It:(CIi==null&&(CIi=w8p(e,t,r)),CIi)}async function w8p(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),_It=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(n){let i=n instanceof Error?n.message:String(n);return SIt(i)?(_It=!0,t.debug(`Network check failed - entering air-gapped mode: ${i}`),!0):(_It=!1,!1)}}async function ymr(e,t){let r=We(e,Se.of("buf.lock")),n=!1;try{await(0,WOe.access)(r),n=!0,t.debug(`Found buf.lock at: ${r}`)}catch{t.debug(`No buf.lock found at: ${r}`)}if(!n)return!1;let i=Ut.of((await tfa.default.dir()).path);try{let o=We(e,Se.of("buf.yaml"));try{await(0,WOe.cp)(o,We(i,Se.of("buf.yaml"))),await(0,WOe.cp)(r,We(i,Se.of("buf.lock")))}catch{return!1}try{return await L4(t,"buf",["dep","update"],{cwd:i,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(s){let a=s instanceof Error?s.message:String(s);return SIt(a)?(t.debug(`Network check failed - entering air-gapped mode: ${a.substring(0,100)}`),!0):!1}}finally{try{await(0,WOe.rm)(i,{recursive:!0,force:!0})}catch{}}}var rfa="buf.gen.yaml",C8p="output",nfa=`${C8p}/ir.json`,ifa="protoc-gen-fern",ofa=`version: v1
1543
+ `).reduce(tQp,Object.create(null)),tQp=(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},rQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Zl=rQp!=="win32"?e=>e:e=>e&&e.replace(/\\/g,"/"),poa=class extends TOe{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=Zl(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?Zl(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=Zl(e.path)),e.linkpath&&(e.linkpath=Zl(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},cfr=(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))},nQp=1024*1024,s0i=Buffer.from([31,139]),a0i=Buffer.from([40,181,47,253]),iQp=Math.max(s0i.length,a0i.length),F4=Symbol("state"),vOe=Symbol("writeEntry"),_oe=Symbol("readEntry"),Gbi=Symbol("nextEntry"),Bia=Symbol("processEntry"),SH=Symbol("extendedHeader"),XEt=Symbol("globalExtendedHeader"),qde=Symbol("meta"),Oia=Symbol("emitMeta"),Dg=Symbol("buffer"),Soe=Symbol("queue"),Gde=Symbol("ended"),Wbi=Symbol("emittedEnd"),IOe=Symbol("emit"),Cv=Symbol("unzip"),Npr=Symbol("consumeChunk"),jpr=Symbol("consumeChunkSub"),$bi=Symbol("consumeBody"),Pia=Symbol("consumeMeta"),Tia=Symbol("consumeHeader"),ZEt=Symbol("consuming"),Hbi=Symbol("bufferConcat"),Mpr=Symbol("maybeEnd"),z6e=Symbol("writing"),Wde=Symbol("aborted"),Lpr=Symbol("onDone"),wOe=Symbol("sawValidEntry"),Upr=Symbol("sawNullBlock"),zpr=Symbol("sawEOF"),Dia=Symbol("closeStream"),oQp=()=>!0,dvt=class extends roa.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Soe]=[];[Dg];[_oe];[vOe];[F4]="begin";[qde]="";[SH];[XEt];[Gde]=!1;[Cv];[Wde]=!1;[wOe];[Upr]=!1;[zpr]=!1;[z6e]=!1;[ZEt]=!1;[Wbi]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(Lpr,()=>{(this[F4]==="begin"||this[wOe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(Lpr,e.ondone):this.on(Lpr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||nQp,this.filter=typeof e.filter=="function"?e.filter:oQp;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[Dia]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){cfr(this,e,t,r)}[Tia](e,t){this[wOe]===void 0&&(this[wOe]=!1);let r;try{r=new POe(e,t,this[SH],this[XEt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[Upr]?(this[zpr]=!0,this[F4]==="begin"&&(this[F4]="header"),this[IOe]("eof")):(this[Upr]=!0,this[IOe]("nullBlock"));else if(this[Upr]=!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[vOe]=new poa(r,this[SH],this[XEt]);if(!this[wOe])if(i.remain){let o=()=>{i.invalid||(this[wOe]=!0)};i.on("end",o)}else this[wOe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[IOe]("ignoredEntry",i),this[F4]="ignore",i.resume()):i.size>0&&(this[qde]="",i.on("data",o=>this[qde]+=o),this[F4]="meta"):(this[SH]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[IOe]("ignoredEntry",i),this[F4]=i.remain?"ignore":"header",i.resume()):(i.remain?this[F4]="body":(this[F4]="header",i.end()),this[_oe]?this[Soe].push(i):(this[Soe].push(i),this[Gbi]())))}}}[Dia](){queueMicrotask(()=>this.emit("close"))}[Bia](e){let t=!0;if(!e)this[_oe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[_oe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[Gbi]()),t=!1);return t}[Gbi](){do;while(this[Bia](this[Soe].shift()));if(!this[Soe].length){let e=this[_oe];!e||e.flowing||e.size===e.remain?this[z6e]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[$bi](e,t){let r=this[vOe];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[F4]="header",this[vOe]=void 0,r.end()),i.length}[Pia](e,t){let r=this[vOe],n=this[$bi](e,t);return!this[vOe]&&r&&this[Oia](r),n}[IOe](e,t,r){!this[Soe].length&&!this[_oe]?this.emit(e,t,r):this[Soe].push([e,t,r])}[Oia](e){switch(this[IOe]("meta",this[qde]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[SH]=rfr.parse(this[qde],this[SH],!1);break;case"GlobalExtendedHeader":this[XEt]=rfr.parse(this[qde],this[XEt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[SH]??Object.create(null);this[SH]=t,t.path=this[qde].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[SH]||Object.create(null);this[SH]=t,t.linkpath=this[qde].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[Wde]=!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[Wde])return r?.(),!1;if((this[Cv]===void 0||this.brotli===void 0&&this[Cv]===!1)&&e){if(this[Dg]&&(e=Buffer.concat([this[Dg],e]),this[Dg]=void 0),e.length<iQp)return this[Dg]=e,r?.(),!0;for(let s=0;this[Cv]===void 0&&s<s0i.length;s++)e[s]!==s0i[s]&&(this[Cv]=!1);let i=!1;if(this[Cv]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<a0i.length;s++)if(e[s]!==a0i[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Cv]===!1&&o)if(e.length<512)if(this[Gde])this.brotli=!0;else return this[Dg]=e,r?.(),!0;else try{new POe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Cv]===void 0||this[Cv]===!1&&(this.brotli||i)){let s=this[Gde];this[Gde]=!1,this[Cv]=this[Cv]===void 0?new T2p({}):i?new k2p({}):new R2p({}),this[Cv].on("data",u=>this[Npr](u)),this[Cv].on("error",u=>this.abort(u)),this[Cv].on("end",()=>{this[Gde]=!0,this[Npr]()}),this[z6e]=!0;let a=!!this[Cv][s?"end":"write"](e);return this[z6e]=!1,r?.(),a}}this[z6e]=!0,this[Cv]?this[Cv].write(e):this[Npr](e),this[z6e]=!1;let n=this[Soe].length?!1:this[_oe]?this[_oe].flowing:!0;return!n&&!this[Soe].length&&this[_oe]?.once("drain",()=>this.emit("drain")),r?.(),n}[Hbi](e){e&&!this[Wde]&&(this[Dg]=this[Dg]?Buffer.concat([this[Dg],e]):e)}[Mpr](){if(this[Gde]&&!this[Wbi]&&!this[Wde]&&!this[ZEt]){this[Wbi]=!0;let e=this[vOe];if(e&&e.blockRemain){let t=this[Dg]?this[Dg].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Dg]&&e.write(this[Dg]),e.end()}this[IOe](Lpr)}}[Npr](e){if(this[ZEt]&&e)this[Hbi](e);else if(!e&&!this[Dg])this[Mpr]();else if(e){if(this[ZEt]=!0,this[Dg]){this[Hbi](e);let t=this[Dg];this[Dg]=void 0,this[jpr](t)}else this[jpr](e);for(;this[Dg]&&this[Dg]?.length>=512&&!this[Wde]&&!this[zpr];){let t=this[Dg];this[Dg]=void 0,this[jpr](t)}this[ZEt]=!1}(!this[Dg]||this[Gde])&&this[Mpr]()}[jpr](e){let t=0,r=e.length;for(;t+512<=r&&!this[Wde]&&!this[zpr];)switch(this[F4]){case"begin":case"header":this[Tia](e,t),t+=512;break;case"ignore":case"body":t+=this[$bi](e,t);break;case"meta":t+=this[Pia](e,t);break;default:throw new Error("invalid state: "+this[F4])}t<r&&(this[Dg]?this[Dg]=Buffer.concat([e.subarray(t),this[Dg]]):this[Dg]=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[Wde]||(this[Cv]?(e&&this[Cv].write(e),this[Cv].end()):(this[Gde]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[Mpr]())),this}},avt=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)},sQp=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},foa=(e,t)=>{let r=new Map(t.map(o=>[avt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,afr.parse)(o).root||".",u;if(o===a)u=!1;else{let c=r.get(o);c!==void 0?u=c:u=i((0,afr.dirname)(o),a)}return r.set(o,u),u};e.filter=n?(o,s)=>n(o,s)&&i(avt(o)):o=>i(avt(o))},aQp=e=>{let t=new dvt(e),r=e.file,n;try{n=SOe.default.openSync(r,"r");let i=SOe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=SOe.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 u=SOe.default.readSync(n,a,0,o,s);if(u===0)break;s+=u,t.write(a.subarray(0,u))}t.end()}}finally{if(typeof n=="number")try{SOe.default.closeSync(n)}catch{}}},uQp=(e,t)=>{let r=new dvt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),SOe.default.stat(i,(a,u)=>{if(a)s(a);else{let c=new S0i(i,{readSize:n,size:u.size});c.on("error",s),c.pipe(r)}})})},lfr=gvt(aQp,uQp,e=>new dvt(e),e=>new dvt(e),(e,t)=>{t?.length&&foa(e,t),e.noResume||sQp(e)}),doa=(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:cQp,parse:Ria}=moa.win32,D0i=e=>{let t="",r=Ria(e);for(;cQp(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=Ria(e)}return[t,e]},pfr=["|","<",">","?",":"],R0i=pfr.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),lQp=new Map(pfr.map((e,t)=>[e,R0i[t]])),pQp=new Map(R0i.map((e,t)=>[e,pfr[t]])),Fia=e=>pfr.reduce((t,r)=>t.split(r).join(lQp.get(r)),e),fQp=e=>R0i.reduce((t,r)=>t.split(r).join(pQp.get(r)),e),hoa=(e,t)=>t?(e=Zl(e).replace(/^\.(\/|$)/,""),avt(t)+"/"+e):Zl(e),dQp=16*1024*1024,kia=Symbol("process"),Qia=Symbol("file"),Nia=Symbol("directory"),c0i=Symbol("symlink"),jia=Symbol("hardlink"),evt=Symbol("header"),$pr=Symbol("read"),l0i=Symbol("lstat"),Hpr=Symbol("onlstat"),p0i=Symbol("onread"),f0i=Symbol("onreadlink"),d0i=Symbol("openfile"),m0i=Symbol("onopenfile"),Jde=Symbol("close"),nfr=Symbol("mode"),h0i=Symbol("awaitDrain"),Kbi=Symbol("ondrain"),BH=Symbol("prefix"),goa=class extends TOe{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=O0i(t);super(),this.path=Zl(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||dQp,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Zl(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Zl(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]=D0i(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=fQp(this.path.replace(/\\/g,"/")),e=e.replace(/\\/g,"/")),this.absolute=Zl(r.absolute||u0i.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[Hpr](i):this[l0i]()}warn(e,t,r={}){return cfr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[l0i](){O6.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Hpr](t)})}[Hpr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=gQp(e),this.emit("stat",e),this[kia]()}[kia](){switch(this.type){case"File":return this[Qia]();case"Directory":return this[Nia]();case"SymbolicLink":return this[c0i]();default:return this.end()}}[nfr](e){return doa(e,this.type==="Directory",this.portable)}[BH](e){return hoa(e,this.prefix)}[evt](){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 POe({path:this[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](this.linkpath):this.linkpath,mode:this[nfr](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 rfr({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[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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)}[Nia](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[evt](),this.end()}[c0i](){O6.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[f0i](t)})}[f0i](e){this.linkpath=Zl(e),this[evt](),this.end()}[jia](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Zl(u0i.default.relative(this.cwd,e)),this.stat.size=0,this[evt](),this.end()}[Qia](){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[jia](t);this.linkCache.set(e,this.absolute)}if(this[evt](),this.stat.size===0)return this.end();this[d0i]()}[d0i](){O6.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[m0i](t)})}[m0i](e){if(this.fd=e,this.#e)return this[Jde]();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[$pr]()}[$pr](){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");O6.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[Jde](()=>this.emit("error",o));this[p0i](s)})}[Jde](e=()=>{}){this.fd!==void 0&&O6.default.close(this.fd,e)}[p0i](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[Jde](()=>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[Jde](()=>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[Kbi]():this[h0i](()=>this[Kbi]())}[h0i](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)}[Kbi](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Jde](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[$pr]()}},mQp=class extends goa{sync=!0;[l0i](){this[Hpr](O6.default.lstatSync(this.absolute))}[c0i](){this[f0i](O6.default.readlinkSync(this.absolute))}[d0i](){this[m0i](O6.default.openSync(this.absolute,"r"))}[$pr](){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=O6.default.readSync(t,r,n,i,o);this[p0i](s),e=!1}finally{if(e)try{this[Jde](()=>{})}catch{}}}[h0i](e){e()}[Jde](e=()=>{}){this.fd!==void 0&&O6.default.closeSync(this.fd),e()}},hQp=class extends TOe{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 cfr(this,e,t,r)}constructor(e,t={}){let r=O0i(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=Zl(e.path),this.mode=e.mode!==void 0?this[nfr](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?Zl(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=D0i(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 POe({path:this[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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 rfr({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[BH](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[BH](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)}[BH](e){return hoa(e,this.prefix)}[nfr](e){return doa(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}},gQp=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",AQp=class H6e{tail;head;length=0;static create(t=[]){return new H6e(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++)bQp(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)EQp(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 H6e;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 H6e;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 H6e;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 H6e;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=yQp(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};function yQp(e,t,r){let n=t,i=t?t.next:e.head,o=new F0i(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function bQp(e,t){e.tail=new F0i(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function EQp(e,t){e.head=new F0i(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var F0i=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}},Mia=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Lia=Buffer.alloc(1024),Kpr=Symbol("onStat"),tvt=Symbol("ended"),S6=Symbol("queue"),COe=Symbol("current"),xOe=Symbol("process"),rvt=Symbol("processing"),Jbi=Symbol("processJob"),B6=Symbol("jobs"),Ybi=Symbol("jobDone"),Jpr=Symbol("addFSEntry"),Uia=Symbol("addTarEntry"),A0i=Symbol("stat"),y0i=Symbol("readdir"),Ypr=Symbol("onreaddir"),Xpr=Symbol("pipe"),zia=Symbol("entry"),Xbi=Symbol("entryOpt"),Zpr=Symbol("writeEntryClass"),Aoa=Symbol("write"),Zbi=Symbol("ondrain"),ffr=class extends TOe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Zpr];onWriteEntry;[S6];[B6]=0;[rvt]=!1;[tvt]=!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=Zl(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[Zpr]=goa,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 P2p(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new D2p(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new F2p(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[Zbi]()),this.on("resume",()=>t.resume())}else this.on("drain",this[Zbi]);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[S6]=new AQp,this[B6]=0,this.jobs=Number(e.jobs)||4,this[rvt]=!1,this[tvt]=!1}[Aoa](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[tvt]=!0,this[xOe](),r&&r(),this}write(e){if(this[tvt])throw new Error("write after end");return e instanceof poa?this[Uia](e):this[Jpr](e),this.flowing}[Uia](e){let t=Zl(g0i.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new Mia(e.path,t);r.entry=new hQp(e,this[Xbi](r)),r.entry.on("end",()=>this[Ybi](r)),this[B6]+=1,this[S6].push(r)}this[xOe]()}[Jpr](e){let t=Zl(g0i.default.resolve(this.cwd,e));this[S6].push(new Mia(e,t)),this[xOe]()}[A0i](e){e.pending=!0,this[B6]+=1;let t=this.follow?"stat":"lstat";mvt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[B6]-=1,r?this.emit("error",r):this[Kpr](e,n)})}[Kpr](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)?t.isFile()&&t.nlink>1&&e===this[COe]&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync&&this[Jbi](e):e.ignore=!0,this[xOe]()}[y0i](e){e.pending=!0,this[B6]+=1,mvt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[B6]-=1,t)return this.emit("error",t);this[Ypr](e,r)})}[Ypr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[xOe]()}[xOe](){if(!this[rvt]){this[rvt]=!0;for(let e=this[S6].head;e&&this[B6]<this.jobs;e=e.next)if(this[Jbi](e.value),e.value.ignore){let t=e.next;this[S6].removeNode(e),e.next=t}this[rvt]=!1,this[tvt]&&!this[S6].length&&this[B6]===0&&(this.zip?this.zip.end(Lia):(super.write(Lia),super.end()))}}get[COe](){return this[S6]&&this[S6].head&&this[S6].head.value}[Ybi](e){this[S6].shift(),this[B6]-=1,this[xOe]()}[Jbi](e){if(!e.pending){if(e.entry){e===this[COe]&&!e.piped&&this[Xpr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[Kpr](e,t):this[A0i](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[Ypr](e,t):this[y0i](e),!e.readdir)return}if(e.entry=this[zia](e),!e.entry){e.ignore=!0;return}e===this[COe]&&!e.piped&&this[Xpr](e)}}}[Xbi](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}}[zia](e){this[B6]+=1;try{return new this[Zpr](e.path,this[Xbi](e)).on("end",()=>this[Ybi](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[Zbi](){this[COe]&&this[COe].entry&&this[COe].entry.resume()}[Xpr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[Jpr](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={}){cfr(this,e,t,r)}},k0i=class extends ffr{sync=!0;constructor(e){super(e),this[Zpr]=mQp}pause(){}resume(){}[A0i](e){let t=this.follow?"statSync":"lstatSync";this[Kpr](e,mvt.default[t](e.absolute))}[y0i](e){this[Ypr](e,mvt.default.readdirSync(e.absolute))}[Xpr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[Jpr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[Aoa](n)})}},vQp=(e,t)=>{let r=new k0i(e),n=new toa(e.file,{mode:e.mode||438});r.pipe(n),yoa(r,t)},IQp=(e,t)=>{let r=new ffr(e),n=new sfr(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 boa(r,t),i},yoa=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?lfr({file:B0i.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},boa=async(e,t)=>{for(let r=0;r<t.length;r++){let n=String(t[r]);n.charAt(0)==="@"?await lfr({file:B0i.default.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{e.add(i)}}):e.add(n)}e.end()},wQp=(e,t)=>{let r=new k0i(e);return yoa(r,t),r},CQp=(e,t)=>{let r=new ffr(e);return boa(r,t),r},Eoa=gvt(vQp,IQp,wQp,CQp,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),xQp=process.env.__FAKE_PLATFORM__||process.platform,_Qp=xQp==="win32",{O_CREAT:SQp,O_TRUNC:BQp,O_WRONLY:OQp}=j0i.default.constants,Ioa=Number(process.env.__FAKE_FS_O_FILENAME__)||j0i.default.constants.UV_FS_O_FILEMAP||0,PQp=_Qp&&!!Ioa,TQp=512*1024,DQp=Ioa|BQp|SQp|OQp,woa=PQp?e=>e<TQp?DQp:"w":()=>"w",b0i=(e,t,r)=>{try{return Avt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},ifr=(e,t,r,n)=>{Avt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},RQp=(e,t,r,n,i)=>{if(t.isDirectory())Coa(J6e.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=J6e.default.resolve(e,t.name);ifr(s,r,n,i)});else{let o=J6e.default.resolve(e,t.name);ifr(o,r,n,i)}},Coa=(e,t,r,n)=>{Avt.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 ifr(e,t,r,n);let s=o.length,a=null,u=c=>{if(!a){if(c)return n(a=c);if(--s===0)return ifr(e,t,r,n)}};for(let c of o)RQp(e,c,t,r,u)})},FQp=(e,t,r,n)=>{t.isDirectory()&&xoa(J6e.default.resolve(e,t.name),r,n),b0i(J6e.default.resolve(e,t.name),r,n)},xoa=(e,t,r)=>{let n;try{n=Avt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return b0i(e,t,r);throw o}for(let i of n)FQp(e,i,t,r);return b0i(e,t,r)},Soa=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"}},dfr=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"}},kQp=(e,t)=>{rF.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new Soa(e,r?.code||"ENOTDIR")),t(r)})},QQp=(e,t,r)=>{e=Zl(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,u=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),c=t.preserve,l=t.unlink,p=Zl(t.cwd),d=(m,h)=>{m?r(m):h&&u?Coa(h,s,a,g=>d(g)):o?rF.default.chmod(e,i,r):r()};if(e===p)return kQp(e,d);if(c)return _oa.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Zl(hvt.default.relative(p,e)).split("/");E0i(p,f,i,l,p,void 0,d)},E0i=(e,t,r,n,i,o,s)=>{if(!t.length)return s(null,o);let a=t.shift(),u=Zl(hvt.default.resolve(e+"/"+a));rF.default.mkdir(u,r,Boa(u,t,r,n,i,o,s))},Boa=(e,t,r,n,i,o,s)=>a=>{a?rF.default.lstat(e,(u,c)=>{if(u)u.path=u.path&&Zl(u.path),s(u);else if(c.isDirectory())E0i(e,t,r,n,i,o,s);else if(n)rF.default.unlink(e,l=>{if(l)return s(l);rF.default.mkdir(e,r,Boa(e,t,r,n,i,o,s))});else{if(c.isSymbolicLink())return s(new dfr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,E0i(e,t,r,n,i,o,s))},NQp=e=>{let t=!1,r;try{t=rF.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new Soa(e,r??"ENOTDIR")}},jQp=(e,t)=>{e=Zl(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),u=t.preserve,c=t.unlink,l=Zl(t.cwd),p=m=>{m&&a&&xoa(m,o,s),i&&rF.default.chmodSync(e,n)};if(e===l)return NQp(l),p();if(u)return p(rF.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Zl(hvt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),h=l;m&&(h+="/"+m);m=d.shift()){h=Zl(hvt.default.resolve(h));try{rF.default.mkdirSync(h,n),f=f||h}catch{let g=rF.default.lstatSync(h);if(g.isDirectory())continue;if(c){rF.default.unlinkSync(h),rF.default.mkdirSync(h,n),f=f||h;continue}else if(g.isSymbolicLink())return new dfr(h,h+"/"+d.join("/"))}}return p(f)},e0i=Object.create(null),Via=1e4,V6e=new Set,MQp=e=>{V6e.has(e)?V6e.delete(e):e0i[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),V6e.add(e);let t=e0i[e],r=V6e.size-Via;if(r>Via/10){for(let n of V6e)if(V6e.delete(n),delete e0i[n],--r<=0)break}return t},LQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,UQp=LQp==="win32",zQp=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t[t.length-1];return n!==void 0&&(r=(0,M0i.join)(n,r)),t.push(r||"/"),t},[]),VQp=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=UQp?["win32 parallelization disabled"]:e.map(n=>avt((0,M0i.join)(MQp(n))));let r=new Set(e.map(n=>zQp(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[i.length-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 u of a)i.add(u)}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 u=s[0];typeof u=="function"&&i.add(u)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},qQp=()=>process.umask(),qia=Symbol("onEntry"),v0i=Symbol("checkFs"),Gia=Symbol("checkFs2"),I0i=Symbol("isReusable"),k4=Symbol("makeFs"),w0i=Symbol("file"),C0i=Symbol("directory"),efr=Symbol("link"),Wia=Symbol("symlink"),$ia=Symbol("hardlink"),ovt=Symbol("ensureNoSymlink"),Hia=Symbol("unsupported"),Kia=Symbol("checkPath"),t0i=Symbol("stripAbsolutePath"),Xde=Symbol("mkdir"),wC=Symbol("onError"),Vpr=Symbol("pending"),Jia=Symbol("pend"),q6e=Symbol("unpend"),r0i=Symbol("ended"),n0i=Symbol("maybeClose"),x0i=Symbol("skip"),uvt=Symbol("doChown"),cvt=Symbol("uid"),lvt=Symbol("gid"),pvt=Symbol("checkedCwd"),GQp=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,fvt=GQp==="win32",WQp=1024,$Qp=(e,t)=>{if(!fvt)return Xp.default.unlink(e,t);let r=e+".DELETE."+(0,N0i.randomBytes)(16).toString("hex");Xp.default.rename(e,r,n=>{if(n)return t(n);Xp.default.unlink(r,t)})},HQp=e=>{if(!fvt)return Xp.default.unlinkSync(e);let t=e+".DELETE."+(0,N0i.randomBytes)(16).toString("hex");Xp.default.renameSync(e,t),Xp.default.unlinkSync(t)},Yia=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,L0i=class extends dvt{[r0i]=!1;[pvt]=!1;[Vpr]=0;reservations=new VQp;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[r0i]=!0,this[n0i]()},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;e.preserveOwner===void 0&&typeof e.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!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:WQp,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||fvt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Zl(xv.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:qQp():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[qia](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[n0i](){this[r0i]&&this[Vpr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[t0i](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=D0i(r),s=o.replace(/\\/g,"/").split("/");if(s.includes("..")||fvt&&/^[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=xv.default.posix.dirname(e.path),u=xv.default.posix.normalize(xv.default.posix.join(a,s.join("/")));if(u.startsWith("../")||u==="..")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}[Kia](e){let t=Zl(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Zl(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[t0i](e,"path")||!this[t0i](e,"linkpath"))return!1;if(xv.default.isAbsolute(e.path)?e.absolute=Zl(xv.default.resolve(e.path)):e.absolute=Zl(xv.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:Zl(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}=xv.default.win32.parse(String(e.absolute));e.absolute=n+Fia(String(e.absolute).slice(n.length));let{root:i}=xv.default.win32.parse(e.path);e.path=i+Fia(e.path.slice(i.length))}return!0}[qia](e){if(!this[Kia](e))return e.resume();switch(voa.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[v0i](e);default:return this[Hia](e)}}[wC](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[q6e](),t.resume())}[Xde](e,t,r){QQp(Zl(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)}[uvt](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}[cvt](e){return Yia(this.uid,e.uid,this.processUid)}[lvt](e){return Yia(this.gid,e.gid,this.processGid)}[w0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new sfr(String(e.absolute),{flags:woa(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Xp.default.close(n.fd,()=>{}),n.write=()=>!0,this[wC](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Xp.default.close(n.fd,()=>{}),this[wC](a,e),t();return}--i===0&&n.fd!==void 0&&Xp.default.close(n.fd,u=>{u?this[wC](u,e):this[q6e](),t()})};n.on("finish",()=>{let a=String(e.absolute),u=n.fd;if(typeof u=="number"&&e.mtime&&!this.noMtime){i++;let c=e.atime||new Date,l=e.mtime;Xp.default.futimes(u,c,l,p=>p?Xp.default.utimes(a,c,l,d=>o(d&&p)):o())}if(typeof u=="number"&&this[uvt](e)){i++;let c=this[cvt](e),l=this[lvt](e);typeof c=="number"&&typeof l=="number"&&Xp.default.fchown(u,c,l,p=>p?Xp.default.chown(a,c,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[wC](a,e),t()}),e.pipe(s)),s.pipe(n)}[C0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[Xde](String(e.absolute),r,n=>{if(n){this[wC](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[q6e](),e.resume())};e.mtime&&!this.noMtime&&(i++,Xp.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[uvt](e)&&(i++,Xp.default.chown(String(e.absolute),Number(this[cvt](e)),Number(this[lvt](e)),o)),o()})}[Hia](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Wia](e,t){let r=Zl(xv.default.relative(this.cwd,xv.default.resolve(xv.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[ovt](e,this.cwd,r,()=>this[efr](e,String(e.linkpath),"symlink",t),n=>{this[wC](n,e),t()})}[$ia](e,t){let r=Zl(xv.default.resolve(this.cwd,String(e.linkpath))),n=Zl(String(e.linkpath)).split("/");this[ovt](e,this.cwd,n,()=>this[efr](e,r,"link",t),i=>{this[wC](i,e),t()})}[ovt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=xv.default.resolve(t,o);Xp.default.lstat(s,(a,u)=>{if(a)return n();if(u?.isSymbolicLink())return i(new dfr(s,xv.default.resolve(s,r.join("/"))));this[ovt](e,s,r,n,i)})}[Jia](){this[Vpr]++}[q6e](){this[Vpr]--,this[n0i]()}[x0i](e){this[q6e](),e.resume()}[I0i](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!fvt}[v0i](e){this[Jia]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Gia](e,r))}[Gia](e,t){let r=s=>{t(s)},n=()=>{this[Xde](this.cwd,this.dmode,s=>{if(s){this[wC](s,e),r();return}this[pvt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Zl(xv.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[Xde](s,this.dmode,a=>{if(a){this[wC](a,e),r();return}o()})}o()},o=()=>{Xp.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[x0i](e),r();return}if(s||this[I0i](e,a))return this[k4](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let u=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,c=l=>this[k4](l??null,e,r);return u?Xp.default.chmod(String(e.absolute),Number(e.mode),c):c()}if(e.absolute!==this.cwd)return Xp.default.rmdir(String(e.absolute),u=>this[k4](u??null,e,r))}if(e.absolute===this.cwd)return this[k4](null,e,r);$Qp(String(e.absolute),u=>this[k4](u??null,e,r))})};this[pvt]?i():n()}[k4](e,t,r){if(e){this[wC](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[w0i](t,r);case"Link":return this[$ia](t,r);case"SymbolicLink":return this[Wia](t,r);case"Directory":case"GNUDumpDir":return this[C0i](t,r)}}[efr](e,t,r,n){Xp.default[r](t,String(e.absolute),i=>{i?this[wC](i,e):(this[q6e](),e.resume()),n()})}},nvt=e=>{try{return[null,e()]}catch(t){return[t,null]}},Ooa=class extends L0i{sync=!0;[k4](e,t){return super[k4](e,t,()=>{})}[v0i](e){if(!this[pvt]){let i=this[Xde](this.cwd,this.dmode);if(i)return this[wC](i,e);this[pvt]=!0}if(e.absolute!==this.cwd){let i=Zl(xv.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[Xde](i,this.dmode);if(o)return this[wC](o,e)}}let[t,r]=nvt(()=>Xp.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[x0i](e);if(t||this[I0i](e,r))return this[k4](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?nvt(()=>{Xp.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[k4](s,e)}let[i]=nvt(()=>Xp.default.rmdirSync(String(e.absolute)));this[k4](i,e)}let[n]=e.absolute===this.cwd?[]:nvt(()=>HQp(String(e.absolute)));this[k4](n,e)}[w0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Xp.default.closeSync(i)}catch(u){a=u}(s||a)&&this[wC](s||a,e),t()},i;try{i=Xp.default.openSync(String(e.absolute),woa(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[wC](s,e)),e.pipe(o)),o.on("data",s=>{try{Xp.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,u=e.mtime;try{Xp.default.futimesSync(i,a,u)}catch(c){try{Xp.default.utimesSync(String(e.absolute),a,u)}catch{s=c}}}if(this[uvt](e)){let a=this[cvt](e),u=this[lvt](e);try{Xp.default.fchownSync(i,Number(a),Number(u))}catch(c){try{Xp.default.chownSync(String(e.absolute),Number(a),Number(u))}catch{s=s||c}}}n(s)})}[C0i](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[Xde](String(e.absolute),r);if(n){this[wC](n,e),t();return}if(e.mtime&&!this.noMtime)try{Xp.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[uvt](e))try{Xp.default.chownSync(String(e.absolute),Number(this[cvt](e)),Number(this[lvt](e)))}catch{}t(),e.resume()}[Xde](e,t){try{return jQp(Zl(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}}[ovt](e,t,r,n,i){if(this.preservePaths||!r.length)return n();let o=t;for(let s of r){o=xv.default.resolve(o,s);let[a,u]=nvt(()=>Xp.default.lstatSync(o));if(a)return n();if(u.isSymbolicLink())return i(new dfr(o,xv.default.resolve(t,r.join("/"))))}n()}[efr](e,t,r,n){let i=`${r}Sync`;try{Xp.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[wC](o,e)}}},KQp=e=>{let t=new Ooa(e),r=e.file,n=Q0i.default.statSync(r),i=e.maxReadSize||16*1024*1024;new b2p(r,{readSize:i,size:n.size}).pipe(t)},JQp=(e,t)=>{let r=new L0i(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),Q0i.default.stat(i,(a,u)=>{if(a)s(a);else{let c=new S0i(i,{readSize:n,size:u.size});c.on("error",s),c.pipe(r)}})})},Poa=gvt(KQp,JQp,e=>new Ooa(e),e=>new L0i(e),(e,t)=>{t?.length&&foa(e,t)}),YQp=(e,t)=>{let r=new k0i(e),n=!0,i,o;try{try{i=tF.default.openSync(e.file,"r+")}catch(u){if(u?.code==="ENOENT")i=tF.default.openSync(e.file,"w+");else throw u}let s=tF.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=tF.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let u=new POe(a);if(!u.cksumValid)break;let c=512*Math.ceil((u.size||0)/512);if(o+c+512>s.size)break;o+=c,e.mtimeCache&&u.mtime&&e.mtimeCache.set(String(u.path),u.mtime)}n=!1,XQp(e,r,o,i,t)}finally{if(n)try{tF.default.closeSync(i)}catch{}}},XQp=(e,t,r,n,i)=>{let o=new toa(e.file,{fd:n,start:r});t.pipe(o),eNp(t,i)},ZQp=(e,t)=>{t=Array.from(t);let r=new ffr(e),n=(i,o,s)=>{let a=(d,f)=>{d?tF.default.close(i,m=>s(d)):s(null,f)},u=0;if(o===0)return a(null,0);let c=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||typeof f>"u")return a(d);if(c+=f,c<512&&f)return tF.default.read(i,l,c,l.length-c,u+c,p);if(u===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,u);let m=new POe(l);if(!m.cksumValid)return a(null,u);let h=512*Math.ceil((m.size??0)/512);if(u+h+512>o||(u+=h+512,u>=o))return a(null,u);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),c=0,tF.default.read(i,l,0,512,u,p)};tF.default.read(i,l,0,512,u,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(u,c)=>{if(u&&u.code==="ENOENT"&&s==="r+")return s="w+",tF.default.open(e.file,s,a);if(u||!c)return o(u);tF.default.fstat(c,(l,p)=>{if(l)return tF.default.close(c,()=>o(l));n(c,p.size,(d,f)=>{if(d)return o(d);let m=new sfr(e.file,{fd:c,start:f});r.pipe(m),m.on("error",o),m.on("close",i),tNp(r,t)})})};tF.default.open(e.file,s,a)})},eNp=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?lfr({file:U0i.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},tNp=async(e,t)=>{for(let r=0;r<t.length;r++){let n=String(t[r]);n.charAt(0)==="@"?await lfr({file:U0i.default.resolve(String(e.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>e.add(i)}):e.add(n)}e.end()},ivt=gvt(YQp,ZQp,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!x2p(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")}),Tiy=gvt(ivt.syncFile,ivt.asyncFile,ivt.syncNoFile,ivt.asyncNoFile,(e,t=[])=>{ivt.validate?.(e,t),rNp(e)}),rNp=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 Qoa=_e(Aw(),1);var nNp=Eoe();async function Noa({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:n,cliVersion:i,settings:o,loadAPIWorkspace:s}){let a,u={type:Uc.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},c=t.dependencies[e];return c==null?u={type:Uc.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${lNp(c)}`},async l=>{switch(c.type){case"version":a=await uNp({context:l,dependency:c,cliVersion:i,settings:o,loadAPIWorkspace:s});return;case"local":a=await aNp({context:l,dependency:c,cliVersion:i,settings:o,loadAPIWorkspace:s});return;default:xe(c)}}),a!=null?{didSucceed:!0,definition:a}:{didSucceed:!1,failure:u}}var joa="dependencies";var iNp="metadata.json",oNp=".fern";function sNp(e){return We(Ut.of((0,Roa.homedir)()),Se.of(oNp),Se.of(joa),Se.of(e.organization),Se.of(e.apiName),Se.of(e.version))}async function aNp({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){if(i==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let o=await i({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!o.didSucceed){t.failWithoutThrowing("Failed to load api definition",o.failures);return}t.logger.info("Modifying source filepath ...");let s=await o.workspace.getDefinition({context:t,relativePathToDependency:Se.of(e.path)},n);return t.logger.info("Loaded..."),s}async function uNp({dependency:e,context:t,cliVersion:r,settings:n,loadAPIWorkspace:i}){let o=sNp(e),s=We(o,Se.of(joa)),a=We(o,Se.of(iNp)),u;if(!await Xt(s)||!await Xt(a)){t.logger.info("Downloading manifest...");let p=await nNp.definitionRegistry.get(z0i.FernFiddle.OrganizationId(e.organization),z0i.FernFiddle.ApiId(e.apiName),e.version);if(!p.ok){p.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:h=>{t.failWithoutThrowing("Failed to download API manifest",h)}});return}let d=p.body.yamlSchemaVersion!=null?parseInt(p.body.yamlSchemaVersion):void 0,f=cOe(r),m=cOe(p.body.cliVersion);if(d!=null){if(d>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${p.body.cliVersion}`);return}else if(d<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(f.major!==m.major||f.minor!==m.minor){t.failWithoutThrowing(`CLI version is ${p.body.cliVersion}. Expected ${f.major}.${f.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+p.body.definitionS3DownloadUrl),await(0,X6e.mkdir)(s,{recursive:!0});try{await cNp({s3PreSignedReadUrl:p.body.definitionS3DownloadUrl,absolutePathToLocalOutput:s})}catch(h){t.failWithoutThrowing("Failed to download API",h);return}u=p.body,await(0,X6e.writeFile)(a,JSON.stringify(u))}else u=JSON.parse((await(0,X6e.readFile)(a)).toString());if(t.logger.info("Parsing..."),i==null){t.failWithoutThrowing("Failed to load API");return}let c=await i({absolutePathToWorkspace:s,context:t,cliVersion:u.cliVersion,workspaceName:void 0});if(!c.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",c.failures);return}if(c.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await c.workspace.getDefinition({context:t},n)}async function cNp({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await Xb.get(e,{responseType:"stream"}),n=await Qoa.default.dir(),i=Foa.default.join(n.path,"api.tgz");await(0,koa.pipeline)(r.data,(0,Doa.createWriteStream)(i)),await Poa({file:i,cwd:t})}function lNp(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:xe(e)}}async function Moa({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:n,settings:i,loadAPIWorkspace:o}){let s={},a={},u={};return await Promise.all(Wy(t.packageMarkers).map(async([c,l])=>{if(l.contents.export==null)s[c]=l;else{let{export:p,...d}=l.contents;if(Wd(d)>0)u[c]={type:Uc.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:c};else{let f=vn(c);if(RO(t.namedDefinitionFiles).some(h=>h!==c&&h.startsWith(f)))u[c]={type:Uc.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:f};else{let h=await Noa({dependencyName:typeof l.contents.export=="string"?l.contents.export:l.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:n,settings:i,loadAPIWorkspace:o});h.didSucceed?a[vn(c)]={definition:h.definition,url:typeof l.contents.export=="object"?l.contents.export.url:void 0}:u[c]=h.failure}}}})),Wd(u)>0?{didSucceed:!1,failures:u}:{didSucceed:!0,packageMarkers:s,importedDefinitions:a}}Qt();Vt();var Loa=_e(require("path"),1);var V0i={};Y(V0i,{additionalProperties:()=>mNp,default:()=>gNp,definitions:()=>hNp,properties:()=>fNp,required:()=>dNp,type:()=>pNp});var pNp="object",fNp={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},dNp=["name"],mNp=!1,hNp={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}},"url-templates":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"default-urls":{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}}},{type:"null"}]}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},gNp={type:pNp,properties:fNp,required:dNp,additionalProperties:mNp,definitions:hNp};var q0i={};Y(q0i,{additionalProperties:()=>bNp,default:()=>vNp,definitions:()=>ENp,properties:()=>yNp,type:()=>ANp});var ANp="object",yNp={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},bNp=!1,ENp={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},vNp={type:ANp,properties:yNp,additionalProperties:bNp,definitions:ENp};var G0i={};Y(G0i,{additionalProperties:()=>CNp,default:()=>_Np,definitions:()=>xNp,properties:()=>wNp,type:()=>INp});var INp="object",wNp={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},"webhook-signature":{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},CNp=!1,xNp={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}},"forward-compatible":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminatorContext":{type:"string",enum:["data","protocol"]},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},context:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminatorContext"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.UriPaginationSchema":{type:"object",properties:{next_uri:{type:"string"},results:{type:"string"}},required:["next_uri","results"],additionalProperties:!1},"pagination.PathPaginationSchema":{type:"object",properties:{next_path:{type:"string"},results:{type:"string"}},required:["next_path","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"},{$ref:"#/definitions/pagination.UriPaginationSchema"},{$ref:"#/definitions/pagination.PathPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"webhooks.WebhookSignatureAlgorithmSchema":{type:"string",enum:["sha256","sha1","sha384","sha512"]},"webhooks.WebhookSignatureEncodingSchema":{type:"string",enum:["base64","hex"]},"webhooks.WebhookPayloadComponentSchema":{type:"string",enum:["body","timestamp","notification-url","message-id"]},"webhooks.WebhookPayloadFormatSchema":{type:"object",properties:{components:{type:"array",items:{$ref:"#/definitions/webhooks.WebhookPayloadComponentSchema"}},delimiter:{oneOf:[{type:"string"},{type:"null"}]}},required:["components"],additionalProperties:!1},"webhooks.WebhookTimestampFormatSchema":{type:"string",enum:["unix-seconds","unix-millis","iso8601"]},"webhooks.WebhookTimestampSchema":{type:"object",properties:{header:{type:"string"},format:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampFormatSchema"},{type:"null"}]},tolerance:{oneOf:[{type:"integer"},{type:"null"}]}},required:["header"],additionalProperties:!1},"webhooks.AsymmetricAlgorithmSchema":{type:"string",enum:["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]},"webhooks.WebhookSignatureSchema":{type:"object",properties:{type:{type:"string",enum:["hmac","asymmetric"]}},oneOf:[{properties:{type:{const:"hmac"},header:{type:"string"},algorithm:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureAlgorithmSchema"},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"payload-format":{oneOf:[{$ref:"#/definitions/webhooks.WebhookPayloadFormatSchema"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header"]},{properties:{type:{const:"asymmetric"},header:{type:"string"},"asymmetric-algorithm":{$ref:"#/definitions/webhooks.AsymmetricAlgorithmSchema"},encoding:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureEncodingSchema"},{type:"null"}]},"signature-prefix":{oneOf:[{type:"string"},{type:"null"}]},"jwks-url":{oneOf:[{type:"string"},{type:"null"}]},"key-id-header":{oneOf:[{type:"string"},{type:"null"}]},timestamp:{oneOf:[{$ref:"#/definitions/webhooks.WebhookTimestampSchema"},{type:"null"}]}},required:["type","header","asymmetric-algorithm"]}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},signature:{oneOf:[{$ref:"#/definitions/webhooks.WebhookSignatureSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},"connect-method-name":{oneOf:[{type:"string"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},_Np={type:INp,properties:wNp,additionalProperties:CNp,definitions:xNp};var W0i=new Map,$0i=new Map,H0i=new Map;function Uoa({files:e,absolutePathToDefinition:t,skipValidation:r}){let n,i={},o={},s={};for(let[a,u]of Wy(e)){let c=u.contents,l=p=>{s[a]={type:Uc.JSONSCHEMA_VALIDATION,error:p}};if(a===Lb){let p=W0i.get(u.rawContents);if(p!=null&&(p.validated||r))n={defaultUrl:p.value["default-url"],contents:p.value,rawContents:u.rawContents};else if(r){let d=$d.serialization.RootApiFileSchema.parseOrThrow(c);W0i.set(u.rawContents,{value:d,validated:!1}),n={defaultUrl:d["default-url"],contents:d,rawContents:u.rawContents}}else{let d=x5(c,V0i);if(d.success){let f=$d.serialization.RootApiFileSchema.parseOrThrow(c);W0i.set(u.rawContents,{value:f,validated:!0}),n={defaultUrl:f["default-url"],contents:f,rawContents:u.rawContents}}else l(d)}}else if(Loa.default.basename(a)===Bp){let p=H0i.get(u.rawContents);if(p!=null&&(p.validated||r))o[a]={defaultUrl:typeof p.value.export=="object"?p.value.export.url:void 0,contents:p.value,rawContents:u.rawContents};else if(r){let d=$d.serialization.PackageMarkerFileSchema.parseOrThrow(c);H0i.set(u.rawContents,{value:d,validated:!1}),o[a]={defaultUrl:typeof d.export=="object"?d.export.url:void 0,contents:d,rawContents:u.rawContents}}else{let d=x5(c,G0i);if(d.success){let f=$d.serialization.PackageMarkerFileSchema.parseOrThrow(c);H0i.set(u.rawContents,{value:f,validated:!0}),o[a]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:u.rawContents}}else l(d)}}else{let p=$0i.get(u.rawContents);if(p!=null&&(p.validated||r))i[a]={defaultUrl:void 0,contents:p.value,rawContents:u.rawContents,absoluteFilePath:We(t,a)};else if(r){let d=$d.serialization.DefinitionFileSchema.parseOrThrow(c);$0i.set(u.rawContents,{value:d,validated:!1}),i[a]={defaultUrl:void 0,contents:d,rawContents:u.rawContents,absoluteFilePath:We(t,a)}}else{let d=x5(c,q0i);if(d.success){let f=$d.serialization.DefinitionFileSchema.parseOrThrow(c);$0i.set(u.rawContents,{value:f,validated:!0}),i[a]={defaultUrl:void 0,contents:f,rawContents:u.rawContents,absoluteFilePath:We(t,a)}}else l(d)}}}return n==null?{didSucceed:!1,failures:{[Se.of(Lb)]:{type:Uc.FILE_MISSING},...s}}:Object.keys(s).length>0?{didSucceed:!1,failures:s}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:n,packageMarkers:o}}var qS=class extends U5{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...n}){super(n),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){let n=t||this.context;return(await this.toFernWorkspace({context:n},r)).definition}async toFernWorkspace({context:t,skipValidation:r},n,i,o){let s=(0,zoa.default)(n??{}),a=this.fernWorkspaces[s];if(a==null){let u=t||this.context,c=We(this.absoluteFilePath,Se.of(Hh)),l=await ati({absolutePathToWorkspace:this.absoluteFilePath,context:u}),p=await ora(c,"{yml,yaml}"),d=await sra(p);if(!d.didSucceed)return Glr(d.failures,u.logger),u.failAndThrow();let f=Uoa({files:d.files,absolutePathToDefinition:c,skipValidation:r});if(!f.didSucceed)return Glr(f.failures,u.logger),u.failAndThrow();let m=await Moa({dependenciesConfiguration:l,structuralValidationResult:f,context:u,cliVersion:this.cliVersion,settings:n,loadAPIWorkspace:this.loadAPIWorkspace});if(!m.didSucceed)return Glr(m.failures,u.logger),u.failAndThrow();let h={absoluteFilePath:c,rootApiFile:f.rootApiFile,namedDefinitionFiles:f.namedDefinitionFiles,packageMarkers:m.packageMarkers,importedDefinitions:m.importedDefinitions};n?.auth!=null&&(h={...h,rootApiFile:{...h.rootApiFile,contents:{...h.rootApiFile.contents,auth:n?.auth}}}),a=new LD({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:h,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[s]=a}return a}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};Vt();var cla=require("fs/promises");var Yca=_e(Jca(),1);async function F6(e){return(await(0,Yca.convertObj)(e,{})).openapi}var nla=require("fs/promises");var ila=require("path");Qt();var Xca=require("fs/promises");async function yVe({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,Xca.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=wr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return Apt({data:t,overrides:i,allowNullKeys:n})}var Zca=require("fs/promises");var vdr=require("path");function ela(e){return e.startsWith("http://")||e.startsWith("https://")}async function j3p(e,t){let r=t.get(e);if(r!==void 0)return r;let n=await(0,Zca.readFile)(e,"utf-8"),i=wr.load(n);return t.set(e,i),i}function tla(e,t){let r=new Map;if(e==null||typeof e!="object"||Array.isArray(e))return r;let n=e;function i(s,a){if(!(s==null||typeof s!="object"||Array.isArray(s)))for(let[u,c]of Object.entries(s)){if(!M3p(c))continue;let l=c.$ref,{jsonPointer:p,absolutePath:d}=rla(l,t);r.set(`${d}#${p}`,`${a}/${u}`)}}i(n.channels,"#/channels"),i(n.operations,"#/operations");let o=n.components;if(o!=null&&typeof o=="object"&&!Array.isArray(o)){let s=o;i(s.schemas,"#/components/schemas"),i(s.messages,"#/components/messages"),i(s.parameters,"#/components/parameters")}return r}function rla(e,t){let r=e.indexOf("#"),n=r>=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"",o=(0,vdr.resolve)(t,n);return{filePath:n,jsonPointer:i,absolutePath:o}}function M3p(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e.$ref;return typeof t=="string"&&t.length>0&&!t.startsWith("#")&&!ela(t)}function L3p(e,t,r,n){if(e===r)return"#"+t;let i=`${e}#${t}`,o=n.get(i);if(o!==void 0)return o;for(let[s,a]of n){let u=s.indexOf("#"),c=s.slice(0,u),l=s.slice(u+1);if(c===e&&t.startsWith(l+"/")){let p=t.slice(l.length);return a+p}}return null}async function pIt(e,t,r,n,i=!1,o=new Set,s=new Map){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return Promise.all(e.map(l=>pIt(l,t,r,n,i,o,s)));let a=e,u=a.$ref;if(typeof u=="string"&&!u.startsWith("#")&&!ela(u)){let{jsonPointer:l,absolutePath:p}=rla(u,t),d={};for(let[v,b]of Object.entries(a))v!=="$ref"&&(d[v]=b);let f=Object.keys(d).length>0;if(i){let v=L3p(p,l,r,n);if(v!==null)return{$ref:v,...d}}let m=`${p}#${l}`;if(o.has(m))throw new Error(`Circular $ref detected: "${u}" (resolved to "${m}")`);let h=new Set(o);h.add(m);let g=await j3p(p,s);if(l!==""){let v=l.split("/").filter(I=>I!==""),b=g;for(let I of v){let w=I.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof b!="object"||b==null)throw new Error(`Cannot navigate JSON Pointer "${l}" in "${p}": expected an object but found ${typeof b} at key "${w}"`);let x=b[w];if(x===void 0)throw new Error(`Cannot navigate JSON Pointer "${l}" in "${p}": key "${w}" not found`);b=x}g=b}let A=(0,vdr.dirname)(p),E=await pIt(g,A,r,n,!0,h,s);return f&&E!=null&&typeof E=="object"&&!Array.isArray(E)?{...E,...d}:E}let c={};for(let[l,p]of Object.entries(a))c[l]=await pIt(p,t,r,n,i,o,s);return c}async function Yvi({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,nla.readFile)(t)).toString(),i=await wr.load(n),o=(0,ila.dirname)(t),s=tla(i,o),a=await pIt(i,o,t,s),u=[];r!=null&&(Array.isArray(r)?u=r:u=[r]);let c=a;for(let l of u)c=await yVe({absoluteFilePathToOverrides:l,context:e,data:c});return c}Vt();var ula=require("fs/promises");Qt();var wdr=require("fs/promises");var Idr=_e(require("path"),1),ola=_e(Aw(),1),Xvi;async function U3p(){return Xvi===void 0&&(Xvi=(await ola.default.dir({prefix:"fern-overlay-"})).path),Xvi}async function sla({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:n}){let i=await z3p(e,n);if(!V3p(i,n))return r;n.logger.debug(`Applying overlay "${i.info.title}" v${i.info.version}`);let o=wLn({data:r,overlay:i}),s=await U3p(),a=Idr.default.basename(t),u=`${Idr.default.parse(a).name}.overlaid.json`,c=Idr.default.join(s,u);return await(0,wdr.writeFile)(c,JSON.stringify(o,null,2),"utf8"),n.logger.info(`Wrote overlaid OpenAPI spec to: ${c}`),o}async function z3p(e,t){let r;try{r=await(0,wdr.readFile)(e,"utf8")}catch(n){return t.failAndThrow(`Failed to read overlay file at ${e}: ${n}`)}try{try{return JSON.parse(r)}catch{return wr.load(r,{json:!0})}}catch(n){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${n}`)}}function V3p(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let n=e.actions[r];if(!n?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(n.update===void 0&&!n.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var mIt=_e(zer(),1);Vt();var ala=_e(zer(),1),fIt=_e(require("path"),1),dIt=class extends ala.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let n=super.resolveExternalRef(t,r);if(n.startsWith("http://")||n.startsWith("https://")||l9(Ut.of(n)))return n;if(this.absolutePathToOpenAPIOverlays!=null){let i=fIt.default.resolve(fIt.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(l9(Ut.of(i)))return i}return this.absolutePathToOpenAPIOverrides!=null?fIt.default.resolve(fIt.default.dirname(this.absolutePathToOpenAPIOverrides),r):n}};async function Cdr({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:n}){return(n!=null?await(0,mIt.bundle)({...Ver,doc:{source:new mIt.Source(e,"<openapi>"),parsed:n},externalRefResolver:new dIt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,mIt.bundle)({...Ver,ref:e,externalRefResolver:new dIt({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}function q3p(e,t){if(t.includes(e))return e;for(let r of t){let n=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${n}$`).test(e))return r}}var G3p=["examples","example",bn.EXAMPLES,c_.REDOCLY_CODE_SAMPLES_CAMEL,c_.REDOCLY_CODE_SAMPLES_KEBAB];async function k6({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:n,loadAiExamples:i=!1}){let o=await Cdr({absolutePathToOpenAPI:t}),s=[];r!=null?Array.isArray(r)?s=r:s=[r]:typeof o=="object"&&o[bn.OPENAPI_OVERIDES_FILEPATH]!=null&&(s=[We(vn(t),Se.of(o[bn.OPENAPI_OVERIDES_FILEPATH]))]);let a=o;for(let c of s)a=await yVe({absoluteFilePathToOverrides:c,context:e,data:a,allowNullKeys:G3p}),a=await Cdr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:c,parsed:a});if(n!=null&&(a=await sla({absoluteFilePathToOverlay:n,absoluteFilePathToOpenAPI:t,context:e,data:a})),i){let c=We(vn(t),Se.of("ai_examples_override.yml"));try{let l=await(0,ula.readFile)(c,"utf-8"),p=wr.load(l);if(p?.paths&&a.paths){for(let[d,f]of Object.entries(p.paths))if(f&&typeof f=="object")for(let[m,h]of Object.entries(f)){let g=m.toLowerCase(),A=a.paths[d];if(!A&&a.paths){let E=q3p(d,Object.keys(a.paths));E&&(A=a.paths[E],e.logger.debug(`Matched override path "${d}" to OpenAPI path "${E}" using pattern matching`))}if(A&&typeof A=="object"){let v=A[g];if(v&&typeof v=="object"){let b=v;!b["x-fern-examples"]&&h["x-fern-examples"]&&(b["x-fern-examples"]=h["x-fern-examples"],e.logger.debug(`Added AI examples for ${m.toUpperCase()} ${d} from override file`))}}}}e.logger.debug(`Processed AI examples from ${c}`)}catch{}}return a!==o&&s.length===0||n!=null?await Cdr({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverlays:n,parsed:a}):a}var Q6=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:n=!1}){return(await Promise.all(r.map(o=>this.loadDocument({context:t,spec:o,loadAiExamples:n})))).filter(o=>o!=null)}async loadDocument({context:t,spec:r,loadAiExamples:n}){try{let i=(await(0,cla.readFile)(r.absoluteFilepath)).toString(),o=ha(this.absoluteFilePath,r.source.file);r.source.relativePathToDependency!=null&&(o=We(r.source.relativePathToDependency,o));let s=r.source.type==="protobuf"?mS.protobuf({file:o}):mS.openapi({file:o});if(i.includes("openapi")||i.includes("swagger"))try{let a=await k6({absolutePathToOpenAPI:r.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:r.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:r.absoluteFilepathToOverlays,loadAiExamples:n});if(nti(a))return{type:"openapi",value:a,source:s,namespace:r.namespace,settings:iM({options:r.settings})};if(p8(a))return(!a.schemes||a.schemes.length===0)&&(a.schemes=["https"]),{type:"openapi",value:await F6(a),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.debug(`Failed to parse OpenAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("asyncapi"))try{return{type:"asyncapi",value:await Yvi({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.error(`Failed to parse AsyncAPI document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}if(i.includes("openrpc"))try{return{type:"asyncapi",value:await Yvi({context:t,absoluteFilePath:r.absoluteFilepath,absoluteFilePathToOverrides:r.absoluteFilepathToOverrides}),source:s,namespace:r.namespace,settings:iM({options:r.settings})}}catch(a){t.logger.error(`Failed to parse OpenRPC document at ${r.absoluteFilepath}: ${a}. Skipping...`);return}t.logger.warn(`${r.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`);return}catch(i){t.logger.error(`Failed to read or process file ${r.absoluteFilepath}: ${i}. Skipping...`);return}}};var io=class e{breadcrumbs=[];context;static STRING=qt.TypeReference.primitive({v1:"STRING",v2:qt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=qt.TypeReference.container(qt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};Ci();Vt();var pla=require("fs/promises");var Zvi=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:u}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:u}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:u})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,u=>{a++,!((!u.children||u.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(u,u.path):(s.children.push({...u,path:u.path.slice(o.length+1)}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,u=n.length;this.iterFragments(o,c=>{a.has(c.position)||(u--,a.add(c.position),this._path.length===1?this.resolveNode(c,`${o}.${u}`):(s.children.push({...c,path:u.toString()}),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 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}}},lla=Zvi;var Sv;(function(e){e.WARNING="warning",e.ERROR="error"})(Sv||(Sv={}));var M4=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new eIi({logger:t,relativePathToFile:Se.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||Sv.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===Sv.ERROR?t++:(n.level===Sv.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??Sv.WARNING;if(!(n===Sv.WARNING&&!t))switch(n){case Sv.ERROR:if(this.logger.log(zn.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(zn.Debug,` - at location (${o})`)}break;case Sv.WARNING:if(this.logger.log(zn.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(zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(zn.Warn,` - resolution: ${r.resolution}`);break}}}},eIi=class{logger;relativePathToFile;map=new lla;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,pla.readFile)(this.relativePathToFile,"utf-8");wr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(zn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var kA=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=PI({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((i,o)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||o===0&&i==="components"||o===1&&i==="schemas"||t[0]==="paths"&&(o===0||o===1&&["get","post","put","delete","patch"].includes(i)||o===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=Ln(r.join("_"));return n.charAt(0).toUpperCase()+n.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:Sv.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:Sv.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 c=t.$ref.split("#"),l=c[0];if(n=c[1],!l)return{resolved:!1};s=l;let p=await fetch(l);if(!p.ok)return{resolved:!1};try{let d=await p.text();try{o=JSON.parse(d),r=o}catch{o=wr.load(d),r=o}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let u=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(c=>c.replace(/~1/g,"/"));for(let c of u){if(typeof r!="object"||r==null)return{resolved:!1};r=r[c]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let c=new Set;c.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,c,s)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let u=r,c=s.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of c){if(typeof u!="object"||u===null)return t;u=u[l]}if(u!=null){let l=await this.resolveNestedExternalReferences(u,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return qt.ObjectPropertyAccess.ReadOnly;if(i)return qt.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 kI.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}let i=new kI.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(t.deprecated===!0)return{status:JE.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 Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Na=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]}};Ci();var kI={};Y(kI,{AudienceExtension:()=>bVe,FernAvailabilityExtension:()=>xdr,FernEnumExtension:()=>EVe,FernIgnoreExtension:()=>VOe,FernOptionalExtension:()=>_dr,FernTypeExtension:()=>Pdr,FernTypeNameExtension:()=>Tdr,SdkGroupNameExtension:()=>Sdr,SdkMethodNameExtension:()=>Bdr,ServerFromOperationNameExtension:()=>Odr});var bVe=class extends Na{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 xdr=class extends Na{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 JE.InDevelopment;case"PRE_RELEASE":case"BETA":return JE.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return JE.GeneralAvailability;case"DEPRECATED":return JE.Deprecated;default:return}}};var W3p=mt.object({snake:mt.string().optional(),camel:mt.string().optional(),screamingSnake:mt.string().optional(),pascal:mt.string().optional()}),$3p=mt.object({description:mt.string().optional(),name:mt.string().optional(),casing:W3p.optional()}),fla=mt.record($3p);var EVe=class extends Na{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=fla.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 VOe=class extends Na{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 _dr=class extends Na{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 Sdr=class extends Na{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 Bdr=class extends Na{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 Odr=class extends Na{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 Pdr=class extends Na{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 Tdr=class extends Na{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var N6=class extends io{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new LBe(n),this.ir={auth:{docs:void 0,requirement:qt.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:qt.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new VOe({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 VOe({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(u=>u.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(u=>u.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(u=>u.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n};let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i));let o=this.context.exampleGenerationArgs,s=hhi({ir:i,exampleGeneration:o});if(this.context.generateV1Examples){let a=N0t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),n=this.irGraph.getFilteredChannels(),i=this.irGraph.getFilteredWebhooks();for(let o of Object.values(t.services)){let s=[];for(let a of o.endpoints)r.has(a.id)&&s.push(a);o.endpoints=s}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([o])=>n.has(o))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([o,s])=>{let a=s.filter(u=>u.id!=null&&i.has(u.id));return[o,a]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let n=r.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,serviceName:o}){let s=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),a=this.getOrCreatePackage({group:n}),u=[...s].map(p=>this.context.casingsGenerator.generateName(p)),c=u[u.length-1];a.service==null&&(a.service=o??`service_${s.map(p=>Ln(p)).join("/")}`),this.ir.services[a.service]==null&&(this.ir.services[a.service]=this.createNewService({allParts:u,finalpart:c,endpointGroupDisplayName:i})),this.ir.services[a.service]?.endpoints.push(t);let l=this.ir.services[a.service];l!=null&&(this.irGraph.addEndpoint(l,t),this.irGraph.markEndpointForAudience(l.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i}){let o=i?.join(".")??r,s=this.getOrCreatePackage({group:i});this.ir.webhookGroups[o]==null&&(this.ir.webhookGroups[o]=[]),this.ir.webhookGroups[o].push(t),s.webhooks=o;let a=this.context.createFernFilepath();this.irGraph.addWebhook(a,t),n!=null&&this.irGraph.markWebhookForAudiences(a,t,n)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=Ln(i?.join(".")),s=Ln(r),a=this.context.namespace?`${Ln(this.context.namespace)}/`:"",u=o?`channel_${a}${o}`:`channel_${a}${s}`,c=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[u]:t},u!==""?c.websocket==null&&(c.websocket=u):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,u,t),n!=null&&this.irGraph.markChannelForAudiences(l,u,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[n,i]of Object.entries(t??{}))r[n]!=null&&this.irGraph.markEnvironmentForAudiences(i,r[n])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(u=>u===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:hy(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>Ln(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 u=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=u}return n}};var qf={};Y(qf,{AbstractConverters:()=>rIi,ExampleConverter:()=>tE,SchemaConverters:()=>tIi,ServersConverter:()=>BQ});var rIi={};Y(rIi,{AbstractMediaTypeObjectConverter:()=>Fdr,AbstractParameterConverter:()=>kdr});Ci();Qt();var H3p=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function K3p(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 dla(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var tE=class e extends io{MAX_DEPTH=12;EXAMPLE_STRING=Ai.STRING;EXAMPLE_NUMBER=Ai.DOUBLE;EXAMPLE_BOOLEAN=Ai.BOOLEAN;EXAMPLE_INTEGER=Ai.INT;EXAMPLE_DATE=Ai.DATE;EXAMPLE_DATE_TIME=Ai.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:u=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=u}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let u;return s!=null?typeof s=="boolean"?u=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:u=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(u=i),a!==void 0&&u!==void 0?(t<a||t>u)&&(t=a+(u-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):u!==void 0&&t>u&&(t=u-Math.abs(u*.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(u=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:u,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(u=>u?.isValid??!1)&&!r,a=!r&&o.some(u=>u.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(u=>u.validExample),errors:s?[]:o.flatMap(u=>u.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=Object.entries(t.properties??{}).map(([p,d])=>{if(typeof d!="object")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(d)&&!this.isRequiredProperty({key:p,resolvedSchema:t}))return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&"writeOnly"in d&&d.writeOnly===!0)return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in d&&d.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in d&&d.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let f=!(p in r)||!("nullable"in d)&&r[p]==null||"nullable"in d&&d.nullable===!0&&r[p]===void 0,m=!t.required?.includes(p);if(f&&m){if(this.example===void 0&&this.generateOptionalProperties){let h=this.maybeResolveSchemaExample(d),g=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:p,result:g.convert()}}return{key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let h=r[p],g=h!==void 0?h:this.maybeResolveSchemaExample(d),E=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:d,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:p,result:E}}}),i=(t.allOf??[]).map((p,d)=>{let f=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],skipErrorCollector:!0});return f&&this.isConstraintOnlySchema(f)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${d}]`],context:this.context,schema:{...t,...p,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),o=this.example!==void 0&&(n.some(({result:p})=>p.usedProvidedExample)||i.some(p=>p.usedProvidedExample)),s=Object.fromEntries(n.map(({key:p,result:d})=>[p,d.validExample]).filter(([p,d])=>d!==void 0));for(let p of i)if(typeof p.validExample=="object"&&p.validExample!==null){let d=p.validExample;s={...s,...Object.fromEntries(Object.entries(d).filter(([f,m])=>m!==void 0))}}let a=[],u=this.collectAllPropertyKeys(t),c=Object.keys(r).filter(p=>!u.has(p));if(c.length>0)if(t.additionalProperties===!1)c.forEach(p=>{let d=[...this.breadcrumbs,p].join("."),f={message:`Found unexpected property '${p}' in example. This property does not exist in the schema${d?` at path: ${d}`:""}`,path:[...this.breadcrumbs,p]};a.push({key:p,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[f]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)c.forEach(p=>{a.push({key:p,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[p],errors:[]}})});else{let p=t.additionalProperties;c.forEach(d=>{let m=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:p,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();a.push({key:d,result:m})})}for(let{key:p,result:d}of a)d.validExample!==void 0&&s[p]===void 0&&(s[p]=d.validExample);let l=n.every(p=>p.result.isValid)&&i.every(p=>p.isValid)&&a.every(({result:p})=>p.isValid);if(Object.keys(s).length===0){let p=i.find(d=>d.validExample!==void 0&&(typeof d.validExample!="object"||d.validExample===null));p&&(s=p.validExample)}return{isValid:l,coerced:!1,usedProvidedExample:o,validExample:s,errors:[...n.flatMap(({result:p})=>p.errors),...i.flatMap(p=>p.errors),...a.flatMap(({result:p})=>p.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,u)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${u}]`],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??this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let h=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});h&&d.push(h)}if(d.length>0&&d.every(m=>K3p(m))){let m=d.findIndex(h=>dla(h)!==void 0);if(m!==-1){let h=n[m],g=d[m];if(h&&g){let A=dla(g),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...h,oneOf:void 0}:h,example:A,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,h=i??this.maybeResolveSchemaExample(m),A=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:h,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(A.isValid&&!A.coerced&&A.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:A.validExample,errors:[]};if(A.isValid&&!A.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:A.usedProvidedExample,validExample:A.validExample,errors:[]};o.push(A),A.isValid&&A.usedProvidedExample&&a===null&&(a=A),A.isValid&&s===null&&(s=A)}let u=a??s,c=u!==null,l=u?.validExample??o[0]?.validExample,p=u?.usedProvidedExample??!1;return{isValid:c,coerced:!1,usedProvidedExample:p,validExample:l,errors:c?[]: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(H3p);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let u of a)n.add(u)}}}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 u of a)n.add(u)}}}return n}};var tIi={};Y(tIi,{ArraySchemaConverter:()=>CVe,EnumSchemaConverter:()=>yme,ObjectSchemaConverter:()=>IVe,OneOfSchemaConverter:()=>qOe,PrimitiveSchemaConverter:()=>wVe,SchemaConverter:()=>bme,SchemaOrReferenceConverter:()=>HS});Ci();function mla(e){return D0({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Rr.primitive({v1:"BASE_64",v2:Qn.base64({})});case"BOOLEAN":return Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})});case"DATE":return Rr.primitive({v1:"DATE",v2:Qn.date({})});case"DATE_TIME":return Rr.primitive({v1:"DATE_TIME",v2:Qn.dateTime({})});case"DATE_TIME_RFC_2822":return Rr.primitive({v1:"DATE_TIME_RFC_2822",v2:Qn.dateTimeRfc2822({})});case"FLOAT":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:void 0,validation:void 0})});case"DOUBLE":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:void 0,validation:void 0})});case"UINT":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:void 0,validation:void 0})});case"UINT_64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:void 0,validation:void 0})});case"INTEGER":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:void 0,validation:void 0})});case"LONG":return Rr.primitive({v1:"LONG",v2:Qn.long({default:void 0,validation:void 0})});case"STRING":return Rr.primitive({v1:"STRING",v2:Qn.string({default:void 0,validation:void 0})});case"UUID":return Rr.primitive({v1:"UUID",v2:Qn.uuid({})});case"BIG_INTEGER":return Rr.primitive({v1:"BIG_INTEGER",v2:Qn.bigInteger({default:void 0})});default:return}},unknown:()=>Rr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Rr.container(zs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Rr.container(zs.list(t))},optional:t=>{if(t!=null)return Rr.container(zs.optional(t))},nullable:t=>{if(t!=null)return Rr.container(zs.nullable(t))},set:t=>{if(t!=null)return Rr.container(zs.set(t))},literal:t=>Rr.container(zs.literal(t._visit({string:r=>ww.string(r),boolean:r=>ww.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var yme=class extends io{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:$a.enum({default:n!=null?r.find(i=>i.name.wireValue===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}};var Ddr=class extends io{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=Rr.container(zs.map({keyType:io.STRING,valueType:Rr.unknown()}));return{type:$a.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new HS({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Rr.container(zs.map({keyType:io.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return{type:$a.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}};Qt();function vVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i}){let o=[],s={},a={},u=new Set;for(let[c,l]of Object.entries(e??{})){let p=[...r,"properties",c];if(typeof l!="object"){i.collect({message:`Schema property ${c} should be an object`,path:p});continue}let d=Y3p(r,l,n)??n.convertBreadcrumbsToName(p),f="nullable"in l?l.nullable:!1,h=new HS({context:n,breadcrumbs:p,schemaOrReference:l,schemaIdOverride:d,wrapAsOptional:!t.includes(c),wrapAsNullable:f}).convert();if(h!=null){o.push({name:n.casingsGenerator.generateNameAndWireValue({name:c,wireValue:c}),valueType:h.type,docs:l.description,availability:h.availability,propertyAccess:n.getPropertyAccess(l),v2Examples:h.schema?.typeDeclaration?.v2Examples??J3p({propertySchema:l,breadcrumbs:p,context:n,propertyId:d})}),s={...s,...h.inlinedTypes},h.schema?.typeDeclaration.referencedTypes!=null&&h.schema.typeDeclaration.referencedTypes.forEach(g=>{u.add(g)});for(let g of h.schema?.audiences??[])a[g]==null&&(a[g]=new Set),a[g].add(c)}}for(let c of Object.keys(s))u.add(c);return{convertedProperties:o,propertiesByAudience:a,inlinedTypesFromProperties:s,referencedTypes:u}}function J3p({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 c={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new tE({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:h}=m.convert();c[f]=h}return{userSpecifiedExamples:c,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new tE({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:u}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:u}}}function Y3p(e,t,r){return r.isReferenceObject(t)?void 0:new kI.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var IVe=class extends io{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:$a.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=vVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),s=[],a=i,u=this.schema.required!=null&&this.schema.required.length>0,c=n,l=o;for(let[p,d]of(this.schema.allOf??[]).entries()){let f=[...this.breadcrumbs,"allOf",p.toString()],m;if(this.context.isReferenceObject(d)){let b=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:f});if(b==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${p}] reference could not be resolved. Skipping: ${JSON.stringify(d)}`);continue}if(m=b,typeof m.additionalProperties=="boolean"&&m.additionalProperties&&(t=!0),!u||Object.keys(m.properties??{}).every(I=>!this.schema.required?.includes(I))){this.addTypeReferenceToExtends({reference:d,breadcrumbs:f,extends_:s,referencedTypes:a});continue}}else m=d;typeof m.additionalProperties=="boolean"&&m.additionalProperties&&(t=!0);let h=m.oneOf??m.anyOf;if(h!=null&&m.type==null&&m.properties==null){let b=new Set(r.map(I=>I.name.wireValue));for(let[I,w]of h.entries()){let x=[...f,m.oneOf!=null?"oneOf":"anyOf",I.toString()],C=this.context.isReferenceObject(w)?this.context.resolveMaybeReference({schemaOrReference:w,breadcrumbs:x}):w;if(C==null)continue;let _={};for(let[V,K]of Object.entries(C.properties??{}))!this.context.isReferenceObject(K)&&"not"in K||(_[V]=K);let R=Object.keys(_).filter(V=>!b.has(V));if(R.length===0)continue;let U={};for(let V of R){let K=_[V];K!=null&&(U[V]=K,b.add(V))}let{convertedProperties:q,inlinedTypesFromProperties:z,referencedTypes:Z,propertiesByAudience:oe}=vVe({properties:U,required:[],breadcrumbs:x,context:this.context,errorCollector:this.context.errorCollector});r.push(...q),c={...c,...z},l={...l,...oe},Z.forEach(V=>{a.add(V)})}continue}let{convertedProperties:g,inlinedTypesFromProperties:A,referencedTypes:E,propertiesByAudience:v}=vVe({properties:m.properties??{},required:[...this.schema.required??[],...m.required??[]],breadcrumbs:f,context:this.context,errorCollector:this.context.errorCollector});r.push(...g),c={...c,...A},l={...l,...v},E.forEach(b=>{a.add(b)})}for(let p of Object.keys(c))a.add(p);return{type:$a.object({properties:r,extends:s.map(p=>this.context.typeReferenceToDeclaredTypeName(p)).filter(ma),extendedProperties:[],extraProperties:t}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:c}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}};var Rdr=class extends Na{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 qOe=class extends io{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 Rdr({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null)return this.convertAsDiscriminatedUnion();if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let u of t){let c;if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(c=l.value)}else c=u;c!=null&&(c.enum!=null&&c.enum.length>1&&(c.type==="string"||c.type==null)?r=c:c.type==="string"&&c.enum==null&&(n=!0))}if(r==null||!n)return;let o=new EVe({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new yme({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let[c,l]of Object.entries(this.schema.discriminator.mapping??{})){let p=this.context.getTypeIdFromSchemaReference({$ref:l}),d=[...this.breadcrumbs,"discriminator","mapping",c],f=this.context.resolveReference({reference:{$ref:l},breadcrumbs:d}),m={$ref:l};f.resolved&&f.value.properties!=null&&t in f.value.properties&&(m=this.filterDiscriminantFromSchema(f.value,t));let h=new HS({context:this.context,schemaOrReference:m,schemaIdOverride:p??void 0,breadcrumbs:d});p!=null&&n.add(p);let g=h.convert();if(g?.type!=null&&p!=null){for(let v of Object.keys(g?.inlinedTypes??{}))n.add(v);for(let v of g.schema?.typeDeclaration.referencedTypes??[])n.add(v);let A=this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:c}),E=l.match(/\/schemas\/([^/]+)/)?.[1]??p;r.push({docs:void 0,discriminantValue:A,availability:g.availability,displayName:c,shape:Cw.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(E),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:c})}),i={...i,...g.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=vVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let u=[];for(let[c,l]of(this.schema.allOf??[]).entries()){let p=[...this.breadcrumbs,"allOf",c.toString()];if(this.context.isReferenceObject(l)){let d=this.context.convertReferenceToTypeReference({reference:l,breadcrumbs:p});if(d.ok){let m=this.context.typeReferenceToDeclaredTypeName(d.reference);m!=null&&u.push(m)}let f=this.context.getTypeIdFromSchemaReference(l);f!=null&&n.add(f);continue}}for(let c of Object.keys({...i,...a}))n.add(c);return{type:$a.union({baseProperties:o,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:u,types:r,discriminatorContext:void 0}),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={},i=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(o=>!this.context.isReferenceObject(o));for(let[o,s]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(s)){let d;if(this.context.isReferenceObjectWithIdentifier(s))d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:s.summary??s.title??s.name??s.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(s)!=null){let m=this.getDiscriminatorKeyForRef(s);d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:m,displayNameOverrideSource:"discriminator_key"})}else d=this.context.convertReferenceToTypeReference({reference:s,displayNameOverride:s.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});d.ok&&t.push({type:d.reference,docs:s.description});let f=this.context.getTypeIdFromSchemaReference(s);f!=null&&r.add(f);continue}let a=this.extendSubSchema(s),u=this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),c=s.title,p=new bme({context:this.context,id:u,nameOverride:c,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`],schema:a??s}).convert();if(p!=null){let d=p.convertedSchema.typeDeclaration.shape;if(d.type==="alias"&&this.typeReferenceIsWrappedPrimitive(d.aliasOf))t.push({type:d.aliasOf,docs:s.description});else if(d.type==="object"&&d.properties.length===0&&d.extends.length===0)t.push({type:Rr.container(zs.map({keyType:io.STRING,valueType:Rr.unknown()})),docs:s.description});else{t.push({type:this.context.createNamedTypeReference(u,c),docs:s.description});let f=this.context.getNamespacedSchemaId(u);n={...n,...p.inlinedTypes,[f]:p.convertedSchema}}p.convertedSchema.typeDeclaration.referencedTypes.forEach(f=>{r.add(f)})}}return{type:$a.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:n}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!("type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new HS({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:$a.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 Rr.container(zs.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 wVe=class extends io{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 Rr.container(zs.literal(ww.string(t)));if(this.schema.format==="date-time-rfc-2822")return Rr.primitive({v1:Ho.DateTimeRfc2822,v2:Qn.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Rr.primitive({v1:Ho.Date,v2:Qn.date({})});if(this.schema.format==="date-time")return Rr.primitive({v1:Ho.DateTime,v2:Qn.dateTime({})})}return Rr.primitive({v1:"STRING",v2:Qn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Rr.primitive({v1:"LONG",v2:Qn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Rr.primitive({v1:"DOUBLE",v2:Qn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Rr.primitive({v1:"FLOAT",v2:Qn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Rr.primitive({v1:"INTEGER",v2:Qn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Rr.primitive({v1:"LONG",v2:Qn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Rr.primitive({v1:"UINT",v2:Qn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Rr.primitive({v1:"UINT_64",v2:Qn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Rr.primitive({v1:"INTEGER",v2:Qn.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?Rr.container(zs.literal(ww.boolean(t))):Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}};var X3p=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],bme=class e extends io{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let n=this.tryConvertSingularAllOfSchema();if(n!=null)return n;let i=this.tryConvertPrimitiveSchema();if(i!=null)return i;let o=this.tryConvertArraySchema();if(o!=null)return o;let s=this.tryConvertTypeArraySchema();if(s!=null)return s;let a=this.tryConvertOneOfAnyOfSchema();if(a!=null)return a;let u=this.tryConvertMapSchema();if(u!=null)return u;let c=this.tryConvertDiscriminatorMappingSchema();if(c!=null)return c;let l=this.tryConvertObjectAllOfSchema();if(l!=null)return l;let p=this.tryConvertUntypedSchema();if(p!=null)return p;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new kI.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new yme({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.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let i=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(i?.convertedSchema.typeDeclaration?.shape.type!=="object")return i}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let i of this.schema.allOf??[]){if(this.context.isReferenceObject(i))return;let o=i.oneOf??i.anyOf;if(o!=null&&i.type==null&&i.properties==null){let s={};for(let a of o){let u=this.context.isReferenceObject(a)?this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:this.breadcrumbs}):a;if(u!=null)for(let[c,l]of Object.entries(u.properties??{}))!this.context.isReferenceObject(l)&&"not"in l||c in s||(s[c]=l)}if(Object.keys(s).length>0){let a=r.properties??{};r.properties={...a,...s}}continue}r=DNe(r,i,(s,a)=>{if(a===i)return s;if(Array.isArray(s)&&Array.isArray(a))return[...s,...a]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new wVe({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new CVe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new qOe({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 Ddr({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 qOe({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 IVe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:Rr.unknown(),resolvedType:Rr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new kI.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=mla(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:$a.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...X3p,...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 tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}};var HS=class extends io{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];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:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new bme({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 Rr.container(zs.optional(t))}wrapInNullable(t){return Rr.container(zs.nullable(t))}};var CVe=class e extends io{static LIST_UNKNOWN=Rr.container(zs.list(Rr.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 HS({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),{typeReference:Rr.container(zs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Fdr=class extends io{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 u=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(u==null)return;t.schema=u}let s=new HS({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(([u,c])=>{if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[u,l.value.value??l.value]:null}return[u,c.value??c]}).filter(u=>u!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new HS({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[u,c]of s){let l=this.context.resolveExampleWithValue(c),p=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:u,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let u=Ln(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[u]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:u})}return i}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:u}=a.convert();return u}};var kdr=class extends io{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??io.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??io.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??io.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:s??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},n=this.parameter.example,i=this.parameter.examples;for(let[o,s]of Object.entries(i??{})){let a=this.context.resolveExampleWithValue(s);a!=null&&(r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:a,exampleName:o}))}if(n!=null){let o=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:t,example:n,exampleName:o})}if(Object.keys(r.userSpecifiedExamples).length===0){let o=`${this.parameter.name}_example`;r.autogeneratedExamples[o]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:o})}return r}generateOrValidateExample({schema:t,example:r}){let n=new tE({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}};Qt();var Qdr=class extends Na{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 hla="Base",Z3p="x-fern-default-url",BQ=class e extends io{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(u=>{let c=e.getServerName({server:u,context:this.context});return{id:c,name:this.context.casingsGenerator.generateName(c)}}).filter((u,c,l)=>l.findIndex(p=>p.id===u.id)===c),s=[i,...o],a=this.servers.map(u=>{let c=e.getServerName({server:u,context:this.context}),l=this.endpointLevelServers?.map(h=>[e.getServerName({server:h,context:this.context}),this.getServerUrl(h)]),p=e.getServerAudiences({server:u,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:u,endpointServers:this.endpointLevelServers??[]});return{id:c,name:this.context.casingsGenerator.generateName(c),urls:{[n]:this.getServerUrl(u),...Object.fromEntries(l??[])},docs:u.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,environments:iy.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(ma);return{value:{defaultEnvironment:r[0]?.id,environments:iy.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 Qdr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new bVe({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?hla:e.getServerExtensionName({server:this.servers[0],context:this.context})??hla}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 u=this.extractFernDefaultUrlFromServer(r);u!=null&&(i[t]=u),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let u of n){let c=e.getServerName({server:u,context:this.context});if(u.variables!=null&&Object.keys(u.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(u);l!=null&&(i[c]=l),o[c]=this.maybeRemoveTrailingSlashIfNotEmpty(u.url),s[c]=this.convertServerVariables(u.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[Z3p];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 GOe=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new tE({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 c=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!c.isValid){i=!1;let l=t.exampleSource==="human"?Sv.WARNING:Sv.ERROR;r.push(...c.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}c.coerced&&(o=!0,n.push({level:Sv.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:c.validExample}}let u=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&u!==void 0){let c=this.validateExample({example:t.responseExample,schema:u,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!c.isValid){i=!1;let l=t.exampleSource==="human"?Sv.WARNING:Sv.ERROR;r.push(...c.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}c.coerced&&(o=!0,n.push({level:Sv.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:c.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:u}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),c={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:u},l=this.validateEndpointExample({exampleToValidate:c}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf)return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let u of a)n.add(u)}}}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 u of a)n.add(u)}}}return n}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[u,c]of Object.entries(t.paths)){if(!c)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=c[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:h,responseSchemas:g}=this.getSchemasForOperation({operation:d}),A=this.extractExamplesFromOperation({operation:d,path:u,method:p});for(let E of A){n++;let v={endpointPath:u,method:p,exampleName:E.name,exampleSource:E.source,requestExample:E.request,responseExample:E.response,requestSchema:m,responseSchema:h,responseStatusCode:E.statusCode,responseSchemas:g},b=this.validateEndpointExample({exampleToValidate:v});f.push(b),b.isValid?i++:(o++,E.source==="human"?s.push(b):E.source==="ai"&&a.push(b))}f.length>0&&r.push({endpointPath:u,method:p,results:f,hasInvalidExamples:f.some(E=>!E.isValid),invalidExampleCount:f.filter(E=>!E.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 u=s.content?.["application/json"];u?.schema&&(i[o]=u.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[u,c]of Object.entries(a.examples)){let l=this.context.isReferenceObject(c)?this.context.resolveExample(c):c;l&&typeof l=="object"&&"value"in l&&i.push({name:u,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let c=a.content?.["application/json"];if(c?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=c.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:c.example,statusCode:s})}if(c?.examples)for(let[l,p]of Object.entries(c.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}};var Ndr={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"},ezp=new Set(Object.values(Ndr));Ci();var tzp=mt.object({type:mt.string(),channelId:mt.string().optional(),messageId:mt.string(),value:mt.any()}),rzp=mt.object({summary:mt.string().optional(),description:mt.string().optional(),"query-parameters":mt.record(mt.string()).optional(),headers:mt.record(mt.string()).optional(),messages:mt.array(tzp)}),gla=mt.array(rzp);var jdr=class extends Na{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=gla.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 xVe=class extends io{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 jdr({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(u=>({type:n==="v2"?u.type:u.messageId,body:u.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var nzp="x-fern-server-name",j6=class e extends io{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,environments:iy.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[nzp];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var Eme=class extends qf.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 kI.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 qf.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 Mdr=class extends Na{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 _Ve=class extends Na{channel;key="x-fern-display-name";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 Ldr=class extends xVe{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 _Ve({breadcrumbs:this.breadcrumbs,channel: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 u=[];s!=null&&u.push(s),a!=null&&u.push(a);let l=new Mdr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=hy(p),m=Ln(this.channelPath),h=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:!1,headers:n,queryParameters:r,pathParameters:t,messages:u,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})}},audiences:h,inlinedTypes:this.inlinedTypes}}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 u=MCe(Ln(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:u}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let c=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(c!=null){let p=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:c,schemaIdOverride:u}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let c=i,l=Rr.named({fernFilepath:t.createFernFilepath(),name:c.typeDeclaration.name.name,typeId:c.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=Zx.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish";return{type:d,displayName:d,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}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 Eme({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0}}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let u=new Eme({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0}}).convert();u!=null&&u.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},r.push(u.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return j6.getServerName(t,n)}return t}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 u=new Eme({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1}}).convert();u!=null&&u.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},r.push(u.parameter))}}}};var Udr=class extends j6{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 nIi="$message.",Ala="#/channels/",yla="#/servers/",zdr=class extends xVe{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 _Ve({breadcrumbs:this.breadcrumbs,channel: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((d,[f,m])=>{try{this.getChannelPathFromOperation(m)===this.channelPath&&(d[f]=m)}catch{}return d},{}),a=[];for(let[d,f]of Object.entries(s))for(let m of f.messages){let h=this.context.convertReferenceToTypeReference({reference:m});if(h.ok){let g=Zx.reference({bodyType:h.reference,docs:f.description});a.push({type:d,displayName:d,origin:f.action==="send"?"client":"server",body:g,availability:this.context.getAvailability({node:f,breadcrumbs:this.breadcrumbs}),docs:f.description,methodName:void 0})}}let u=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),c=this.transformToValidPath(this.channel.address??this.channelPath),l=hy(c),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:u,path:l,auth:!1,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:c,baseUrl:u,asyncApiVersion:"v3"})}},audiences:p,inlinedTypes:this.inlinedTypes}}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:u,parameterKey:c}=a,p=new Eme({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:c,in:u},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(nIi)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${nIi} prefix`,path:this.breadcrumbs});return}let i=r.substring(nIi.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(yla)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(yla.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 j6.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 j6.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(Ala))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(Ala.length)}};var Vdr=class extends j6{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 hIt=class extends N6{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.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 u=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(u==null)continue;let c=`${r}_${i}`;this.convertSchema({id:c,breadcrumbs:s,schema:u})}}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 qf.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 Vdr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Udr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new kI.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 zdr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new Ldr({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 gIt=class extends kA{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\/(.+)$/),u=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 c=a[1],l=a[2];return o=`${c}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return u&&u[1]?(o=u[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;return i==="reference_identifier"?a=n??s.value.title:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.title??n),{ok:!0,reference:Rr.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;return i==="reference_identifier"?a=n??s.value.name:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.name??n),{ok:!0,reference:Rr.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;return i==="reference_identifier"?a=n??s.value.messageId??s.value.name:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.messageId??s.value.name??n),{ok:!0,reference:Rr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};Qt();Vt();var xla=_e(qdr(),1);var Gdr=class extends Na{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Wdr=class extends Na{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 bla({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?io.OPTIONAL_STRING:io.STRING,env:r.env,v2Examples:r.optional?void 0:szp({header:r,context:t}),availability:void 0,docs:void 0}))}function szp({header:e,context:t}){let r=new tE({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}Ci();var $dr=class extends qf.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let n=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),o=new qf.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:n}).convert();o!=null&&(t=o.type,r=o.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};Qt();var Hdr=class extends qf.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:u,streamingExtension:c,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:u}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=c,this.queryParameters=l??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(af.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=af.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=af.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;let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:Tf.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:Tf.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes})}:{requestBody:Tf.reference({contentType:t,docs:this.description,requestBodyType:n.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.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:Tf.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[o.name.wireValue];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:Tf.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?XE.file(OD.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):XE.file(OD.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):XE.bodyProperty({...t,contentType:n?.contentType??r,style:uzp({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i==null||this.context.isReferenceObject(i))return;let o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(u==null)return;let c=u.schema?.typeDeclaration.shape;if(c?.type==="object")return{requestBody:Tf.inlinedRequestBody({contentType:i,docs:void 0,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:c.extendedProperties,extends:c.extends,properties:c.properties,extraProperties:c.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:u.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=>n.name.wireValue.toLowerCase()));return t.some(n=>r.has(n.name.wireValue.toLowerCase()))}},azp={"application/json":"json"};function uzp({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return azp[e.contentType]}}var czp=/{([^}]+)}/g,lzp=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),SVe=class extends io{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o}convertHttpMethod(){switch(this.method){case"get":return Gh.Get;case"post":return Gh.Post;case"put":return Gh.Put;case"delete":return Gh.Delete;case"patch":return Gh.Patch;case"head":return Gh.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let o of this.operation.parameters){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t});if(s==null)continue;let u=new $dr({context:this.context,breadcrumbs:t,parameter:s}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let c=u.parameter.name.name.originalName,l=u.parameter.name.wireValue,p=!1,d=this.context.authOverrides?.["auth-schemes"];if(d!=null){for(let m of Object.values(d))if(mzp(m)&&m.header.toLowerCase()===l.toLowerCase()){p=!0;break}}let f=this.context.globalHeaderNames;if(f!=null){for(let m of f)if(m.toLowerCase()===l.toLowerCase()){p=!0;break}}!lzp.has(c.toLowerCase())&&!p&&i.push(u.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}checkMissingPathParameters(t){let n=[...this.path.matchAll(czp)].map(i=>i[1]).filter(i=>!t.some(o=>o.name.originalName===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:io.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode: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[u,c]of Object.entries(s.content)){let p=new Hdr({context:this.context,breadcrumbs:t,contentType:u,mediaType:c,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new kI.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new kI.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?Ln(this.operation.summary):Ln(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let n=Ela(t),i=Ela(r);return Qb(n,i)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:n,methodName:r,methodNameTokens:i})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,u)=>a!==i[u]))return{group:[t],method:n};let s=i.slice(r.length);return{group:[t],method:Ln(s.join("_"))}}generateStringParameterExample({example:t}){let r=new qf.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}};function Ela(e){let t=pzp(e)?fzp(e):dzp(e);return t=t.map(r=>r.toLowerCase()),t=dj(t),t}function pzp(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function fzp(e){return e.split(/(?=[A-Z])/)}function dzp(e){return e.split(/[^a-zA-Z0-9]+/)}function mzp(e){return e?.header!=null}var BVe=class extends SVe{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let u=a[0]?.requestBody;if(u==null)return;let c,l;if(u.type==="inlinedRequestBody")c=xw.inlinedPayload({name:u.name,extends:u.extends,properties:u.properties});else if(u.type==="reference")c=xw.reference({payloadType:u.requestBodyType,docs:u.docs});else if(u.type==="fileUpload")l={name:u.name,properties:u.properties,docs:u.docs,v2Examples:u.v2Examples,contentType:u.contentType},c=xw.inlinedPayload({name:u.name,extends:[],properties:[]});else return;let p=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:c,signatureVerification:void 0,fileUploadPayload:l,responses:p.length>0?p:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(u.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(u.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 sIi=_e(qdr(),1);var vla=["get","post","put","delete","patch","head"];var Kdr=class extends Na{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 hzp=mt.object({cursor:mt.string(),next_cursor:mt.string(),results:mt.string()}),gzp=mt.object({offset:mt.string(),results:mt.string(),step:mt.string().optional(),"has-next-page":mt.string().optional()}),Azp=mt.object({next_uri:mt.string(),results:mt.string()}),yzp=mt.object({next_path:mt.string(),results:mt.string()}),iIi=mt.union([mt.boolean(),hzp,gzp,Azp,yzp]);var oIi="$request.",Ime="$response.",Jdr=class extends Na{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=iIi.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=iIi.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:kA.maybeTrimPrefix(r.cursor,oIi),nextCursor:kA.maybeTrimPrefix(r.next_cursor,Ime),results:kA.maybeTrimPrefix(r.results,Ime)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:kA.maybeTrimPrefix(n.next_uri,Ime),results:kA.maybeTrimPrefix(n.results,Ime)};let i=t;if("next_path"in i)return{type:"path",nextPath:kA.maybeTrimPrefix(i.next_path,Ime),results:kA.maybeTrimPrefix(i.results,Ime)};let o=t;return{type:"offset",offset:kA.maybeTrimPrefix(o.offset,oIi),results:kA.maybeTrimPrefix(o.results,Ime),step:o.step!=null?kA.maybeTrimPrefix(o.step,oIi):void 0,hasNextPage:o["has-next-page"]!=null?kA.maybeTrimPrefix(o["has-next-page"],Ime):void 0}}};var bzp="$request.",Ezp=mt.object({"stream-condition":mt.string().optional(),format:mt.enum(["sse","json"]).optional(),"stream-description":mt.string().optional(),"stream-request-name":mt.string().optional(),"response-stream":mt.any(),response:mt.any(),terminator:mt.string().optional()}),vzp=mt.union([mt.boolean(),Ezp]),Ydr=class extends Na{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=vzp.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:kA.maybeTrimPrefix(r.data["stream-condition"],bzp),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response}}};var Xdr=class extends Na{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}}};Ci();Qt();var emr=require("fs"),Ila=require("path");function Izp(e){return ba(e)&&typeof e.$ref=="string"}function wzp(e,t){if(e!=null){if(typeof e=="string")return e;if(Izp(e)){let r=(0,Ila.resolve)(t??process.cwd(),e.$ref);if((0,emr.existsSync)(r))try{return(0,emr.readFileSync)(r,"utf-8")}catch{return}}}}var Zdr=class extends Na{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=ba(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 u of s){if(!ba(u))continue;let c=u,l=c.lang,p=c.label,d=c.source;if(typeof l!="string")continue;let f=wzp(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}};Qt();var rmr=require("fs"),wla=require("path");function Czp(e){return ba(e)&&typeof e.$ref=="string"}function xzp(e,t){if(e!=null){if(typeof e=="string")return e;if(Czp(e)){let r=(0,wla.resolve)(t??process.cwd(),e.$ref);if((0,rmr.existsSync)(r))try{return(0,rmr.readFileSync)(r,"utf-8")}catch{return}}}}function _zp(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!ba(n))continue;let o=xzp(n.code,t);o!=null&&r.push({...n,code:o})}return r}var tmr=class extends Na{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(!ba(o))return o;let a=o["code-samples"];if(a!=null){let u=_zp(a,this.baseDir);return{...o,"code-samples":u}}return o}).filter(o=>{let s=$d.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 AIt=class extends Na{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}}};Qt();var yIt=class extends qf.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300){let o={schema:{type:"object",description:"Empty response body"}},s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:"application/json",resolveSchema:!0});if(s!=null)return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:s})}}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:Zu.json(P0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:Zu.streaming(jb.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:Zu.streaming(jb.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:Zu.streaming(jb.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:Zu.json(P0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:Zu.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:Zu.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:Zu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return af.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=io.OPTIONAL_STRING;if(s!=null){let c=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});c!=null&&(c.type==="number"||c.type==="integer"?a=Rr.primitive({v1:c.type==="integer"?"INTEGER":"DOUBLE",v2:c.type==="integer"?Qn.integer({default:void 0,validation:void 0}):Qn.double({default:void 0,validation:void 0})}):c.type==="boolean"&&(a=Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})})))}let u=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:u,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,u]of Object.entries(s??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:c}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};var nmr=class extends qf.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:u}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=u}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:Rr.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:Cla(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),u=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),c=this.getIdForErrorExample({key:o,example:u,usedExampleNames:n});n.add(c),a!=null&&(i[c]=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 Ndr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?Cla(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[n,i]of Object.entries(r)){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"headers",n]});if(o==null)continue;let s=o.schema,a=io.OPTIONAL_STRING;if(s!=null){let c=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:[...this.breadcrumbs,"headers",n,"schema"]});c!=null&&(c.type==="number"||c.type==="integer"?a=Rr.primitive({v1:c.type==="integer"?"INTEGER":"DOUBLE",v2:c.type==="integer"?Qn.integer({default:void 0,validation:void 0}):Qn.double({default:void 0,validation:void 0})}):c.type==="boolean"&&(a=Rr.primitive({v1:"BOOLEAN",v2:Qn.boolean({default:void 0})})))}let u=this.convertHeaderExamples({header:o,headerName:n,schema:s});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),docs:o.description,valueType:a,env:void 0,v2Examples:u,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t.example,s=t.examples;for(let[a,u]of Object.entries(s??{})){let c=this.context.resolveExampleWithValue(u);c!=null&&(i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:c}))}if(o!=null){let a=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(i.userSpecifiedExamples)});i.userSpecifiedExamples[a]=this.generateHeaderExample({schema:n,example:o})}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let a=`${r}_example`;i.autogeneratedExamples[a]=this.generateHeaderExample({schema:n,example:void 0,ignoreErrors:!0})}return i}generateHeaderExample({schema:t,example:r,ignoreErrors:n}){if(t==null)return r;let i=new tE({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:o,errors:s}=i.convert();return n||s.forEach(a=>{this.context.errorCollector.collect({message:a.message,path:a.path})}),o}};function Cla(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var imr=class e extends SVe{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,idempotent:s,idToAuthScheme:a,topLevelServers:u,pathLevelServers:c,streamingExtension:l}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o}),this.idempotent=s,this.idToAuthScheme=a,this.topLevelServers=u,this.pathLevelServers=c,this.streamingExtension=l}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),{headers:o,pathParameters:s,queryParameters:a}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:a}),c=u?.[0]?.requestBody,l=u?.[0]?.streamRequestBody,p={requestBodies:u?.map(K=>K.requestBody)},d=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),f=d?.response,m=d?.streamResponse,h=d!=null?d.errors:[],g={},A=h.map(K=>K.error),E=hy(this.path),v=this.getEndpointBaseUrl(),b=this.getEndpointBaseUrls(),I=this.convertExamples({httpPath:E,httpMethod:t,baseUrl:v}),w=new Set(this.operation.security?.flatMap(K=>Object.keys(K))??[]),x=this.authSchemeToHeaders(Array.from(w));x.length>0&&o.push(...x);for(let K of h){let be=K.error,Ce=K.errorType,J=be.error.errorId,H=K.examples;g[J]={name:be.error,displayName:K.displayName,discriminantValue:{name:be.error.name,wireValue:J},type:Ce,statusCode:K.statusCode,isWildcardStatusCode:K.isWildcardStatusCode,docs:be.docs,examples:[],v2Examples:{userSpecifiedExamples:H??{},autogeneratedExamples:{}},headers:K.headers}}let C=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],R=new AIt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),z=new AIt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??R,Z={displayName:this.operation.summary,method:t,baseUrl:v,v2BaseUrls:b,path:E,pathParameters:s,queryParameters:a,headers:o.filter((K,be,Ce)=>be===Ce.findIndex(J=>J.name.wireValue===K.name.wireValue)),responseHeaders:d?.responseHeaders,sdkRequest:void 0,errors:A,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:E,allPathParameters:s,pagination:void 0,transport:void 0,source:rS.openapi(),audiences:C,retries:void 0,apiPlayground:z},oe=this.context.namespace!=null?[this.context.namespace]:[],V=r?.map(K=>Ln(K));return oe.push(...V??[]),{audiences:C,group:r,groupDisplayName:i,errors:g,endpoint:{...Z,id:`endpoint_${oe.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:c,v2RequestBodies:p,response:f,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:I.examples},v2Responses:{responses:d?.v2Responses}},streamEndpoint:m!=null&&m.body!=null?{...Z,id:`endpoint_${oe.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:l,v2RequestBodies:void 0,response:m,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:I.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:m.body,docs:m.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1;for(let[a,u]of Object.entries(this.operation.responses)){let c=/^[45]XX$/i.test(a),l,p=!1;if(c)l=parseInt(a.charAt(0))*100,p=!0;else{if(l=parseInt(a),isNaN(l)||l<200||l>=300&&l<400)continue;p=l>=400&&l<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),l>=200&&l<300){let d=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,a]});if(d==null)continue;let m=new yIt({context:this.context,breadcrumbs:[...t,a],responseBody:d,group:r??[],method:n,statusCode:a,streamingExtension:i}).convert();m!=null&&(this.inlinedTypes={...this.inlinedTypes,...m.inlinedTypes},s||(s=!0,o.response={statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.responseBody,docs:d.description},o.streamResponse={statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.streamResponseBody,docs:d.description},m.headers!=null&&(o.responseHeaders=m.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:l,isWildcardStatusCode:c?!0:void 0,body:m.responseBody,docs:d.description}])}if(p){let d=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,a]});if(d==null)continue;let m=new nmr({context:this.context,breadcrumbs:[...t,a],responseError:d,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:l,isWildcardStatusCode:c?!0:void 0}).convert();m!=null&&(this.inlinedTypes={...this.inlinedTypes,...m.inlinedTypes},o.errors.push(m))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new yIt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():this.operation.security??this.context.spec.security}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:io.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples: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 tmr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new Zdr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return c.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:c}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:c}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(c=>!(c.response!=null&&"stream"in c.response)),s=i.filter(c=>c.response!=null&&"stream"in c.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),u=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:u}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let u=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:u,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 qt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return qt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new kI.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${bn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return BQ.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(n=>{let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return BQ.getServerName({server:o,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let n=t?.[t.length-1];if(n!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===n?r:void 0}};var omr=class extends io{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s}convert(){let t=[],r=[],n={};for(let i of vla){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 c=new Ydr({breadcrumbs:s,operation:o,context:this.context}).convert();c==null&&this.operationHasTextEventStreamResponse(o)&&(c={type:"stream",format:"sse",terminator:void 0});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:c});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new Xdr({breadcrumbs:n,operation:t,context:i}).convert()?new BVe({context:this.context,breadcrumbs:n,operation:t,method:sIi.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new Jdr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let u=new Kdr({breadcrumbs:n,operation:t,context:this.context}).convert();return new imr({context:this.context,breadcrumbs:n,operation:t,method:sIi.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:u,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}};var smr=class extends io{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",n=t?.env;return ud.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:n,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",n=t?.password?.name??"password",i=t?.username?.env,o=t?.password?.env;return ud.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(n),usernameEnvVar:i,passwordEnvVar:o,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",n=t?.env,i=t?.prefix;return ud.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:io.OPTIONAL_STRING,prefix:i,headerEnvVar:n,docs:this.securityScheme.description})}break}case"oauth2":return ud.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var bIt=class extends N6{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.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Wdr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=bla({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertBasePath(){let r=new Gdr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=hy(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=uhi({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new smr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let i=k0t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return i!=null&&this.addEnvironmentsToIr({environmentConfig:i.environmentsConfig,audiences:i.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let n=new BQ({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 qf.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 BVe({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:xla.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[n,i]of Object.entries(this.context.spec.paths??{})){if(i==null)continue;let s=new omr({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:i,path:n}).convert();if(s!=null){for(let a of s.endpoints){if(a.streamEndpoint!=null&&this.addEndpointToIr({endpoint:a.streamEndpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),this.addEndpointToIr({endpoint:a.endpoint,audiences:a.audiences,endpointGroup:a.group,endpointGroupDisplayName:a.groupDisplayName}),a.servers)for(let u of a.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(a.errors)for(let[u,c]of Object.entries(a.errors))r[u]=c}for(let a of s.webhooks){let u=this.context.getGroup({groupParts:a.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:a.webhook,operationId:u.join("."),group:u,audiences:a.audiences})}this.addTypesToIr(s.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security&&delete i.security}}}};var amr=class extends Na{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 koe=class extends kA{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.getRawSchemaNameFromReference(t)??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let u;i==="reference_identifier"?u=n??a.value.title:i==="discriminator_key"?u=a.value.title??n:i==="schema_identifier"&&(u=a.value.title);let c;if(o.includes("/")){let p=new qf.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(c={[o]:p.convertedSchema})}return{ok:!0,reference:Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:u}),inlinedTypes:c}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new amr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=i}return this.tagToDisplayName[t]??t}};var Szp=mt.object({description:mt.string().optional(),required:mt.boolean().optional(),deprecated:mt.boolean().optional(),allowEmptyValue:mt.boolean().optional(),style:mt.string().optional(),explode:mt.boolean().optional(),allowReserved:mt.boolean().optional(),schema:mt.any().optional(),example:mt.any().optional(),examples:mt.record(mt.string(),mt.any()).optional(),content:mt.record(mt.string(),mt.any()).optional()}),Bzp=Szp.extend({name:mt.string(),in:mt.string()}),Ozp=mt.array(Bzp),umr=class extends Na{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 Ozp.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var cmr=class extends io{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let c of this.pathParameters)r+=`/{${c.name.originalName}}`;let n=hy(r),i=[];for(let[c,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let h=this.context.resolveReference({reference:l});if(h.resolved)p=h.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new qf.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let c=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(c!=null){let l=new qf.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:c.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:c.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?Tf.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:Zu.json(P0.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:rS.openrpc(),audiences:a,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return BQ.getServerName({server:s,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let n of this.method.examples??[]){let i;if(this.context.isReferenceObject(n)){let u=this.context.resolveReference({reference:n});if(u.resolved)i=u.value;else continue}else i=n;let o;if(i.result)if(this.context.isReferenceObject(i.result)){let u=this.context.resolveReference({reference:i.result});u.resolved&&(o=u.value)}else o=i.result;let s=i.name??`Example ${r+1}`,a=[];if(i.params&&Array.isArray(i.params)){a=[];for(let u of i.params)if(this.context.isReferenceObject(u)){let c=this.context.resolveReference({reference:u});if(c.resolved)a.push(c.value);else continue}else a.push(u)}t[s]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:a.map(u=>u.value)??void 0},response:{docs:void 0,statusCode:void 0,body:o?.value?qt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:i.examplePairedRequest?.id||"1",result:o.value}):void 0},codeSamples:[]}}++r}return t}};var lmr=class extends qf.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 qf.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 EIt=class extends N6{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 BQ({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 qf.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 umr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[u,c]of n.entries()){let p=new lmr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${u}]`],parameter:c}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let u of this.context.spec.methods??[]){let c=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:["methods"]});if(c==null)continue;let p=new cmr({context:this.context,breadcrumbs:["methods"],method:c,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}};var vIt=class extends kA{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;return i==="reference_identifier"?a=n??s.value.title:(i==="discriminator_key"||i==="schema_identifier")&&(a=s.value.title??n),{ok:!0,reference:Rr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}};var Mma=require("fs/promises");var _la=require("fs/promises");async function aIi({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,_la.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=wr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await yVe({absoluteFilePathToOverrides:a,context:e,data:s});return s}Vt();var efa=_e(Zpa(),1);function I8p(e,t){if(!t)return;if(e.catch(()=>{}),t.aborted){e.kill();return}let r=()=>{e.kill()};t.addEventListener("abort",r,{once:!0}),e.finally(()=>t.removeEventListener("abort",r)).catch(()=>{})}function L4(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let u=i.reduce((p,d)=>({...p,[d]:"<redacted>"}),o),c=[t,...r].join(" ");for(let[p,d]of Object.entries(u))c=c.replaceAll(p,d);e?.debug(`+ ${c}`);let l=(0,efa.default)(t,r,a);return I8p(l,s),l}async function cc(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:o={},signal:s,...a}={}){let u=L4(e,t,r,{doNotPipeOutput:n,secrets:i,substitutions:o,signal:s,...a});n||(u.stdout?.pipe(process.stdout),u.stderr?.pipe(process.stderr));let c=await u;return c.stdout==null&&(c.stdout=""),c.stderr==null&&(c.stderr=""),c}function wme(e,{logger:t,...r}={}){return(n,i)=>cc(t,e,n,{...r,...i})}var xP=require("fs/promises"),lfa=_e(require("path"),1),xIi=_e(Aw(),1);Vt();var WOe=require("fs/promises"),tfa=_e(Aw(),1);function SIt(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var _It,CIi;async function BIt(e,t,r=5e3){return _It!==void 0?_It:(CIi==null&&(CIi=w8p(e,t,r)),CIi)}async function w8p(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),_It=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(n){let i=n instanceof Error?n.message:String(n);return SIt(i)?(_It=!0,t.debug(`Network check failed - entering air-gapped mode: ${i}`),!0):(_It=!1,!1)}}async function ymr(e,t){let r=We(e,Se.of("buf.lock")),n=!1;try{await(0,WOe.access)(r),n=!0,t.debug(`Found buf.lock at: ${r}`)}catch{t.debug(`No buf.lock found at: ${r}`)}if(!n)return!1;let i=Ut.of((await tfa.default.dir()).path);try{let o=We(e,Se.of("buf.yaml"));try{await(0,WOe.cp)(o,We(i,Se.of("buf.yaml"))),await(0,WOe.cp)(r,We(i,Se.of("buf.lock")))}catch{return!1}try{return await L4(t,"buf",["dep","update"],{cwd:i,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(s){let a=s instanceof Error?s.message:String(s);return SIt(a)?(t.debug(`Network check failed - entering air-gapped mode: ${a.substring(0,100)}`),!0):!1}}finally{try{await(0,WOe.rm)(i,{recursive:!0,force:!0})}catch{}}}var rfa="buf.gen.yaml",C8p="output",nfa=`${C8p}/ir.json`,ifa="protoc-gen-fern",ofa=`version: v1
1544
1544
  `,sfa=`version: v2
1545
1545
  `,bmr=e=>{let t=`version: v1
1546
1546
  `;if(e.length>0){t+=`deps:
@@ -1653,7 +1653,7 @@ ${Txa.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&jSi(th
1653
1653
  `+DPe.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?DPe.default.cyan(Lxa(t,this.opt.mask)):DPe.default.italic(DPe.default.dim("[hidden]")):this.opt.mask?Lxa(t,this.opt.mask):DPe.default.italic(DPe.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var FEr=_e(jI(),1);var M_a=_e(bBi(),1),DEr=require("child_process"),x9e=require("fs"),TEr=_e(require("path"),1),L_a=_e(require("os"),1),U_a=require("crypto"),nOi=_e(N_a(),1);var BEr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var RCt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var OEr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var PEr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function REr(e="",t,r){let n=new iOi(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function j_a(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function pbf(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var iOi=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=pbf(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??L_a.default.tmpdir(),r=(0,U_a.randomUUID)(),n=j_a(this.fileOptions.prefix),i=j_a(this.fileOptions.postfix),o=`${n}${r}${i}`,s=TEr.default.resolve(t,o),a=TEr.default.resolve(t)+TEr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,x9e.writeFileSync)(this.tempFile,this.text,u)}catch(t){throw new BEr(t)}}readTemporaryFile(){try{let t=(0,x9e.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,M_a.detect)(t)??"utf8";nOi.default.encodingExists(r)||(r="utf8"),this.text=nOi.default.decode(t,r)}}catch(t){throw new OEr(t)}}removeTemporaryFile(){try{(0,x9e.unlinkSync)(this.tempFile)}catch(t){throw new PEr(t)}}launchEditor(){try{let t=(0,DEr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new RCt(t)}}launchEditorAsync(t){try{(0,DEr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new RCt(r)}}};var z_a=_e(LQ(),1);var FCt=class extends MI{_run(t){this.done=t,this.editorResult=new z_a.Subject;let r=t1(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?FEr.default.dim("Received"):FEr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=FEr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),REr(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var $_a=require("stream");var G_a=_e(require("readline"),1),W_a=_e(q_a(),1),QPe=class{constructor(t){this.rl||=G_a.default.createInterface(dbf(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function dbf(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new W_a.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var kCt=class extends QPe{constructor(t={}){super(t),this.log=new $_a.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return yCt(this.rl,this.bottomBar.split(`
1654
1654
  `).length),this}updateBottomBar(t){return yCt(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+`
1655
1655
  `}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&&rEr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var bf=_e(LQ(),1),J_a=_e(Kwt(),1);var kEr=_e(LQ(),1),H_a=_e(Kwt(),1),QEr=function(e,t,r){return typeof e[t]!="function"?(0,kEr.of)(e):(0,kEr.from)((0,H_a.default)(e[t])(r).then(n=>(e[t]=n,e)))};var K_a={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}},_9e=class extends QPe{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,bf.from)(t):(0,bf.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,bf.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,bf.from)([t]),this.process=n.pipe((0,bf.concatMap)(this.processQuestion.bind(this)),(0,bf.publish)()),this.process.connect(),this.process.pipe((0,bf.reduce)((i,o)=>(K_a.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,bf.defer)(()=>(0,bf.of)(t).pipe((0,bf.concatMap)(this.setDefaultType.bind(this)),(0,bf.concatMap)(this.filterIfRunnable.bind(this)),(0,bf.concatMap)(()=>QEr(t,"message",this.answers)),(0,bf.concatMap)(()=>QEr(t,"default",this.answers)),(0,bf.concatMap)(()=>QEr(t,"choices",this.answers)),(0,bf.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,bf.defer)(()=>(0,bf.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,bf.defer)(()=>(0,bf.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&K_a.get(this.answers,t.name)!==void 0)return bf.EMPTY;if(t.when===!1)return bf.EMPTY;if(typeof t.when!="function")return(0,bf.of)(t);let{answers:r}=this;return(0,bf.defer)(()=>(0,bf.from)((0,J_a.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,bf.filter)(n=>n!=null)))}};function Y_a(e){let t=function(r,n){let i;try{i=new _9e(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",ECt),this.registerPrompt("input",TPe),this.registerPrompt("number",vCt),this.registerPrompt("confirm",ICt),this.registerPrompt("rawlist",wCt),this.registerPrompt("expand",CCt),this.registerPrompt("checkbox",xCt),this.registerPrompt("password",_Ct),this.registerPrompt("editor",FCt)},t.restoreDefaultPrompts(),t}var sOi=Y_a();function hbf(e,t){sOi.registerPrompt(e,t)}function gbf(){sOi.restoreDefaultPrompts()}var Abf={prompt:sOi,ui:{BottomBar:kCt,Prompt:_9e},createPromptModule:Y_a,registerPrompt:hbf,restoreDefaultPrompts:gbf,Separator:gF},lp=Abf;var S9e=require("path");function Z_a(){let e=ybf();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function ybf(e=process.argv[1]?(0,S9e.dirname)(process.argv[1]):process.cwd(),t=S9e.sep==="\\"){let r=t?X_a(e):e;return n=>{if(!n)return;let i=t?X_a(n):n,{dir:o,base:s,ext:a}=S9e.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);o||(o=".");let c=o.lastIndexOf("/node_modules");if(c>-1)return`${o.slice(c+14).replace(/\//g,".")}:${u}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function X_a(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var aOi=e=>{if("flags"in e){let t=e1a(e.flags),r=t1a(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,uOi(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,bbf(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function bbf(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 e1a=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,QCt(r)]).filter(([,t])=>t!==void 0)),t1a=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?uOi(n):void 0]}))};var QCt=e=>e===void 0?void 0:e.variant??e.enabled,uOi=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var NEr="0123456789abcdef",jEr=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+=NEr.charAt(this.bytes[r]>>>4),t+=NEr.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+=NEr.charAt(this.bytes[r]>>>4),t+=NEr.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}},cOi=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Ebf()}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 jEr.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,jEr.ofInner(t)}},Ebf=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),r1a,iK=()=>vbf().toString(),vbf=()=>(r1a||(r1a=new cOi)).generate();var yF=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var Ibf=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],n1a=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return Ibf.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var Cbf=Array.isArray,i1a=Object.prototype,WQy=i1a.hasOwnProperty,lOi=i1a.toString,pOi=Cbf||function(e){return lOi.call(e)==="[object Array]"};var fOi=e=>e===Object(e)&&!pOi(e);var B9e=e=>e===void 0,NCt=e=>lOi.call(e)=="[object String]",o1a=e=>NCt(e)&&e.trim().length===0;var s1a=e=>lOi.call(e)=="[object Number]"&&e===e;var dOi=e=>e instanceof Error;function jCt(e){return e===null||typeof e!="object"}function NPe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function a1a(e){return NPe(e,"ErrorEvent")}function MEr(e){return!B9e(Event)&&xbf(e,Event)}function u1a(e){return NPe(e,"Object")}function xbf(e,t){try{return e instanceof t}catch{return!1}}function MCt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),s1a(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),MCt(i||r,t,r,n))}var _bf=864e5,LEr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=MCt(t.bucketSize,0,100,t._logger),this._refillRate=MCt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=MCt(t.refillInterval,0,_bf,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 UEr=class{add(t){let r=iK();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function Sbf(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var c1a=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>c1a(`${e} ${o}`,t,r)}},Bbf=e=>e();function l1a(e,t=Bbf){return c1a(e,t,Sbf())}var P9e="Mobile",VEr="iOS",O9e="Android",p1a="Tablet",iNy=O9e+" "+p1a;var Obf="Apple",oNy=Obf+" Watch",f1a="Safari",qEr="BlackBerry",d1a="Samsung",Pbf=d1a+"Browser",Tbf=d1a+" Internet",GEr="Chrome",Dbf=GEr+" OS",Rbf=GEr+" "+VEr,m1a="Internet Explorer",Fbf=m1a+" "+P9e,hOi="Opera",sNy=hOi+" Mini",h1a="Edge",kbf="Microsoft "+h1a,gOi="Firefox",Qbf=gOi+" "+VEr,AOi="Nintendo",yOi="PlayStation",zEr="Xbox",Nbf=O9e+" "+P9e,jbf=P9e+" "+f1a,LCt="Windows",Mbf=LCt+" Phone";var g1a="Generic",aNy=g1a+" "+P9e.toLowerCase(),uNy=g1a+" "+p1a.toLowerCase(),Lbf="Konqueror",TP="(\\d+(\\.\\d+)?)",mOi=new RegExp("Version/"+TP),cNy=new RegExp(zEr,"i"),lNy=new RegExp(yOi+" \\w+","i"),pNy=new RegExp(AOi+" \\w+","i"),Ubf=new RegExp(qEr+"|PlayBook|BB10","i"),zbf={"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 fNy={[Fbf]:[new RegExp("rv:"+TP)],[kbf]:[new RegExp(h1a+"?\\/"+TP)],[GEr]:[new RegExp("("+GEr+"|CrMo)\\/"+TP)],[Rbf]:[new RegExp("CriOS\\/"+TP)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+TP)],[f1a]:[mOi],[jbf]:[mOi],[hOi]:[new RegExp("("+hOi+"|OPR)\\/"+TP)],[gOi]:[new RegExp(gOi+"\\/"+TP)],[Qbf]:[new RegExp("FxiOS\\/"+TP)],[Lbf]:[new RegExp("Konqueror[:/]?"+TP,"i")],[qEr]:[new RegExp(qEr+" "+TP),mOi],[Nbf]:[new RegExp("android\\s"+TP,"i")],[Tbf]:[new RegExp(Pbf+"\\/"+TP)],[m1a]:[new RegExp("(rv:|MSIE )"+TP)],Mozilla:[new RegExp("rv:"+TP)]};var dNy=[[new RegExp(zEr+"; "+zEr+" (.*?)[);]","i"),e=>[zEr,e&&e[1]||""]],[new RegExp(AOi,"i"),[AOi,""]],[new RegExp(yOi,"i"),[yOi,""]],[Ubf,[qEr,""]],[new RegExp(LCt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Mbf,""];if(new RegExp(P9e).test(t)&&!/IEMobile\b/.test(t))return[LCt+" "+P9e,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=zbf[n]||"";return/arm/i.test(t)&&(i="RT"),[LCt,i]}return[LCt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[VEr,t.join(".")]}return[VEr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=B9e(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+O9e+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+O9e+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[O9e,t.join(".")]}return[O9e,""]}],[/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/,[Dbf,""]],[/Linux|debian/i,["Linux",""]]];var A1a="utf8";function y1a(e,t){if(!e||typeof e!="string"||Vbf(e))throw new Error(t)}function Vbf(e){return e.trim().length===0}function b1a(e){return e?.replace(/\/+$/,"")}async function E1a(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 WEr(){return new Date().toISOString()}function jPe(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var v1a=e=>e instanceof Error;function bOi(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var $Er=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 I1a(){return"CompressionStream"in globalThis}async function EOi(e,t=!0){try{let n=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(n).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var MPe=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},T9e=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function w1a(e){if(e instanceof MPe){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function vOi(e){return typeof e=="object"&&(e instanceof MPe||e instanceof T9e)}function C1a(e){return typeof e=="object"&&e instanceof MPe&&e.status===413}var UCt=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new UEr,this._events=new $Er,this._isInitialized=!1,y1a(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=b1a(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:vOi},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=l1a("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!I1a()||(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(yF.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(yF.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(yF.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!0){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:aOi(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof MPe)return{type:"api_error",statusCode:t.status};if(t instanceof T9e){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 u=QCt(a.response);return u===void 0&&(u=!1),{response:u,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 u=a[t];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={};(o??this.disableGeoip)&&(a.geoip_disable=!0),s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(t,r,n,i,a);if(!u.success)return;let c=u.response;return c.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"),c.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:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(yF.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(yF.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(yF.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(yF.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(yF.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=jPe(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:WEr()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,u=this.disableCompression?null:await EOi(s,this.isDebug),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||s};try{await this.fetchWithRetry(a,c)}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:WEr(),uuid:n?.uuid?n.uuid:iK()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await w1a(t)})}async flush(){let t=bOi([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),bOi([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(yF.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(yF.Queue)||[]).slice(i.length);this.setPersistedProperty(yF.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:WEr()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),c=`${this.host}/batch/`,l=this.disableCompression?null:await EOi(u,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||u},d={retryCheck:f=>C1a(f)?!1:vOi(f)};try{await this.fetchWithRetry(c,p,d)}catch(f){if(C1a(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof T9e||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){AbortSignal.timeout??=function(a){let u=new AbortController;return setTimeout(()=>u.abort(),a),u.signal};let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,A1a)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await E1a(async()=>{let a=null;try{a=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(c){throw new T9e(c)}if(!(r.mode==="no-cors")&&(a.status<200||a.status>=400))throw new MPe(a,s);return a},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(yF.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!vOi(i))throw i;await w1a(i)}};return Promise.race([new Promise((i,o)=>{jPe(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}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 bF={};Y(bF,{DOMExceptionCoercer:()=>xOi,ErrorCoercer:()=>_Oi,ErrorEventCoercer:()=>SOi,ErrorPropertiesBuilder:()=>IOi,EventCoercer:()=>POi,ObjectCoercer:()=>OOi,PrimitiveCoercer:()=>TOi,PromiseRejectionEventCoercer:()=>DOi,ReduceableCache:()=>ROi,StringCoercer:()=>BOi,chromeStackLineParser:()=>wOi,createDefaultStackParser:()=>i0f,createStackParser:()=>k1a,geckoStackLineParser:()=>COi,nodeStackLineParser:()=>T1a,opera10StackLineParser:()=>B1a,opera11StackLineParser:()=>O1a,reverseAndStripFrames:()=>F1a,winjsStackLineParser:()=>S1a});var HEr,x1a,KEr;function _1a(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return KEr&&r.length===x1a||(x1a=r.length,KEr=r.reduce((n,i)=>{HEr||(HEr={});let o=HEr[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=t[i];if(c&&l){n[c]=l,HEr[i]=[c,l];break}}}return n},{})),KEr}var Gbf=4,IOi=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),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&pOi(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:_1a(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=Gbf){let u=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,u)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var n1="?";function oK(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?n1:r,in_app:!0};return B9e(n)||(o.lineno=n),B9e(i)||(o.colno=i),o}var JEr=(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]:n1,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Wbf=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,$bf=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Hbf=/\((\S*)(?::(\d+))(?::(\d+))\)/,wOi=(e,t)=>{let r=Wbf.exec(e);if(r){let[,i,o,s]=r;return oK(t,i,n1,+o,+s)}let n=$bf.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Hbf.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=JEr(n[1]||n1,n[2]);return oK(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Kbf=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Jbf=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,COi=(e,t)=>{let r=Kbf.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=Jbf.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]||n1;return[o,i]=JEr(o,i),oK(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Ybf=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,S1a=(e,t)=>{let r=Ybf.exec(e);return r?oK(t,r[2],r[1]||n1,+r[3],r[4]?+r[4]:void 0):void 0};var Xbf=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,B1a=(e,t)=>{let r=Xbf.exec(e);return r?oK(t,r[2],r[3]||n1,+r[1]):void 0},Zbf=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,O1a=(e,t)=>{let r=Zbf.exec(e);return r?oK(t,r[5],r[3]||r[4]||n1,+r[1],+r[2]):void 0};var e0f=/^\s*[-]{4,}$/,t0f=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,T1a=(e,t)=>{let r=e.match(t0f);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||n1,o=s?`${s}.${a}`:a);let u=r[2]?.startsWith("file://")?r[2].slice(7):r[2],c=r[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&r[5]&&!c&&(u=r[5]),{filename:u?decodeURI(u):void 0,module:void 0,function:o,lineno:P1a(r[3]),colno:P1a(r[4]),in_app:r0f(u||"",c),platform:t}}if(e.match(e0f))return{filename:e,platform:t}};function r0f(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 P1a(e){return parseInt(e||"",10)||void 0}var D1a=/\(error: (.*)\)/,R1a=50;function F1a(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,R1a).map(r=>({...r,filename:r.filename||n0f(t).filename,function:r.function||n1}))}function n0f(e){return e[e.length-1]||{}}function i0f(){return k1a("web:javascript",wOi,COi)}function k1a(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
1656
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let u=D1a.test(a)?a.replace(D1a,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of t){let l=c(u,e);if(l){i.push(l);break}}if(i.length>=R1a)break}}return F1a(i)}}var xOi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=NCt(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 NPe(t,"DOMException")}isDOMError(t){return NPe(t,"DOMError")}};var _Oi=class{match(t){return dOi(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var SOi=class{constructor(){}match(t){return a1a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var o0f=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,BOi=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(o0f);return i&&(r=i[1],n=i[2]),[r,n]}};var Q1a=["fatal","error","warning","log","info","debug"];function YEr(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 OOi=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return MEr(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=YEr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return NCt(t)&&!o1a(t)&&Q1a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(v1a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var POi=class{match(t){return MEr(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${YEr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var TOi=class{match(t){return jCt(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var DOi=class{match(t){return NPe(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return jCt(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(jCt(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var ROi=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 M1a=require("fs"),L1a=require("readline"),XEr=new bF.ReduceableCache(25),U1a=new bF.ReduceableCache(20),FOi=7,s0f=1e3,a0f=1e4;async function z1a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||p0f(s)||f0f(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(U1a.get(i))continue;let o=t[i];if(!o)continue;o.sort((u,c)=>u-c);let s=m0f(o);if(s.every(u=>d0f(i,u)))continue;let a=h0f(XEr,i,{});n.push(u0f(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&c0f(e,XEr),XEr.reduce(),e}function u0f(e,t,r){return new Promise(n=>{let i=(0,M1a.createReadStream)(e),o=(0,L1a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,u=0,c=t[u];if(c===void 0)return void s();let l=c[0],p=c[1];function d(){U1a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=g0f(f,0),a>=p)){if(u===t.length-1){o.close(),o.removeAllListeners();return}u++;let m=t[u];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function c0f(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;l0f(r.lineno,r,n)}}function l0f(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=V1a(e);i<e;i++){let o=r[i];if(o===void 0)return void N1a(t);t.pre_context.push(o)}if(r[e]===void 0)return void N1a(t);t.context_line=r[e];let n=q1a(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 N1a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function p0f(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function f0f(e){return e.lineno!==void 0&&e.lineno>a0f||e.colno!==void 0&&e.colno>s0f}function d0f(e,t){let r=XEr.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 m0f(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=j1a(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+FOi:(i.push(n),n=j1a(o)),t++}return i}function j1a(e){return[V1a(e),q1a(e)]}function V1a(e){return Math.max(1,e-FOi)}function q1a(e){return e+FOi}function h0f(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function g0f(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function A0f(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function G1a(e,t){globalThis.process?.on("uncaughtException",A0f(e,t))}function W1a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var y0f=2e3,iV=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new LEr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return fOi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n||iK(),properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(G1a(this.onException.bind(this),this.onFatalError.bind(this)),W1a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(y0f),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var $1a="5.26.2";var zCt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function H1a(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var b0f=6e4,E0f=1152921504606847e3,v0f=["is_not"],D9e=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},ah=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},sK=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ZEr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let u=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(c){c instanceof sK||c instanceof ah?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(i[u.key]=l)}catch(c){c instanceof sK||c instanceof ah?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new ah("Flag has experience continuity enabled");if(!t.active)return!1;let u=(t.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${t.key}`)),new ah("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[c];return await this.matchFeatureFlagProperties(t,i[c],l,r)}{let c=this.getBucketingValueForFlag(t,n,o);if(c===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 ah(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,c,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new ah("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new ah(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new ah(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new ah(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let u of s){if(!(u in i)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[u]=p}catch(p){throw new ah(`Error evaluating flag dependency '${u}' for flag '${o}': ${p}`)}else i[u]=!1;else throw new ah(`Missing flag dependency '${u}' for flag '${o}'`)}if(i[u]==null)throw new ah(`Dependency '${u}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,u;for(let c of s)try{if(await this.isConditionMatch(t,r,c,n,i)){let l=c.variant,p=o.multivariate?.variants||[];u=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof sK)throw l;if(l instanceof ah)a=!0;else throw l}if(u!==void 0)return u;if(a)throw new ah("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(l=c==="cohort"?Z1a(u,i,this.cohorts,this.debugMode):c==="flag"?await this.evaluateFlagDependency(u,i,o):X1a(u,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await K1a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await K1a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(b0f,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new D9e(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new D9e(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new D9e(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof D9e&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=jPe(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function K1a(e,t,r=""){let n=await H1a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/E0f}function X1a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new ah("Operator is_not_set is not supported")}else throw new ah(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!v0f.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return J1a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return J1a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof i=="number"?i:null;if(typeof i=="string")try{c=parseFloat(i)}catch{}return c==null||s==null?u(String(s),String(i),o):typeof s=="string"?u(s,String(i),o):u(s,c,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new ah("Date operations cannot be performed on boolean values");let c=w0f(String(i));if(c==null&&(c=Y1a(i)),c==null)throw new ah(`Invalid date: ${i}`);let l=Y1a(s);return["is_date_before"].includes(o)?l<c:l>c}default:throw new ah(`Unknown operator: ${o}`)}}function I0f(e,t){if(!(e in t))throw new sK(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z1a(e,t,r,n=!1){let i=String(e.value);I0f(i,r);let o=r[i];return eSa(o,t,r,n)}function eSa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let u=eSa(a,t,r,n);if(i==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof sK)throw u;if(u instanceof ah)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new ah("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let u;if(a.type==="cohort")u=Z1a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else u=X1a(a,t);let c=a.negation||!1;if(i==="AND"){if(!u&&!c||u&&c)return!1}else if(u&&!c||!u&&c)return!0}catch(u){if(u instanceof sK)throw u;if(u instanceof ah)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new ah("can't match cohort without a given cohort property value");return i==="AND"}function J1a(e){try{return new RegExp(e),!0}catch{return!1}}function Y1a(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 ah(`${e} is in an invalid date format`)}throw new ah(`The date provided ${e} must be a string, number, or date object`)}function w0f(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var evr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var C0f=100,tSa=3e4,x0f=5e4,tvr=class extends UCt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new evr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,C0f):tSa,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new ZEr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new iV(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||x0f}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return $1a}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=tSa){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,E,v,b;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;E=w.id,b="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof sK||x instanceof ah)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!u){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=zCt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(zCt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(zCt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(zCt.FLAG_MISSING);else{E=C.metadata?.id,v=C.metadata?.version,b=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:E,$feature_flag_version:v,$feature_flag_reason:b,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!u){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=jPe(()=>{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(u1a(s)&&r&&o in r){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!iV.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(iV.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!iV.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(iV.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=iK(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,u,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[E,v]of Object.entries(h))g[`$feature/${E}`]=v;let A=Object.keys(h||{}).filter(E=>h?.[E]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&n1a(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var rSa=require("async_hooks"),rvr=class{constructor(){this.storage=new rSa.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 nSa="posthog-node";function _0f(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 u=s.tags[kOi.POSTHOG_ID_TAG];if(u===void 0)return s;let c=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:u,properties:f}),s}}var kOi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=nSa,this.name=nSa,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(_0f(t,{organization:r,projectId:u,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};iV.errorPropertiesBuilder=new bF.ErrorPropertiesBuilder([new bF.EventCoercer,new bF.ErrorCoercer,new bF.ObjectCoercer,new bF.StringCoercer,new bF.PrimitiveCoercer],bF.createStackParser("node:javascript",bF.nodeStackLineParser),[Z_a(),z1a]);var R9e=class extends tvr{getLibraryId(){return"posthog-node"}initializeContext(){return new rvr}};var nvr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new R9e(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.31.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var VCt=class{async sendEvent(){}async identify(){}async flush(){}};Vt();var F9e=require("fs/promises"),iSa=require("os"),oSa=require("path");var S0f="id",B0f=".fern",qCt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new R9e(r),this.userId=t==null?void 0:Xwi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"4.31.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 FA({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=We(Ut.of((0,iSa.homedir)()),Se.of(B0f),Se.of(S0f));await Xt(t)||(await(0,F9e.mkdir)((0,oSa.dirname)(t),{recursive:!0}),await(0,F9e.writeFile)(t,mC())),this.persistedDistinctId=(await(0,F9e.readFile)(t)).toString()}return this.persistedDistinctId}};var QOi;async function k9e(){return QOi==null&&(QOi=await O0f()),QOi}async function O0f(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new VCt;let r=await ghr();return r!=null?new qCt({token:r,posthogApiKey:e}):await UH()!=null?new nvr({posthogApiKey:e}):new qCt({token:void 0,posthogApiKey:e})}catch{return new VCt}}Qt();var GCt=_e(require("process"),1);rNe();var uSa=_e(oAi(),1),cSa=_e(aSa(),1);function TC(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=h5(e),e.length===0))return 0;e=e.replace((0,cSa.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(uSa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function ivr(e){let t=0;for(let r of e.split(`
1656
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let u=D1a.test(a)?a.replace(D1a,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of t){let l=c(u,e);if(l){i.push(l);break}}if(i.length>=R1a)break}}return F1a(i)}}var xOi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=NCt(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 NPe(t,"DOMException")}isDOMError(t){return NPe(t,"DOMError")}};var _Oi=class{match(t){return dOi(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var SOi=class{constructor(){}match(t){return a1a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var o0f=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,BOi=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(o0f);return i&&(r=i[1],n=i[2]),[r,n]}};var Q1a=["fatal","error","warning","log","info","debug"];function YEr(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 OOi=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return MEr(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=YEr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return NCt(t)&&!o1a(t)&&Q1a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(v1a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var POi=class{match(t){return MEr(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${YEr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var TOi=class{match(t){return jCt(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var DOi=class{match(t){return NPe(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return jCt(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(jCt(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var ROi=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 M1a=require("fs"),L1a=require("readline"),XEr=new bF.ReduceableCache(25),U1a=new bF.ReduceableCache(20),FOi=7,s0f=1e3,a0f=1e4;async function z1a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||p0f(s)||f0f(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(U1a.get(i))continue;let o=t[i];if(!o)continue;o.sort((u,c)=>u-c);let s=m0f(o);if(s.every(u=>d0f(i,u)))continue;let a=h0f(XEr,i,{});n.push(u0f(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&c0f(e,XEr),XEr.reduce(),e}function u0f(e,t,r){return new Promise(n=>{let i=(0,M1a.createReadStream)(e),o=(0,L1a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,u=0,c=t[u];if(c===void 0)return void s();let l=c[0],p=c[1];function d(){U1a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=g0f(f,0),a>=p)){if(u===t.length-1){o.close(),o.removeAllListeners();return}u++;let m=t[u];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function c0f(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;l0f(r.lineno,r,n)}}function l0f(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=V1a(e);i<e;i++){let o=r[i];if(o===void 0)return void N1a(t);t.pre_context.push(o)}if(r[e]===void 0)return void N1a(t);t.context_line=r[e];let n=q1a(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 N1a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function p0f(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function f0f(e){return e.lineno!==void 0&&e.lineno>a0f||e.colno!==void 0&&e.colno>s0f}function d0f(e,t){let r=XEr.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 m0f(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=j1a(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+FOi:(i.push(n),n=j1a(o)),t++}return i}function j1a(e){return[V1a(e),q1a(e)]}function V1a(e){return Math.max(1,e-FOi)}function q1a(e){return e+FOi}function h0f(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function g0f(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function A0f(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function G1a(e,t){globalThis.process?.on("uncaughtException",A0f(e,t))}function W1a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var y0f=2e3,iV=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new LEr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return fOi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n||iK(),properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(G1a(this.onException.bind(this),this.onFatalError.bind(this)),W1a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(y0f),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var $1a="5.26.2";var zCt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function H1a(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var b0f=6e4,E0f=1152921504606847e3,v0f=["is_not"],D9e=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},ah=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},sK=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ZEr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let u=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(c){c instanceof sK||c instanceof ah?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(i[u.key]=l)}catch(c){c instanceof sK||c instanceof ah?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new ah("Flag has experience continuity enabled");if(!t.active)return!1;let u=(t.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${t.key}`)),new ah("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[c];return await this.matchFeatureFlagProperties(t,i[c],l,r)}{let c=this.getBucketingValueForFlag(t,n,o);if(c===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 ah(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,c,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new ah("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new ah(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new ah(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new ah(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let u of s){if(!(u in i)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[u]=p}catch(p){throw new ah(`Error evaluating flag dependency '${u}' for flag '${o}': ${p}`)}else i[u]=!1;else throw new ah(`Missing flag dependency '${u}' for flag '${o}'`)}if(i[u]==null)throw new ah(`Dependency '${u}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,u;for(let c of s)try{if(await this.isConditionMatch(t,r,c,n,i)){let l=c.variant,p=o.multivariate?.variants||[];u=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof sK)throw l;if(l instanceof ah)a=!0;else throw l}if(u!==void 0)return u;if(a)throw new ah("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(l=c==="cohort"?Z1a(u,i,this.cohorts,this.debugMode):c==="flag"?await this.evaluateFlagDependency(u,i,o):X1a(u,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await K1a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await K1a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(b0f,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new D9e(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new D9e(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new D9e(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof D9e&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=jPe(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function K1a(e,t,r=""){let n=await H1a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/E0f}function X1a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new ah("Operator is_not_set is not supported")}else throw new ah(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!v0f.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return J1a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return J1a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof i=="number"?i:null;if(typeof i=="string")try{c=parseFloat(i)}catch{}return c==null||s==null?u(String(s),String(i),o):typeof s=="string"?u(s,String(i),o):u(s,c,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new ah("Date operations cannot be performed on boolean values");let c=w0f(String(i));if(c==null&&(c=Y1a(i)),c==null)throw new ah(`Invalid date: ${i}`);let l=Y1a(s);return["is_date_before"].includes(o)?l<c:l>c}default:throw new ah(`Unknown operator: ${o}`)}}function I0f(e,t){if(!(e in t))throw new sK(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z1a(e,t,r,n=!1){let i=String(e.value);I0f(i,r);let o=r[i];return eSa(o,t,r,n)}function eSa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let u=eSa(a,t,r,n);if(i==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof sK)throw u;if(u instanceof ah)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new ah("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let u;if(a.type==="cohort")u=Z1a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else u=X1a(a,t);let c=a.negation||!1;if(i==="AND"){if(!u&&!c||u&&c)return!1}else if(u&&!c||!u&&c)return!0}catch(u){if(u instanceof sK)throw u;if(u instanceof ah)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new ah("can't match cohort without a given cohort property value");return i==="AND"}function J1a(e){try{return new RegExp(e),!0}catch{return!1}}function Y1a(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 ah(`${e} is in an invalid date format`)}throw new ah(`The date provided ${e} must be a string, number, or date object`)}function w0f(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var evr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var C0f=100,tSa=3e4,x0f=5e4,tvr=class extends UCt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new evr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,C0f):tSa,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new ZEr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new iV(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||x0f}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return $1a}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=tSa){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,E,v,b;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;E=w.id,b="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof sK||x instanceof ah)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!u){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=zCt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(zCt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(zCt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(zCt.FLAG_MISSING);else{E=C.metadata?.id,v=C.metadata?.version,b=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:E,$feature_flag_version:v,$feature_flag_reason:b,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!u){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=jPe(()=>{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(u1a(s)&&r&&o in r){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!iV.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(iV.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!iV.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(iV.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=iK(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,u,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[E,v]of Object.entries(h))g[`$feature/${E}`]=v;let A=Object.keys(h||{}).filter(E=>h?.[E]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&n1a(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var rSa=require("async_hooks"),rvr=class{constructor(){this.storage=new rSa.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 nSa="posthog-node";function _0f(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 u=s.tags[kOi.POSTHOG_ID_TAG];if(u===void 0)return s;let c=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:u,properties:f}),s}}var kOi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=nSa,this.name=nSa,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(_0f(t,{organization:r,projectId:u,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};iV.errorPropertiesBuilder=new bF.ErrorPropertiesBuilder([new bF.EventCoercer,new bF.ErrorCoercer,new bF.ObjectCoercer,new bF.StringCoercer,new bF.PrimitiveCoercer],bF.createStackParser("node:javascript",bF.nodeStackLineParser),[Z_a(),z1a]);var R9e=class extends tvr{getLibraryId(){return"posthog-node"}initializeContext(){return new rvr}};var nvr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new R9e(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.31.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var VCt=class{async sendEvent(){}async identify(){}async flush(){}};Vt();var F9e=require("fs/promises"),iSa=require("os"),oSa=require("path");var S0f="id",B0f=".fern",qCt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new R9e(r),this.userId=t==null?void 0:Xwi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"4.31.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 FA({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=We(Ut.of((0,iSa.homedir)()),Se.of(B0f),Se.of(S0f));await Xt(t)||(await(0,F9e.mkdir)((0,oSa.dirname)(t),{recursive:!0}),await(0,F9e.writeFile)(t,mC())),this.persistedDistinctId=(await(0,F9e.readFile)(t)).toString()}return this.persistedDistinctId}};var QOi;async function k9e(){return QOi==null&&(QOi=await O0f()),QOi}async function O0f(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new VCt;let r=await ghr();return r!=null?new qCt({token:r,posthogApiKey:e}):await UH()!=null?new nvr({posthogApiKey:e}):new qCt({token:void 0,posthogApiKey:e})}catch{return new VCt}}Qt();var GCt=_e(require("process"),1);rNe();var uSa=_e(oAi(),1),cSa=_e(aSa(),1);function TC(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=h5(e),e.length===0))return 0;e=e.replace((0,cSa.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(uSa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function ivr(e){let t=0;for(let r of e.split(`
1657
1657
  `))t=Math.max(t,TC(r));return t}var OSa=_e(jOi(),1);var T0f=/[\p{Lu}]/u,D0f=/[\p{Ll}]/u,fSa=/^[\p{Lu}](?![\p{Lu}])/gu,hSa=/([\p{Alpha}\p{N}_]|$)/u,MOi=/[_.\- ]+/,R0f=new RegExp("^"+MOi.source),dSa=new RegExp(MOi.source+hSa.source,"gu"),mSa=new RegExp("\\d+"+hSa.source,"gu"),F0f=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let u=0;u<e.length;u++){let c=e[u];a=u>2?e[u-3]==="-":!0,i&&T0f.test(c)?(e=e.slice(0,u)+"-"+e.slice(u),i=!1,s=o,o=!0,u++):o&&s&&D0f.test(c)&&(!a||n)?(e=e.slice(0,u-1)+"-"+e.slice(u-1),s=o,o=!1,i=!0):(i=t(c)===c&&r(c)!==c,s=o,o=r(c)===c&&t(c)!==c)}return e},k0f=(e,t)=>(fSa.lastIndex=0,e.replace(fSa,r=>t(r))),Q0f=(e,t)=>(dSa.lastIndex=0,mSa.lastIndex=0,e.replace(dSa,(r,n)=>t(n)).replace(mSa,r=>t(r)));function LOi(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?MOi.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=F0f(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(R0f,""),e=t.preserveConsecutiveUppercase?k0f(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Q0f(e,n))}var qOi=_e(ASa(),1);rNe();var ySa=(e=0)=>t=>`\x1B[${t+e}m`,bSa=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,ESa=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,Iy={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]}},v4y=Object.keys(Iy.modifier),L0f=Object.keys(Iy.color),U0f=Object.keys(Iy.bgColor),I4y=[...L0f,...U0f];function z0f(){let e=new Map;for(let[t,r]of Object.entries(Iy)){for(let[n,i]of Object.entries(r))Iy[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Iy[n],e.set(i[0],i[1]);Object.defineProperty(Iy,t,{value:r,enumerable:!1})}return Object.defineProperty(Iy,"codes",{value:e,enumerable:!1}),Iy.color.close="\x1B[39m",Iy.bgColor.close="\x1B[49m",Iy.color.ansi=ySa(),Iy.color.ansi256=bSa(),Iy.color.ansi16m=ESa(),Iy.bgColor.ansi=ySa(10),Iy.bgColor.ansi256=bSa(10),Iy.bgColor.ansi16m=ESa(10),Object.defineProperties(Iy,{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=>Iy.rgbToAnsi256(...Iy.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)=>Iy.ansi256ToAnsi(Iy.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>Iy.ansi256ToAnsi(Iy.hexToAnsi256(t)),enumerable:!1}}),Iy}var V0f=z0f(),vSa=V0f;var ovr=new Set(["\x1B","\x9B"]),q0f=39,zOi="\x07",CSa="[",G0f="]",xSa="m",VOi=`${G0f}8;;`,ISa=e=>`${ovr.values().next().value}${CSa}${e}${xSa}`,wSa=e=>`${ovr.values().next().value}${VOi}${e}${zOi}`,W0f=e=>e.split(" ").map(t=>TC(t)),UOi=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=TC(h5(e[e.length-1]));for(let[a,u]of n.entries()){let c=TC(u);if(s+c<=r?e[e.length-1]+=u:(e.push(u),s=0),ovr.has(u)&&(i=!0,o=n.slice(a+1).join("").startsWith(VOi)),i){o?u===zOi&&(i=!1,o=!1):u===xSa&&(i=!1);continue}s+=c,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())},$0f=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(TC(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},H0f=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=W0f(e),a=[""];for(let[c,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=TC(a[a.length-1]);if(c!==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[c]>t){let d=t-p,f=1+Math.floor((s[c]-d-1)/t);Math.floor((s[c]-1)/t)<f&&a.push(""),UOi(a,l,t);continue}if(p+s[c]>t&&p>0&&s[c]>0){if(r.wordWrap===!1&&p<t){UOi(a,l,t);continue}a.push("")}if(p+s[c]>t&&r.wordWrap===!1){UOi(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(c=>$0f(c)));let u=[...a.join(`
1658
1658
  `)];for(let[c,l]of u.entries()){if(n+=l,ovr.has(l)){let{groups:d}=new RegExp(`(?:\\${CSa}(?<code>\\d+)m|\\${VOi}(?<uri>.*)${zOi})`).exec(u.slice(c).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===q0f?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=vSa.codes.get(Number(i));u[c+1]===`
1659
1659
  `?(o&&(n+=wSa("")),i&&p&&(n+=ISa(p))):l===`
@@ -2160,7 +2160,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
2160
2160
  Example: package-name: "@scope/package"`)}return{success:!1,warnings:[{type:"conflict",message:`Failed to parse generators.yml: ${o}`}]}}}checkDeprecatedFields(t,r){t.openapi!=null&&r.push({type:"deprecated",message:"The 'openapi' field is deprecated",suggestion:"Use 'api.specs' instead"}),t["openapi-overrides"]!=null&&r.push({type:"deprecated",message:"The 'openapi-overrides' field is deprecated",suggestion:"Use 'api.specs.[].overrides' instead"}),t["spec-origin"]!=null&&r.push({type:"deprecated",message:"The 'spec-origin' field is deprecated",suggestion:"Use 'api.specs.[].origin' instead"}),t["async-api"]!=null&&r.push({type:"deprecated",message:"The 'async-api' field is deprecated",suggestion:"Use 'api.specs' with asyncapi instead"}),t["api-settings"]!=null&&r.push({type:"deprecated",message:"The 'api-settings' field is deprecated",suggestion:"Use 'api.specs.[].settings' instead"}),t.whitelabel!=null&&r.push({type:"unsupported",message:"Whitelabel configuration is not yet supported in fern.yml"}),t.metadata!=null&&r.push({type:"unsupported",message:"Metadata configuration is not yet supported in fern.yml"}),t.reviewers!=null&&r.push({type:"unsupported",message:"Reviewers configuration is not yet supported in fern.yml"}),t.aliases!=null&&r.push({type:"unsupported",message:"Group aliases are not yet supported in fern.yml",suggestion:"Use multiple group names in target.group array instead"}),t["auth-schemes"]!=null&&r.push({type:"info",message:"Auth schemes configuration detected but not yet migrated",suggestion:"Auth schemes will be supported in a future version"})}async getAbsoluteFilePath(){let t=We(this.cwd,Se.of(Hd)),r=We(this.cwd,Se.of(u4e));if(await Xt(t,"file"))return t;if(await Xt(r,"file"))return r}};var ESt=class{cwd;logger;deleteOriginals;constructor(t){this.cwd=t.cwd,this.logger=t.logger,this.deleteOriginals=t.deleteOriginals??!0}async migrate(){let t=[],r=[],n=await this.findFernDirectory();if(n==null)return{success:!1,warnings:[{type:"conflict",message:"Could not find fern directory",suggestion:"Run this command from a directory containing a 'fern' folder"}],migratedFiles:r};let o=await new bSt({cwd:n}).migrate();if(t.push(...o.warnings),!o.success||o.org==null)return{success:!1,warnings:[...t,{type:"conflict",message:"Failed to migrate fern.config.json - organization is required"}],migratedFiles:r};o.absoluteFilePath!=null&&r.push(o.absoluteFilePath);let s=We(n,Se.of(GO)),a=await Xt(s,"directory"),u;if(a){let p=await this.migrateMultiApi({fernDir:n,apisDir:s,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};u=p.fernYml}else{let p=await this.migrateSingleApi({fernDir:n,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};u=p.fernYml}let c=We(this.cwd,Se.of(A1)),l=this.serializeFernYml(u);if(await(0,lrt.writeFile)(c,l,"utf-8"),this.deleteOriginals)for(let p of r)try{await(0,lrt.rm)(p),this.logger.debug(`Deleted ${p}`)}catch{t.push({type:"info",message:`Could not delete ${p}`})}return this.logger.info(`Created ${c}`),{success:!0,warnings:t,migratedFiles:r,outputPath:c}}async migrateSingleApi(t){let{fernDir:r,org:n,warnings:i,migratedFiles:o}=t,a=await new CDe({cwd:r}).migrate();i.push(...a.warnings),a.absoluteFilePath!=null&&o.push(a.absoluteFilePath);let u=await _5i({fernDir:r,generatorsYmlApi:a.rawApi});i.push(...u.warnings);let c={org:n};return u.api!=null&&(c.api=u.api),a.sdks!=null&&(c.sdks=a.sdks),{success:!0,fernYml:c}}async migrateMultiApi(t){let{fernDir:r,apisDir:n,org:i,warnings:o,migratedFiles:s}=t,u=(await(0,lrt.readdir)(n,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>A.name);if(u.length===0)return o.push({type:"conflict",message:"No API directories found in fern/apis/"}),{success:!1,fernYml:{org:i}};let c={},l={targets:{}},p,d;for(let A of u){let E=We(n,Se.of(A)),b=await new CDe({cwd:E,apiName:A}).migrate();if(o.push(...b.warnings),b.absoluteFilePath!=null&&s.push(b.absoluteFilePath),c[A]=b.rawApi,b.sdks!=null){for(let[I,w]of Object.entries(b.sdks.targets))l.targets[I]=w;b.sdks.defaultGroup!=null&&p==null&&(p=b.sdks.defaultGroup),b.sdks.autorelease!=null&&d==null&&(d=b.sdks.autorelease)}}let f=await S5i({fernDir:r,apisDir:n,generatorsYmlApis:c});o.push(...f.warnings);let m={org:i,apis:f.apis};Object.keys(l.targets).length>0&&(p!=null&&(l.defaultGroup=p),d!=null&&(l.autorelease=d),m.sdks=l);let g=await new CDe({cwd:r}).detect();return g.found&&g.absoluteFilePath!=null&&(o.push({type:"info",message:"Found generators.yml in fern root alongside apis/ directory",suggestion:"Review the migrated configuration to ensure it's correct"}),s.push(g.absoluteFilePath)),{success:!0,fernYml:m}}async findFernDirectory(){if(this.cwd.split("/").pop()===$h)return this.cwd;let r=We(this.cwd,Se.of($h));if(await Xt(r,"directory"))return r}serializeFernYml(t){let r={edition:t.edition,org:t.org};return t.api!=null&&(r.api=t.api),t.apis!=null&&(r.apis=t.apis),t.ai!=null&&(r.ai=t.ai),t.cli!=null&&(r.cli=t.cli),t.sdks!=null&&(r.sdks=this.simplifySdks(t.sdks)),wr.dump(r,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1})}simplifySdks(t){let r={...t},n={};for(let[i,o]of Object.entries(t.targets)){let s=o.output;if(typeof s=="string"){n[i]=o;continue}if(s.git==null&&s.path!=null){n[i]={...o,output:s.path};continue}n[i]=o}return r.targets=n,r}};var B5i=class{async handle(t,r){let i=await new ESt({cwd:t.cwd,logger:t.stdout,deleteOriginals:r.delete}).migrate();for(let o of i.warnings){switch(o.type){case"deprecated":t.stdout.warn(`Deprecated: ${o.message}`);break;case"unsupported":t.stdout.warn(`Unsupported: ${o.message}`);break;case"conflict":t.stderr.error(`Error: ${o.message}`);break;case"info":t.stdout.info(o.message);break}o.suggestion!=null&&t.stdout.info(` Suggestion: ${o.suggestion}`)}if(i.success){i.outputPath!=null&&t.stdout.debug(`Created: ${i.outputPath}`);return}throw new gn({message:"Migration failed"})}};function O5i(e,t){let r=new B5i;qa(e,"migrate","Migrate legacy configuration files to fern.yml",(n,i)=>r.handle(n,i),n=>n.option("delete",{type:"boolean",description:"Keep original files after migration",default:!0}),t)}function P5i(e){U1(e,"config","Configure, edit, and inspect your settings",[O5i])}var T5i=class{async handle(t,r){let n=await t.loadWorkspaceOrThrow();if(n.docs==null)throw new gn({message:`No docs configuration found in fern.yml.
2161
2161
 
2162
2162
  Add a 'docs:' section to your fern.yml to get started.`});let o=await new fve({context:t}).check({workspace:n,strict:r.strict}),s=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let a=this.buildJsonResponse({result:o,hasErrors:s});if(t.stdout.info(JSON.stringify(a,null,2)),s)throw gn.exit();return}if(o.violations.length>0)for(let a of o.violations){let u=a.severity==="warning"?Ie.yellow:Ie.red;process.stderr.write(`${u(`${a.displayRelativeFilepath}:${a.line}:${a.column}: ${a.message}`)}
2163
- `)}if(s)throw gn.exit();if(o.warningCount>0){t.stderr.info(`${ns.warning} ${Ie.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(Ie.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${ns.success} ${Ie.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>fK(i))),{success:!r,results:n}}};function D5i(e,t){let r=new T5i;qa(e,"check","Validate docs configuration",(n,i)=>r.handle(n,i),n=>n.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}),t)}var BWa=_e(require("net"),1),OWa=_e(require("os"),1),I0n=class extends Error{constructor(t){super(`${t} is locked`)}},prt={old:new Set,young:new Set},jKf=1e3*15;var vSt,MKf=()=>{let e=OWa.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},_Wa=e=>new Promise((t,r)=>{let n=BWa.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),SWa=async(e,t)=>{if(e.host||e.port===0)return _Wa(e);for(let r of t)try{await _Wa({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},LKf=function*(e){e&&(yield*e),yield 0};async function dve(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}vSt===void 0&&(vSt=setTimeout(()=>{vSt=void 0,prt.old=prt.young,prt.young=new Set},jKf),vSt.unref&&vSt.unref());let n=MKf();for(let i of LKf(t))try{if(r.has(i))continue;let o=await SWa({...e,port:i},n);for(;prt.old.has(o)||prt.young.has(o);){if(i!==0)throw new I0n(i);o=await SWa({...e,port:i},n)}return prt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof I0n))throw o}throw new Error("No available ports found")}_g();Vt();var Wiu=_e(k5i(),1),$iu=_e(uEn(),1),Wvn=require("fs/promises"),Hiu=_e(require("http"),1),Kiu=_e(require("path"),1);var SYa=require("events"),dEn=_e(require("fs"),1),FDe=_e(require("path"),1);var cYa=_e(require("os"),1),lYa=300,Eve=20,WSt=1e7,pYa=cYa.default.platform();var tnd=pYa==="darwin",e6i=pYa==="win32",vve=tnd||e6i,fYa=3e3,dYa=2e4,t6i=1250;var FX;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(FX||(FX={}));var RDe;(function(e){e.CHANGE="change",e.RENAME="rename"})(RDe||(RDe={}));var $St;(function(e){e.CHANGE="change",e.ERROR="error"})($St||($St={}));var Za;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Za||(Za={}));var kT;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(kT||(kT={}));var rnd=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,u=0,c=0,l=()=>{let b=Date.now(),I=b-u,w=b-c,x=I>=t||w>=o;return[b,x]},p=b=>{if(c=b,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{E(0)},f=()=>{a&&(d(),p(Date.now()))},m=b=>{if(c=b,n)return p(b)},h=b=>{if(i&&s)return p(b);s=void 0},g=()=>{a=void 0;let[b,I]=l();return I?h(b):A(b)},A=b=>{let I=b-u,w=b-c,x=t-I,C=o-w,_=Math.min(x,C);return E(_)},E=b=>{a&&clearTimeout(a),!(b<=0)&&(a=setTimeout(g,b))},v=(...b)=>{let[I,w]=l(),x=!!a;if(s=b,u=I,(w||!a)&&E(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},cEn=rnd;var o6i=_e(require("fs"),1),pEn=_e(require("path"),1);var vf=_e(require("fs"),1),y1=require("util");var cae=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},kX=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var r6i=_e(require("process"),1),mYa=r6i.default.getuid?!r6i.default.getuid():!1,hYa=1e4,Bk=()=>{};var HSt={isChangeErrorOk:e=>{if(!HSt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mYa&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!HSt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!HSt.isNodeError(e))throw e;if(!HSt.isChangeErrorOk(e))throw e}},CE=HSt;var n6i=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=hYa,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gYa=new n6i;var lae=(e,t)=>function(n){return function i(...o){return gYa.schedule().then(s=>{let a=c=>(s(),c),u=c=>{if(s(),Date.now()>=n)throw c;if(t(c)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw c};return e.apply(void 0,o).then(a,u)})}},pae=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var nnd={attempt:{chmod:cae((0,y1.promisify)(vf.default.chmod),CE.onChangeError),chown:cae((0,y1.promisify)(vf.default.chown),CE.onChangeError),close:cae((0,y1.promisify)(vf.default.close),Bk),fsync:cae((0,y1.promisify)(vf.default.fsync),Bk),mkdir:cae((0,y1.promisify)(vf.default.mkdir),Bk),realpath:cae((0,y1.promisify)(vf.default.realpath),Bk),stat:cae((0,y1.promisify)(vf.default.stat),Bk),unlink:cae((0,y1.promisify)(vf.default.unlink),Bk),chmodSync:kX(vf.default.chmodSync,CE.onChangeError),chownSync:kX(vf.default.chownSync,CE.onChangeError),closeSync:kX(vf.default.closeSync,Bk),existsSync:kX(vf.default.existsSync,Bk),fsyncSync:kX(vf.default.fsync,Bk),mkdirSync:kX(vf.default.mkdirSync,Bk),realpathSync:kX(vf.default.realpathSync,Bk),statSync:kX(vf.default.statSync,Bk),unlinkSync:kX(vf.default.unlinkSync,Bk)},retry:{close:lae((0,y1.promisify)(vf.default.close),CE.isRetriableError),fsync:lae((0,y1.promisify)(vf.default.fsync),CE.isRetriableError),open:lae((0,y1.promisify)(vf.default.open),CE.isRetriableError),readFile:lae((0,y1.promisify)(vf.default.readFile),CE.isRetriableError),rename:lae((0,y1.promisify)(vf.default.rename),CE.isRetriableError),stat:lae((0,y1.promisify)(vf.default.stat),CE.isRetriableError),write:lae((0,y1.promisify)(vf.default.write),CE.isRetriableError),writeFile:lae((0,y1.promisify)(vf.default.writeFile),CE.isRetriableError),closeSync:pae(vf.default.closeSync,CE.isRetriableError),fsyncSync:pae(vf.default.fsyncSync,CE.isRetriableError),openSync:pae(vf.default.openSync,CE.isRetriableError),readFileSync:pae(vf.default.readFileSync,CE.isRetriableError),renameSync:pae(vf.default.renameSync,CE.isRetriableError),statSync:pae(vf.default.statSync,CE.isRetriableError),writeSync:pae(vf.default.writeSync,CE.isRetriableError),writeFileSync:pae(vf.default.writeFileSync,CE.isRetriableError)}},AYa=nnd;var lEn=_e(require("fs"),1),KSt=_e(require("path"),1);var i6i=()=>{};var ind=()=>{let e=i6i,t=i6i,r=!1,n=!1;return{promise:new Promise((u,c)=>{e=l=>(r=!0,u(l)),t=l=>(n=!0,c(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},yYa=ind;var ond=()=>{let{promise:e,resolve:t,isPending:r}=yYa(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},bYa=ond;var EYa={then:e=>{e()}};var vYa=e=>Array.isArray(e)?e:[e],IYa=e=>typeof e=="function";var snd=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=vYa(o).map(J=>IYa(J)?J:H=>J.test(H)),a=J=>s.some(H=>H(J)),u=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,E={},v={},b=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:E,map:v},{promise:x,increment:C,decrement:_}=bYa(),R=0,U=(J,H,ge,me)=>{b.has(H)||R>=i||(R+=1,J.directories.push(H),J.directoriesNames.add(ge),l.push(H),p.add(ge),d.propertyIsEnumerable(ge)||(d[ge]=[]),d[ge].push(H),b.add(H),!(me>=n)&&(R>=i||K(H,me+1)))},q=(J,H,ge)=>{b.has(H)||R>=i||(R+=1,J.files.push(H),J.filesNames.add(ge),f.push(H),m.add(ge),h.propertyIsEnumerable(ge)||(h[ge]=[]),h[ge].push(H),b.add(H))},z=(J,H,ge,me)=>{b.has(H)||R>=i||(R+=1,J.symlinks.push(H),J.symlinksNames.add(ge),g.push(H),A.add(ge),E.propertyIsEnumerable(ge)||(E[ge]=[]),E[ge].push(H),b.add(H),r&&(me>=n||R>=i||be(H,me+1)))},Z=(J,H,ge,me,we)=>{u.aborted||a(H)||(me.isDirectory()?U(J,H,ge,we):me.isFile()?q(J,H,ge):me.isSymbolicLink()&&z(J,H,ge,we))},oe=(J,H,ge,me)=>{if(u.aborted)return;let we=H===KSt.default.sep?"":KSt.default.sep,Be=ge.name,le=`${H}${we}${Be}`;a(le)||(ge.isDirectory()?U(J,le,Be,me):ge.isFile()?q(J,le,Be):ge.isSymbolicLink()&&z(J,le,Be,me))},V=(J,H,ge,me)=>{for(let we=0,Be=ge.length;we<Be;we++)oe(J,H,ge[we],me)},K=(J,H)=>{u.aborted||H>n||R>=i||(C(),lEn.default.readdir(J,{withFileTypes:!0},(ge,me)=>{if(ge||u.aborted||!me.length)return _();(c(me)||EYa).then(()=>{let Be=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(Be,J,me,H),_()})}))},be=(J,H)=>{C(),lEn.default.realpath(J,(ge,me)=>{if(ge||u.aborted)return _();lEn.default.stat(me,(we,Be)=>{if(we||u.aborted)return _();let le=KSt.default.basename(me),ue=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Z(ue,me,le,Be,H),_()})})};return(async(J,H=1)=>(J=KSt.default.normalize(J),b.add(J),K(J,H),await x,u.aborted?I:w))(e)},wYa=snd;var QX={lang:{debounce:cEn,attempt:e=>{try{return e()}catch(t){return QX.lang.castError(t)}},castArray:e=>QX.lang.isArray(e)?e:[e],castError:e=>QX.lang.isError(e)?e:QX.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(QX.lang.isNaN(e))return QX.lang.isNaN(t);if(QX.lang.isPrimitive(e)||QX.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(pEn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?o6i.default.realpathSync.native(e):o6i.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===pEn.default.sep&&t.length-e.length>pEn.default.sep.length,poll:(e,t=dYa)=>AYa.retry.stat(t)(e,{bigint:!0}).catch(QX.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await wYa(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},cl=QX;var fEn=_e(require("path"),1);var s6i=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||cl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=lYa){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,u)=>{let c=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...u]),p=this.eventsDeduplicate([...c,...l]);this.onTargetEvents(p)},s=cl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,u="",c=!1)=>{c?await this.eventsPopulate([u],n,!0):i.add(u),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Za.CHANGE&&a===Za.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===Za.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Za.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??Eve:Math.min(1,this.options.depth??Eve),s=this.options.limit??WSt,[a,u]=await cl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),c=[...a,...u];return await Promise.all(c.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())cl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Za.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!vve&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Za.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Za.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(fEn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Za.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(fEn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Za.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Za.ADD?this.onTargetAdd(n):r===Za.ADD_DIR?this.onTargetAddDir(n):r===Za.CHANGE?this.onTargetChange(n):r===Za.UNLINK?this.onTargetUnlink(n):r===Za.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=RDe.CHANGE,r){if(this.watcher.isClosed())return;let n=fEn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){e6i&&t.code==="EPERM"?this.onWatcherChange(RDe.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on($St.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on($St.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(RDe.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&vve&&this.options.native!==!1?this.options.depth??Eve:Math.min(1,this.options.depth??Eve),n=this.options.limit??WSt,[i,o]=await cl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(RDe.CHANGE,a,t)}))}}},CYa=s6i;var QT={interval:100,intervalId:void 0,fns:new Map,init:()=>{QT.intervalId||(QT.intervalId=setInterval(QT.resolve,QT.interval))},reset:()=>{QT.intervalId&&(clearInterval(QT.intervalId),delete QT.intervalId)},add:(e,t)=>{QT.fns.set(e,Date.now()+t),QT.init()},remove:e=>{QT.fns.delete(e)},resolve:()=>{if(!QT.fns.size)return QT.reset();let e=Date.now();for(let[t,r]of QT.fns)r>=e||(QT.remove(t),t())}},JSt=QT;var YSt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=t6i){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(cl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let u=()=>{s.add.delete(n),JSt.remove(c)},c=()=>{u(),a()};JSt.add(c,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;u();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=t6i){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let u=()=>{s.unlink.delete(n),JSt.remove(c)},c=()=>{u(),a()};JSt.add(c,r);let l=()=>(u(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Za.ADD,FX.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Za.ADD_DIR,FX.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Za.UNLINK,FX.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Za.UNLINK_DIR,FX.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};YSt.DIR_EVENTS={add:Za.ADD_DIR,rename:Za.RENAME_DIR,unlink:Za.UNLINK_DIR};YSt.FILE_EVENTS={add:Za.ADD,change:Za.CHANGE,rename:Za.RENAME,unlink:Za.UNLINK};var xYa=YSt;var a6i=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(cl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(cl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(cl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(cl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return cl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);cl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},u6i=a6i;var c6i=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},_Ya=c6i;var l6i=class{constructor(){this.inos={},this.paths=new u6i,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await cl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new _Ya(n)}reset(){this.inos={},this.paths=new u6i,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Za.ADD,i),[Za.ADD];if(i.isDirectory())return this.updateIno(t,Za.ADD_DIR,i),[Za.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Za.UNLINK,n),[Za.UNLINK];if(n.isDirectory())return this.updateIno(t,Za.UNLINK_DIR,n),[Za.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Za.CHANGE,i),[Za.CHANGE]);if(i.isDirectory())return this.updateIno(t,Za.UNLINK,n),this.updateIno(t,Za.ADD_DIR,i),[Za.UNLINK,Za.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Za.UNLINK_DIR,n),this.updateIno(t,Za.ADD,i),[Za.UNLINK_DIR,Za.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Za.UNLINK_DIR,n),this.updateIno(t,Za.ADD_DIR,i),[Za.UNLINK_DIR,Za.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?FX.FILE:FX.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},p6i=l6i;var f6i=class e extends SYa.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(kT.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(kT.CLOSE,i)),this._readyWait=new Promise(i=>this.on(kT.READY,i)),this._locker=new xYa(this),this._roots=new Set,this._poller=new p6i,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(cl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(kT.CLOSE))}error(t){if(this.isClosed())return!1;let r=cl.lang.castError(t);return this.emit(kT.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(kT.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(kT.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&cl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&cl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)cl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new CYa(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=cl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=FDe.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??Eve))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&vve&&l.options.native!==!1)))return!0;if(!vve)break;let c=FDe.default.dirname(t);if(s===c)break;s=c}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=cl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let u=!r.recursive||vve&&r.native!==!1?r:{...r,recursive:!1},l={watcher:dEn.default.watch(a,u),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=FDe.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(u){this.error(u)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||vve&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??Eve,a=r.limit??WSt,[u]=await cl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,o);if(u.length){let l=cl.fs.getDepth(t);for(let p of u){let d=cl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(c,l)=>{l===t&&(u(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(kT.CLOSE,u),s.watchFile(t,r,o)},u=()=>{this._subwatchers.delete(i),this.removeListener(kT.CLOSE,u),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=FDe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new p6i,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return cl.lang.noop;if(this.pollerExists(t,r))return cl.lang.noop;let i={...r,interval:r.pollingInterval??fYa},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(kT.CLOSE,a),dEn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(kT.CLOSE,a),dEn.default.unwatchFile(t,n)};return cl.lang.attempt(s),()=>cl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=cl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,u)=>u===s||!cl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=FDe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await cl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=FDe.default.dirname(t);return(await cl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=cl.lang.noop){if(cl.lang.isFunction(t))return this.watch([],{},t);if(cl.lang.isUndefined(t))return this.watch([],r,n);if(cl.lang.isFunction(r))return this.watch(t,{},r);if(cl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=cl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==cl.lang.noop&&this.on(kT.ALL,n),r.readdirMap=void 0,this.ready())}},mEn=f6i;BEn();Vt();var krt=require("fs/promises"),RXa=require("os"),FXa=_e(require("path"),1),Oid=".fern",Pid="logs";function Tid(){return"cli@4.31.0"}var LDe=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=We(Ut.of((0,RXa.homedir)()),Se.of(Oid)),r=We(t,Se.of(Pid));await Xt(r)||await(0,krt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=We(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${FXa.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2163
+ `)}if(s)throw gn.exit();if(o.warningCount>0){t.stderr.info(`${ns.warning} ${Ie.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(Ie.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${ns.success} ${Ie.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>fK(i))),{success:!r,results:n}}};function D5i(e,t){let r=new T5i;qa(e,"check","Validate docs configuration",(n,i)=>r.handle(n,i),n=>n.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}),t)}var BWa=_e(require("net"),1),OWa=_e(require("os"),1),I0n=class extends Error{constructor(t){super(`${t} is locked`)}},prt={old:new Set,young:new Set},jKf=1e3*15;var vSt,MKf=()=>{let e=OWa.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},_Wa=e=>new Promise((t,r)=>{let n=BWa.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),SWa=async(e,t)=>{if(e.host||e.port===0)return _Wa(e);for(let r of t)try{await _Wa({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},LKf=function*(e){e&&(yield*e),yield 0};async function dve(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}vSt===void 0&&(vSt=setTimeout(()=>{vSt=void 0,prt.old=prt.young,prt.young=new Set},jKf),vSt.unref&&vSt.unref());let n=MKf();for(let i of LKf(t))try{if(r.has(i))continue;let o=await SWa({...e,port:i},n);for(;prt.old.has(o)||prt.young.has(o);){if(i!==0)throw new I0n(i);o=await SWa({...e,port:i},n)}return prt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof I0n))throw o}throw new Error("No available ports found")}_g();Vt();var Wiu=_e(k5i(),1),$iu=_e(uEn(),1),Wvn=require("fs/promises"),Hiu=_e(require("http"),1),Kiu=_e(require("path"),1);var SYa=require("events"),dEn=_e(require("fs"),1),FDe=_e(require("path"),1);var cYa=_e(require("os"),1),lYa=300,Eve=20,WSt=1e7,pYa=cYa.default.platform();var tnd=pYa==="darwin",e6i=pYa==="win32",vve=tnd||e6i,fYa=3e3,dYa=2e4,t6i=1250;var FX;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(FX||(FX={}));var RDe;(function(e){e.CHANGE="change",e.RENAME="rename"})(RDe||(RDe={}));var $St;(function(e){e.CHANGE="change",e.ERROR="error"})($St||($St={}));var Za;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Za||(Za={}));var kT;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(kT||(kT={}));var rnd=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,u=0,c=0,l=()=>{let b=Date.now(),I=b-u,w=b-c,x=I>=t||w>=o;return[b,x]},p=b=>{if(c=b,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{E(0)},f=()=>{a&&(d(),p(Date.now()))},m=b=>{if(c=b,n)return p(b)},h=b=>{if(i&&s)return p(b);s=void 0},g=()=>{a=void 0;let[b,I]=l();return I?h(b):A(b)},A=b=>{let I=b-u,w=b-c,x=t-I,C=o-w,_=Math.min(x,C);return E(_)},E=b=>{a&&clearTimeout(a),!(b<=0)&&(a=setTimeout(g,b))},v=(...b)=>{let[I,w]=l(),x=!!a;if(s=b,u=I,(w||!a)&&E(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},cEn=rnd;var o6i=_e(require("fs"),1),pEn=_e(require("path"),1);var vf=_e(require("fs"),1),y1=require("util");var cae=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},kX=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var r6i=_e(require("process"),1),mYa=r6i.default.getuid?!r6i.default.getuid():!1,hYa=1e4,Bk=()=>{};var HSt={isChangeErrorOk:e=>{if(!HSt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mYa&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!HSt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!HSt.isNodeError(e))throw e;if(!HSt.isChangeErrorOk(e))throw e}},CE=HSt;var n6i=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=hYa,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gYa=new n6i;var lae=(e,t)=>function(n){return function i(...o){return gYa.schedule().then(s=>{let a=c=>(s(),c),u=c=>{if(s(),Date.now()>=n)throw c;if(t(c)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw c};return e.apply(void 0,o).then(a,u)})}},pae=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var nnd={attempt:{chmod:cae((0,y1.promisify)(vf.default.chmod),CE.onChangeError),chown:cae((0,y1.promisify)(vf.default.chown),CE.onChangeError),close:cae((0,y1.promisify)(vf.default.close),Bk),fsync:cae((0,y1.promisify)(vf.default.fsync),Bk),mkdir:cae((0,y1.promisify)(vf.default.mkdir),Bk),realpath:cae((0,y1.promisify)(vf.default.realpath),Bk),stat:cae((0,y1.promisify)(vf.default.stat),Bk),unlink:cae((0,y1.promisify)(vf.default.unlink),Bk),chmodSync:kX(vf.default.chmodSync,CE.onChangeError),chownSync:kX(vf.default.chownSync,CE.onChangeError),closeSync:kX(vf.default.closeSync,Bk),existsSync:kX(vf.default.existsSync,Bk),fsyncSync:kX(vf.default.fsync,Bk),mkdirSync:kX(vf.default.mkdirSync,Bk),realpathSync:kX(vf.default.realpathSync,Bk),statSync:kX(vf.default.statSync,Bk),unlinkSync:kX(vf.default.unlinkSync,Bk)},retry:{close:lae((0,y1.promisify)(vf.default.close),CE.isRetriableError),fsync:lae((0,y1.promisify)(vf.default.fsync),CE.isRetriableError),open:lae((0,y1.promisify)(vf.default.open),CE.isRetriableError),readFile:lae((0,y1.promisify)(vf.default.readFile),CE.isRetriableError),rename:lae((0,y1.promisify)(vf.default.rename),CE.isRetriableError),stat:lae((0,y1.promisify)(vf.default.stat),CE.isRetriableError),write:lae((0,y1.promisify)(vf.default.write),CE.isRetriableError),writeFile:lae((0,y1.promisify)(vf.default.writeFile),CE.isRetriableError),closeSync:pae(vf.default.closeSync,CE.isRetriableError),fsyncSync:pae(vf.default.fsyncSync,CE.isRetriableError),openSync:pae(vf.default.openSync,CE.isRetriableError),readFileSync:pae(vf.default.readFileSync,CE.isRetriableError),renameSync:pae(vf.default.renameSync,CE.isRetriableError),statSync:pae(vf.default.statSync,CE.isRetriableError),writeSync:pae(vf.default.writeSync,CE.isRetriableError),writeFileSync:pae(vf.default.writeFileSync,CE.isRetriableError)}},AYa=nnd;var lEn=_e(require("fs"),1),KSt=_e(require("path"),1);var i6i=()=>{};var ind=()=>{let e=i6i,t=i6i,r=!1,n=!1;return{promise:new Promise((u,c)=>{e=l=>(r=!0,u(l)),t=l=>(n=!0,c(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},yYa=ind;var ond=()=>{let{promise:e,resolve:t,isPending:r}=yYa(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},bYa=ond;var EYa={then:e=>{e()}};var vYa=e=>Array.isArray(e)?e:[e],IYa=e=>typeof e=="function";var snd=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=vYa(o).map(J=>IYa(J)?J:H=>J.test(H)),a=J=>s.some(H=>H(J)),u=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,E={},v={},b=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:E,map:v},{promise:x,increment:C,decrement:_}=bYa(),R=0,U=(J,H,ge,me)=>{b.has(H)||R>=i||(R+=1,J.directories.push(H),J.directoriesNames.add(ge),l.push(H),p.add(ge),d.propertyIsEnumerable(ge)||(d[ge]=[]),d[ge].push(H),b.add(H),!(me>=n)&&(R>=i||K(H,me+1)))},q=(J,H,ge)=>{b.has(H)||R>=i||(R+=1,J.files.push(H),J.filesNames.add(ge),f.push(H),m.add(ge),h.propertyIsEnumerable(ge)||(h[ge]=[]),h[ge].push(H),b.add(H))},z=(J,H,ge,me)=>{b.has(H)||R>=i||(R+=1,J.symlinks.push(H),J.symlinksNames.add(ge),g.push(H),A.add(ge),E.propertyIsEnumerable(ge)||(E[ge]=[]),E[ge].push(H),b.add(H),r&&(me>=n||R>=i||be(H,me+1)))},Z=(J,H,ge,me,we)=>{u.aborted||a(H)||(me.isDirectory()?U(J,H,ge,we):me.isFile()?q(J,H,ge):me.isSymbolicLink()&&z(J,H,ge,we))},oe=(J,H,ge,me)=>{if(u.aborted)return;let we=H===KSt.default.sep?"":KSt.default.sep,Be=ge.name,le=`${H}${we}${Be}`;a(le)||(ge.isDirectory()?U(J,le,Be,me):ge.isFile()?q(J,le,Be):ge.isSymbolicLink()&&z(J,le,Be,me))},V=(J,H,ge,me)=>{for(let we=0,Be=ge.length;we<Be;we++)oe(J,H,ge[we],me)},K=(J,H)=>{u.aborted||H>n||R>=i||(C(),lEn.default.readdir(J,{withFileTypes:!0},(ge,me)=>{if(ge||u.aborted||!me.length)return _();(c(me)||EYa).then(()=>{let Be=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(Be,J,me,H),_()})}))},be=(J,H)=>{C(),lEn.default.realpath(J,(ge,me)=>{if(ge||u.aborted)return _();lEn.default.stat(me,(we,Be)=>{if(we||u.aborted)return _();let le=KSt.default.basename(me),ue=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Z(ue,me,le,Be,H),_()})})};return(async(J,H=1)=>(J=KSt.default.normalize(J),b.add(J),K(J,H),await x,u.aborted?I:w))(e)},wYa=snd;var QX={lang:{debounce:cEn,attempt:e=>{try{return e()}catch(t){return QX.lang.castError(t)}},castArray:e=>QX.lang.isArray(e)?e:[e],castError:e=>QX.lang.isError(e)?e:QX.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(QX.lang.isNaN(e))return QX.lang.isNaN(t);if(QX.lang.isPrimitive(e)||QX.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(pEn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?o6i.default.realpathSync.native(e):o6i.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===pEn.default.sep&&t.length-e.length>pEn.default.sep.length,poll:(e,t=dYa)=>AYa.retry.stat(t)(e,{bigint:!0}).catch(QX.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await wYa(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},cl=QX;var fEn=_e(require("path"),1);var s6i=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||cl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=lYa){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,u)=>{let c=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...u]),p=this.eventsDeduplicate([...c,...l]);this.onTargetEvents(p)},s=cl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,u="",c=!1)=>{c?await this.eventsPopulate([u],n,!0):i.add(u),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Za.CHANGE&&a===Za.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===Za.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Za.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??Eve:Math.min(1,this.options.depth??Eve),s=this.options.limit??WSt,[a,u]=await cl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),c=[...a,...u];return await Promise.all(c.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())cl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Za.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!vve&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Za.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Za.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(fEn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Za.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(fEn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Za.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Za.ADD?this.onTargetAdd(n):r===Za.ADD_DIR?this.onTargetAddDir(n):r===Za.CHANGE?this.onTargetChange(n):r===Za.UNLINK?this.onTargetUnlink(n):r===Za.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=RDe.CHANGE,r){if(this.watcher.isClosed())return;let n=fEn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){e6i&&t.code==="EPERM"?this.onWatcherChange(RDe.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on($St.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on($St.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(RDe.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&vve&&this.options.native!==!1?this.options.depth??Eve:Math.min(1,this.options.depth??Eve),n=this.options.limit??WSt,[i,o]=await cl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(RDe.CHANGE,a,t)}))}}},CYa=s6i;var QT={interval:100,intervalId:void 0,fns:new Map,init:()=>{QT.intervalId||(QT.intervalId=setInterval(QT.resolve,QT.interval))},reset:()=>{QT.intervalId&&(clearInterval(QT.intervalId),delete QT.intervalId)},add:(e,t)=>{QT.fns.set(e,Date.now()+t),QT.init()},remove:e=>{QT.fns.delete(e)},resolve:()=>{if(!QT.fns.size)return QT.reset();let e=Date.now();for(let[t,r]of QT.fns)r>=e||(QT.remove(t),t())}},JSt=QT;var YSt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=t6i){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(cl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let u=()=>{s.add.delete(n),JSt.remove(c)},c=()=>{u(),a()};JSt.add(c,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;u();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=t6i){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let u=()=>{s.unlink.delete(n),JSt.remove(c)},c=()=>{u(),a()};JSt.add(c,r);let l=()=>(u(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Za.ADD,FX.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Za.ADD_DIR,FX.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Za.UNLINK,FX.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Za.UNLINK_DIR,FX.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};YSt.DIR_EVENTS={add:Za.ADD_DIR,rename:Za.RENAME_DIR,unlink:Za.UNLINK_DIR};YSt.FILE_EVENTS={add:Za.ADD,change:Za.CHANGE,rename:Za.RENAME,unlink:Za.UNLINK};var xYa=YSt;var a6i=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(cl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(cl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(cl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(cl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return cl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);cl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},u6i=a6i;var c6i=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},_Ya=c6i;var l6i=class{constructor(){this.inos={},this.paths=new u6i,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await cl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new _Ya(n)}reset(){this.inos={},this.paths=new u6i,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Za.ADD,i),[Za.ADD];if(i.isDirectory())return this.updateIno(t,Za.ADD_DIR,i),[Za.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Za.UNLINK,n),[Za.UNLINK];if(n.isDirectory())return this.updateIno(t,Za.UNLINK_DIR,n),[Za.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Za.CHANGE,i),[Za.CHANGE]);if(i.isDirectory())return this.updateIno(t,Za.UNLINK,n),this.updateIno(t,Za.ADD_DIR,i),[Za.UNLINK,Za.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Za.UNLINK_DIR,n),this.updateIno(t,Za.ADD,i),[Za.UNLINK_DIR,Za.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Za.UNLINK_DIR,n),this.updateIno(t,Za.ADD_DIR,i),[Za.UNLINK_DIR,Za.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?FX.FILE:FX.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},p6i=l6i;var f6i=class e extends SYa.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(kT.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(kT.CLOSE,i)),this._readyWait=new Promise(i=>this.on(kT.READY,i)),this._locker=new xYa(this),this._roots=new Set,this._poller=new p6i,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(cl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(kT.CLOSE))}error(t){if(this.isClosed())return!1;let r=cl.lang.castError(t);return this.emit(kT.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(kT.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(kT.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&cl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&cl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)cl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new CYa(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=cl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=FDe.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??Eve))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&vve&&l.options.native!==!1)))return!0;if(!vve)break;let c=FDe.default.dirname(t);if(s===c)break;s=c}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=cl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let u=!r.recursive||vve&&r.native!==!1?r:{...r,recursive:!1},l={watcher:dEn.default.watch(a,u),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=FDe.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(u){this.error(u)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||vve&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??Eve,a=r.limit??WSt,[u]=await cl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,o);if(u.length){let l=cl.fs.getDepth(t);for(let p of u){let d=cl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(c,l)=>{l===t&&(u(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(kT.CLOSE,u),s.watchFile(t,r,o)},u=()=>{this._subwatchers.delete(i),this.removeListener(kT.CLOSE,u),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=FDe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new p6i,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return cl.lang.noop;if(this.pollerExists(t,r))return cl.lang.noop;let i={...r,interval:r.pollingInterval??fYa},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(kT.CLOSE,a),dEn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(kT.CLOSE,a),dEn.default.unwatchFile(t,n)};return cl.lang.attempt(s),()=>cl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=cl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,u)=>u===s||!cl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=FDe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await cl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=FDe.default.dirname(t);return(await cl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=cl.lang.noop){if(cl.lang.isFunction(t))return this.watch([],{},t);if(cl.lang.isUndefined(t))return this.watch([],r,n);if(cl.lang.isFunction(r))return this.watch(t,{},r);if(cl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=cl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==cl.lang.noop&&this.on(kT.ALL,n),r.readdirMap=void 0,this.ready())}},mEn=f6i;BEn();Vt();var krt=require("fs/promises"),RXa=require("os"),FXa=_e(require("path"),1),Oid=".fern",Pid="logs";function Tid(){return"cli@4.31.1"}var LDe=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=We(Ut.of((0,RXa.homedir)()),Se.of(Oid)),r=We(t,Se.of(Pid));await Xt(r)||await(0,krt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=We(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${FXa.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2164
2164
  `);await(0,krt.writeFile)(this.logFilePath,o,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
2165
2165
  `;try{await(0,krt.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:Tid(),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)}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 F6i={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function kXa(e){let t=Did();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i}=e,o=new Map;function s(u){let c=JSON.stringify(u),l=[];for(let[p]of o)try{p.send(c)}catch{l.push(p)}for(let p of l){let d=o.get(p);d&&(clearInterval(d.pingInterval),o.delete(p))}}let a=t.serve({port:r,fetch(u,c){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:F6i});let l=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){c.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&l.pathname==="/v2/registry/docs/load-with-url")return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...F6i}});let p=/^\/_local\/(.*)/.exec(l.pathname);return u.method==="GET"&&p!=null?new Response(t.file(`/${p[1]}`),{headers:F6i}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:c}=u.data,l=setInterval(()=>{let p=o.get(u);if(!p)return;let d=Date.now();if(d-p.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:d}))}catch{u.close()}},3e4);o.set(u,{pingInterval:l,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:c}))}catch{}},message(u,c){try{let l=JSON.parse(c.toString());if(l.type==="pong"){let p=o.get(u);p&&(p.lastPong=Date.now())}else LDe.isMetricsMessage(l)&&n.logFrontendMetrics(l)}catch{}},close(u){let c=o.get(u);c&&(clearInterval(c.pingInterval),o.delete(u))}}});return{sendData:s,stop:u=>a.stop(u)}}function Did(){return globalThis.Bun}Vt();var mqi=_e(V6i(),1),jiu=_e(rqi(),1),Ok=require("fs/promises"),Miu=require("os"),Liu=_e(Aw(),1),Uiu=_e(Qiu(),1),Lvn=process.platform==="win32",dqi=Ie.cyan("[docs]:"),ucd="etag",ccd=23,Niu=e=>e.padEnd(ccd," "),lcd="preview",pcd="app-preview",fcd="bundle",dcd=".next",mcd="standalone",hcd=".fern",gcd="packages/fern-docs/bundle/.next/server/instrumentation.js",Acd=".npmrc",ycd=".pnpmfile.cjs",bcd="pnpm-workspace.yaml",Ecd='Cannot find matching keyid: {"signatures":';function vcd(){return We(Ut.of((0,Miu.homedir)()),Se.of(hcd))}function Zrt({app:e=!1}){return We(vcd(),Se.of(e?pcd:lcd))}function Dve({app:e=!1}){return We(Zrt({app:e}),Se.of(e?dcd:fcd))}function PBt({app:e=!1}){return We(Dve({app:e}),Se.of(mcd))}function Icd({app:e=!1}){return We(PBt({app:e}),Se.of(gcd))}function wcd({app:e=!1}){return We(PBt({app:e}),Se.of(bcd))}function Ccd({app:e=!1}){return We(PBt({app:e}),Se.of(ycd))}function xcd({app:e=!1}){return We(PBt({app:e}),Se.of(Acd))}function KDe(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function _cd({app:e=!1}){return We(Zrt({app:e}),Se.of(ucd))}var Scd=`module.exports = {
2166
2166
  hooks: {
@@ -2201,7 +2201,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
2201
2201
 
2202
2202
  Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`);case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function yfd(e,t){let n=e?.content;if(n?.reason==="status-code"){let i=n.statusCode;if(i===401||i===403)return`${`You do not have permission to publish docs to organization '${t}'. Please run 'fern login' to ensure you are logged in with the correct account.`}
2203
2203
 
2204
- Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function bfd(e){try{return new URL(BT(e)).pathname}catch{return}}async function Efd({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await vfd({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Cr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let u={};for(let[c,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${c}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();u[c]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${c}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${c}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${c}: ${p}`)}return Object.keys(u).length>0?u:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function Ssu(e){return e.replace(/^https:\/\//,"")}async function vfd({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&Ssu(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await Ifd({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function Ifd({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,u;if(t.generatorsConfiguration?.groups){let c=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=yn.getPackageName({generatorInvocation:p});d&&c.push(d),!a&&d&&(a=d,u=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let c=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!c.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${c.body.version} for package "${a}"`),{version:c.body.version,generatorPackage:a}}catch(c){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${c}`);return}}async function wfd({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&Ssu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let u of a.generators){let c=JDe({apiName:e.workspaceName??"",organization:t,generatorInvocation:u}),l="";if(c?.outputConfig.type==="publish")switch(c.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=c.outputConfig.value.packageName;break;case"maven":l=c.outputConfig.value.coordinate;break;case"go":l=c.outputConfig.value.repoUrl;break;case"swift":l=c.outputConfig.value.repoUrl;break;case"crates":l=c.outputConfig.value.packageName;break}if(u.language==="php"&&u.config&&typeof u.config=="object"&&"packageName"in u.config&&(l=u.config.packageName??""),!!u.language){if(i.has(u.language)){r.logger.debug(`Skipping dynamic IR generation for ${u.language} (using existing SDK dynamic IR)`);continue}if(u.language&&s[u.language]===l){let p=Zm({workspace:e,generationLanguage:u.language,keywords:void 0,smartCasing:u.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new tm(r,e),dynamicGeneratorConfig:c}),d=qBe({ir:p,disableExamples:!0,smartCasing:u.smartCasing,generationLanguage:u.language,generatorConfig:c});d?o[u.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${u.language}`)}}}for(let[a,u]of Object.entries(s))a&&u&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${u}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${u} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function Cfd({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function xfd({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(Ie.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function _fd(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function Sfd(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var jBt=[60*1e3,300*1e3,300*1e3];async function MBt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,disableTemplates:u,skipUpload:c,cliVersion:l}){let p=a&&!n.config.settings?.substituteEnvVars;n.config=$y(n.config,{onError:g=>i.failAndThrow(g)},{substituteAsEmpty:p});let d=n.config.instances;if(d.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(d.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${d[0]?.url})`);return}let f=d.find(g=>g.url===s)??d[0];if(f==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let m=[];f.customDomain!=null&&(typeof f.customDomain=="string"?m.push(f.customDomain):Array.isArray(f.customDomain)&&m.push(...f.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${f.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let h;return await i.runInteractiveTask({name:f.url},async()=>{let g=performance.now(),A=()=>_su({docsWorkspace:n,customDomains:m,domain:f.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,editThisPage:f.editThisPage,isPrivate:f.private,disableTemplates:u,skipUpload:c,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:f.audiences?Array.isArray(f.audiences)?f.audiences:[f.audiences]:void 0,docsUrl:f.url,cliVersion:l});for(let v=0;;v++)try{h=await A();break}catch(b){if(!(b instanceof nnt)||v>=jBt.length){if(b instanceof nnt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw b}let I=jBt[v]??jBt[jBt.length-1]??6e4,w=I/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${w} minute${w===1?"":"s"} (attempt ${v+1}/${jBt.length})...`),await new Promise(x=>setTimeout(x,I))}let E=performance.now()-g;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),h}var QIn=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,skipUpload:n}){let i=new ih({context:this.context,task:this.task});try{let o=await MBt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,disableTemplates:void 0,skipUpload:n,cliVersion:"4.31.0"});return i.getResult()===Op.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};Qt();var int=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(`
2204
+ Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function bfd(e){try{return new URL(BT(e)).pathname}catch{return}}async function Efd({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await vfd({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Cr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let u={};for(let[c,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${c}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();u[c]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${c}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${c}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${c}: ${p}`)}return Object.keys(u).length>0?u:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function Ssu(e){return e.replace(/^https:\/\//,"")}async function vfd({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&Ssu(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await Ifd({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function Ifd({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,u;if(t.generatorsConfiguration?.groups){let c=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=yn.getPackageName({generatorInvocation:p});d&&c.push(d),!a&&d&&(a=d,u=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let c=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!c.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${c.body.version} for package "${a}"`),{version:c.body.version,generatorPackage:a}}catch(c){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${c}`);return}}async function wfd({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&Ssu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let u of a.generators){let c=JDe({apiName:e.workspaceName??"",organization:t,generatorInvocation:u}),l="";if(c?.outputConfig.type==="publish")switch(c.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=c.outputConfig.value.packageName;break;case"maven":l=c.outputConfig.value.coordinate;break;case"go":l=c.outputConfig.value.repoUrl;break;case"swift":l=c.outputConfig.value.repoUrl;break;case"crates":l=c.outputConfig.value.packageName;break}if(u.language==="php"&&u.config&&typeof u.config=="object"&&"packageName"in u.config&&(l=u.config.packageName??""),!!u.language){if(i.has(u.language)){r.logger.debug(`Skipping dynamic IR generation for ${u.language} (using existing SDK dynamic IR)`);continue}if(u.language&&s[u.language]===l){let p=Zm({workspace:e,generationLanguage:u.language,keywords:void 0,smartCasing:u.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new tm(r,e),dynamicGeneratorConfig:c}),d=qBe({ir:p,disableExamples:!0,smartCasing:u.smartCasing,generationLanguage:u.language,generatorConfig:c});d?o[u.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${u.language}`)}}}for(let[a,u]of Object.entries(s))a&&u&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${u}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${u} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function Cfd({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function xfd({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(Ie.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function _fd(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function Sfd(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var jBt=[60*1e3,300*1e3,300*1e3];async function MBt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,disableTemplates:u,skipUpload:c,cliVersion:l}){let p=a&&!n.config.settings?.substituteEnvVars;n.config=$y(n.config,{onError:g=>i.failAndThrow(g)},{substituteAsEmpty:p});let d=n.config.instances;if(d.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(d.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${d[0]?.url})`);return}let f=d.find(g=>g.url===s)??d[0];if(f==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let m=[];f.customDomain!=null&&(typeof f.customDomain=="string"?m.push(f.customDomain):Array.isArray(f.customDomain)&&m.push(...f.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${f.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let h;return await i.runInteractiveTask({name:f.url},async()=>{let g=performance.now(),A=()=>_su({docsWorkspace:n,customDomains:m,domain:f.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,editThisPage:f.editThisPage,isPrivate:f.private,disableTemplates:u,skipUpload:c,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:f.audiences?Array.isArray(f.audiences)?f.audiences:[f.audiences]:void 0,docsUrl:f.url,cliVersion:l});for(let v=0;;v++)try{h=await A();break}catch(b){if(!(b instanceof nnt)||v>=jBt.length){if(b instanceof nnt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw b}let I=jBt[v]??jBt[jBt.length-1]??6e4,w=I/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${w} minute${w===1?"":"s"} (attempt ${v+1}/${jBt.length})...`),await new Promise(x=>setTimeout(x,I))}let E=performance.now()-g;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),h}var QIn=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,skipUpload:n}){let i=new ih({context:this.context,task:this.task});try{let o=await MBt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,disableTemplates:void 0,skipUpload:n,cliVersion:"4.31.1"});return i.getResult()===Op.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};Qt();var int=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(`
2205
2205
  `),this.stream.write(`${Ie.cyan("\u25C6")} ${Ie.bold(t.title)}
2206
2206
  `),t.subtitle!=null&&this.stream.write(` ${Ie.dim(t.subtitle)}
2207
2207
  `),this.stream.write(`
@@ -3590,7 +3590,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
3590
3590
  Run ${Ie.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
3591
3591
  Run ${Ie.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Q9e(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Abo({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!KUu(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,u)=>a.generatorName.localeCompare(u.generatorName)||a.currentVersion.localeCompare(u.currentVersion));for(let a of s)i+=`
3592
3592
  ${await pBm(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+Ie.dim(a.currentVersion)+Ie.reset(" \u2192 ")+Ie.green(a.latestVersion);return i+=`
3593
- `,n?Q9e(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function pBm(e){let r=await new HUu.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function fBm({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await YUu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(u,c,l,p)=>{a.versions[c]==null&&(a.versions[c]={});let d=iBe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await jS({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[c][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await YUu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,u,c,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][u]==null&&(s.versions[a][u]={});let p=iBe(c.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${c.name}`);return}let d=await jS({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][u][c.name]={previousVersion:c.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function YUu({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 bQ({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let u=n!=null?oC(n):void 0;for(let c of a.groups)if(!(i!=null&&c.groupName!==i))for(let l of c.generators)u!=null&&l.name!==u||await r(o.workspaceName,c.groupName,l,s)})}))}function XUu(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 u=XR(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(u?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:u,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function Mkn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await fBm({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[u,c]of Object.entries(a.versions))s.push(...XUu(c,u,t.logger));else s.push(...XUu(a.versions,void 0,t.logger))}return s}async function Zue({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:hdt(e.packageName,{version:t?"prerelease":"latest"})}var ZUu=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Lkn=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=zn.Info;isLocal;stdoutRedirector=new jkn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new oOe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s}}getPackageName(){return"fern-api"}getPackageVersion(){return"4.31.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ie.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pm}failWithoutThrowing(t,r){this.didSucceed=!1,nEt({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3593
+ `,n?Q9e(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function pBm(e){let r=await new HUu.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function fBm({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await YUu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(u,c,l,p)=>{a.versions[c]==null&&(a.versions[c]={});let d=iBe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await jS({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[c][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await YUu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,u,c,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][u]==null&&(s.versions[a][u]={});let p=iBe(c.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${c.name}`);return}let d=await jS({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][u][c.name]={previousVersion:c.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function YUu({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 bQ({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let u=n!=null?oC(n):void 0;for(let c of a.groups)if(!(i!=null&&c.groupName!==i))for(let l of c.generators)u!=null&&l.name!==u||await r(o.workspaceName,c.groupName,l,s)})}))}function XUu(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 u=XR(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(u?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:u,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function Mkn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await fBm({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[u,c]of Object.entries(a.versions))s.push(...XUu(c,u,t.logger));else s.push(...XUu(a.versions,void 0,t.logger))}return s}async function Zue({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:hdt(e.packageName,{version:t?"prerelease":"latest"})}var ZUu=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Lkn=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=zn.Info;isLocal;stdoutRedirector=new jkn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new oOe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s}}getPackageName(){return"fern-api"}getPackageVersion(){return"4.31.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ie.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pm}failWithoutThrowing(t,r){this.didSucceed=!1,nEt({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3594
3594
  `),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await k9e()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await JUu({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
3595
3595
  `)||(r+=`
3596
3596
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=yLn(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new OFt(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){throw o.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,o),new pm}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await k9e()).sendEvent(t)}logger=aP((t,...r)=>this.log(t,...r));stderr=aP((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=e3u(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?e3u(this.longestWorkspaceName):r).length,i=r.padEnd(n),o=ZUu[this.numTasks++%ZUu.length],s=Ie.hex(o)(i);return{...this.constructTaskInit(),logPrefix:s}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Op.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>b_.indexOf(i.level)>=b_.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===zn.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await Zue({cliEnvironment:this.environment,includePreReleases:t}),n=XR(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await Mkn({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await hbo({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ie.yellow("?"),style:{answer:i=>Ie.cyan(i),message:i=>Ie.bold(i),highlight:i=>Ie.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`