fern-api 4.62.1 → 4.62.3

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 +11 -11
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1495,7 +1495,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1495
1495
  Location: ${i.join("-> ")}`),Dr.unknown({nameOverride:p,generatedName:m,title:h,description:g,availability:A,namespace:a,groupName:f,example:void 0})}}function VDl(e,t){if(!t&&e.enum!=null&&e.enum.length===1&&typeof e.enum[0]=="boolean")return e.enum[0]}function qDl(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 w9e(e){if(e.$ref.startsWith(cRe))return e.$ref.replace(cRe,"")}function GEi(e,t,r,n,i){let o=qr(e,On.TYPE_NAME),s=kb(t,n),a=e.description,c=sw(e),u=w9e(e);if(u==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return Da.reference({generatedName:s,nameOverride:o,title:void 0,schema:u,description:a??void 0,availability:c,namespace:i.getNamespace(u),groupName:void 0,source:r})}function GDl(e){return e.oneOf==null||e.oneOf.length===0}function nTs(e){return e.allOf==null||e.allOf.length===0}function Afr(e){return e.properties==null||Hm(e.properties)===0}function bfr(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function zH(e,t,r,n){if(e.type==="reference")return Dr.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n});if(e.type==="optional"){let i=zH(e.value,t,r,n);return Dr.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=zH(e.value,t,r,n);return Dr.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 Dr.primitive({...e,description:t});return e}function yfr(e){return Mn(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>yfr(t)):e.oneOf!=null?e.oneOf.every(t=>yfr(t)):e.anyOf!=null?e.anyOf.every(t=>yfr(t)):!1}function iTs({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,nameOverride:a,generatedName:c,title:u}){let l=Dr.literal({nameOverride:a,generatedName:c,title:u,value:e,namespace:n,groupName:i,description:o,availability:s});return r&&(l=Dr.nullable({nameOverride:a,generatedName:c,title:u,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(l=Dr.optional({nameOverride:a,generatedName:c,title:u,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),l}function p_({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:s,generatedName:a,nameOverride:c,title:u}){i=typeof i=="string"?[i]:i;let l=Dr.primitive({nameOverride:c,generatedName:a,title:u,schema:e,description:o,availability:s,namespace:n,groupName:i});return r&&(l=Dr.nullable({nameOverride:c,generatedName:a,title:u,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),t&&(l=Dr.optional({nameOverride:c,generatedName:a,title:u,value:l,namespace:n,groupName:i,description:o,availability:s,inline:void 0})),l}function WDl({schemas:e}){let t=new Set;for(let r of e){if(Mn(r))return;if(r.enum!=null&&bfr(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function oTs({schemas:e,context:t}){let r={};for(let n of e){let i=cTs({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 cTs({schema:e,context:t}){let r=Mn(e)?t.resolveSchemaReference(e):e;return $Dl({schema:r,context:t})}function $Dl({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=cTs({schema:n,context:t});for(let[o,s]of Object.entries(i??{}))r[o]=s}return r}for(let[n,i]of Object.entries(e.properties??{})){let o=Mn(i)?t.resolveSchemaReference(i):i;o.type==="string"&&o.enum!=null&&bfr(o.enum)&&HDl(o.enum).length===1&&o.enum[0]!=null&&(r[n]=o.enum[0]);let s=uTs(o,"const");o.type==="string"&&s!=null&&(r[n]=s),n==="type"&&o.example!=null&&(r[n]=o.example)}return r}function HDl(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 uTs(e,t){let r=e[t];if(r!=null)return r}function KDl({schema:e,logger:t}){let r=NOs({schema:e,logger:t});if(r!=null)return $Os(r)}var x9e=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(cRe))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let n=t.$ref.substring(cRe.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 c=i.schemas[o];if(c==null)throw new Error(`Schema "${o}" is undefined in document.components.schemas.`);if(Mn(c)&&(c=this.resolveSchemaReference(c)),s==="properties"&&a!=null){let u=c.properties?.[a];if(u==null)throw new Error(`Property "${a}" not found on "${o}". Full ref: ${t.$ref}`);Mn(u)?c=this.resolveSchemaReference(u):c=u}return c}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}getNamespace(t){return this.namespace}};var vfr=class extends x9e{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}};Tt();function _9e(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:we(o)}return{rootSchemas:r,namespacedSchemas:n}}Tt();var S9e=ve(require("fs"),1),uRe=ve(require("path"),1);Tt();function IAe(e){if(typeof e=="string")return Cc.primitive(_s.string(e));if(typeof e=="number")return Number.isInteger(e)?Cc.primitive(_s.int(e)):Cc.primitive(_s.double(e));if(typeof e=="boolean")return Cc.primitive(_s.boolean(e));if(Array.isArray(e)){let t=e.map(r=>IAe(r));return t.length===0?void 0:Cc.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=IAe(n);i!=null&&t.push({key:_s.string(r),value:i})}return Cc.map(t)}}function o_t(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function lTs(e){if(e!=null&&Array.isArray(e))return e}var wAe=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"&&pTs({schema:n,value:r}))return Cc.enum(r);if(r!=null){let c=n.values.map(l=>l.value),u=e.truncateExample(r);this.context.logger.warn(`Example value ${u} is not a valid enum value${s.name!=null?` for '${s.name}'`:""}. Allowed values: [${c.join(", ")}]. Using fallback value instead.`)}return n.values[0]!=null?Cc.enum(n.values[0]?.value):void 0;case"literal":return Cc.literal(n.value);case"nullable":{if(r===null)return Cc.null({});if(r==null&&!this.hasExample(n.value,0,o,s)&&this.exceedsMaxDepth(i,s))return Cc.null({});let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return c??Cc.null({})}case"optional":{if(r==null&&!this.hasExample(n.value,0,o,s)&&(s.ignoreOptionals||this.exceedsMaxDepth(i,s))||Object.is(r,null))return;let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:s,skipReadonly:a});return c!=null&&c.type==="array"&&c.value.length===0||c!=null&&c.type==="map"&&c.value.length===0||c!=null&&c.type==="object"&&Object.keys(c.properties).length===0?void 0:c}case"primitive":{let c=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:s});return Cc.primitive(c)}case"reference":{let c=this.schemas[n.schema];if(c!=null&&!o.has(n.schema)){o.add(n.schema);let u=c?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),l=this.buildExampleHelper({example:r,schema:c,exampleId:t,visitedSchemaIds:o,depth:i,options:s,skipReadonly:u||this.context.options.respectReadonlySchemas?a:!1});return o.delete(n.schema),l}return}case"oneOf":switch(n.value.type){case"discriminated":{let c={},u={},l={},p=o_t(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"){u=this.getAllProperties(f),l=this.getAllRequiredProperties(f),c[n.value.discriminantProperty]=Cc.primitive(_s.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,c),c[n.value.discriminantProperty]=Cc.primitive(_s.string(g[0]));break}}for(let g of n.value.commonProperties){u[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(u)){let b=g in l;if(b&&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)c[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)c[g]=v;else if(b)return}}return Cc.oneOf(iAe.discriminated(c))}case"undiscriminated":{let c=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(c!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:c,visitedSchemaIds:o,depth:i,options:s,skipReadonly:a});break}}return;case"unknown":if(r!=null){let c=IAe(r);if(c!=null)return Cc.unknown(c)}return s.ignoreOptionals||this.exceedsMaxDepth(i,s)?void 0:s.isParameter?Cc.primitive(_s.string(s.name??"string")):Cc.map([{key:_s.string("key"),value:Cc.primitive(_s.string("value"))}]);case"array":{let c=lTs(r),u=[];if(c!=null&&c.length>0)for(let l of c){let p=this.buildExampleHelper({exampleId:t,example:l,schema:n.value,depth:i+1,visitedSchemaIds:o,options:s,skipReadonly:a});p!=null&&u.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&&u.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&&u.push(l)}return Cc.array(u)}case"map":{let c=o_t(r??n.example);if(c!=null&&Object.entries(c).length>0){let p=[];for(let[d,f]of Object.entries(c)){let m=this.buildExampleFromPrimitive({schema:n.key.schema,example:d,options:s}),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 Cc.map(p)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return Cc.map([{key:_s.string("key"),value:Cc.unknown(Cc.primitive(_s.string("value")))}]);let u=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"?Cc.map([{key:u,value:l}]):Cc.map([])}case"object":{let c={},u=n.fullExamples?.find(f=>f.name===t)??n.fullExamples?.find(f=>f.name==null)??n.fullExamples?.[0],l=o_t(r)??(u!=null?o_t(u.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],b=this.getSchemaExample(m.schema),v=g?A:b,E=this.buildExampleHelper({schema:m.schema,exampleId:t,example:v,visitedSchemaIds:o,depth:i+1,options:{...s,name:f},skipReadonly:a});if(h&&E!=null)c[f]=E;else{if(h)return;(g&&E!=null||!s.ignoreOptionals&&E!=null)&&(c[f]=E)}}if(n.additionalProperties){for(let[f,m]of Object.entries(l))if(!(f in c)){let h=this.buildExampleHelper({schema:Dr.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&&(c[f]=h)}}return Cc.object({properties:c})}default:we(n)}}mergeExampleWith(t,r){t._visit({array:ht,enum:ht,literal:ht,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:ht,unknown:ht,null:ht,_other:ht})}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 pTs({schema:t,value:r})?5:0;case"object":{if(!Ma(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(!Ma(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"?_s.string(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string",schemaType:r.type,options:n}),_s.string(r.example??n.name??_i.STRING));case"base64":return t!=null&&typeof t=="string"?_s.base64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (base64)",schemaType:r.type,options:n}),_s.base64(r.example??_i.BASE64));case"boolean":return t!=null&&typeof t=="boolean"?_s.boolean(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"boolean",schemaType:r.type,options:n}),_s.boolean(r.example??_i.BOOLEAN));case"date":return t!=null&&typeof t=="string"?_s.date(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (date)",schemaType:r.type,options:n}),_s.date(r.example??_i.DATE));case"datetime":return t!=null&&typeof t=="string"?_s.datetime(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime)",schemaType:r.type,options:n}),_s.datetime(r.example??_i.DATE_TIME));case"datetimeRfc2822":return t!=null&&typeof t=="string"?_s.datetimeRfc2822(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"string (datetime RFC 2822)",schemaType:r.type,options:n}),_s.datetimeRfc2822(r.example??_i.DATE_TIME_RFC_2822));case"double":return t!=null&&typeof t=="number"?_s.double(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (double)",schemaType:r.type,options:n}),_s.double(r.example??_i.DOUBLE));case"float":return t!=null&&typeof t=="number"?_s.float(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (float)",schemaType:r.type,options:n}),_s.float(r.example??_i.FLOAT));case"int":return t!=null&&typeof t=="number"?_s.int(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int)",schemaType:r.type,options:n}),_s.int(r.example??_i.INT));case"int64":return t!=null&&typeof t=="number"?_s.int64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (int64)",schemaType:r.type,options:n}),_s.int64(r.example??_i.INT64));case"uint":return t!=null&&typeof t=="number"?_s.uint(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint)",schemaType:r.type,options:n}),_s.uint(r.example??_i.UINT));case"uint64":return t!=null&&typeof t=="number"?_s.uint64(t):(t!=null&&this.warnTypeMismatch({example:t,expected:"number (uint64)",schemaType:r.type,options:n}),_s.uint64(r.example??_i.UINT64));default:we(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 pTs({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}Tt();function gG(e){switch(e.type){case"object":return Dr.object({allOf:e.allOf,properties:e.properties.map(t=>YDl(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 Dr.array({description:e.description,availability:e.availability,value:gG(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 Dr.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 Dr.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 Dr.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:gG(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Dr.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:gG(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Dr.primitive({description:e.description,availability:e.availability,schema:fTs(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Dr.map({description:e.description,availability:e.availability,key:Dr.primitive({description:e.key.description,availability:e.key.availability,schema:fTs(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:gG(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 Dr.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 Dr.oneOf(JDl(e.value));case"unknown":return Dr.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:we(e)}}function JDl(e){switch(e.type){case"discriminated":return yM.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:gG(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,gG(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return yM.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>gG(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:we(e)}}function fTs(e){switch(e.type){case"string":return Di.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Di.base64({example:void 0});case"boolean":return Di.boolean({default:e.default,example:void 0});case"date":return Di.date({example:void 0});case"datetime":return Di.datetime({example:void 0});case"datetimeRfc2822":return Di.datetimeRfc2822({example:void 0});case"double":return Di.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 Di.float({example:void 0});case"int":return Di.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 Di.int64({default:e.default,example:void 0});case"uint":return Di.uint({default:void 0,example:void 0});case"uint64":return Di.uint64({default:void 0,example:void 0});default:we(e)}}function YDl(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:gG(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Ifr(e){return e.type!=="optional"&&e.type!=="nullable"}function $Ei(e){return e==="POST"||e==="PUT"||e==="PATCH"}function s_t(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 wfr=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 wAe(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=uRe.dirname(o),a=s;for(;a!==uRe.dirname(a);){let c=uRe.join(a,"fern");if(S9e.existsSync(c)&&S9e.statSync(c).isDirectory()){t=c;break}a=uRe.dirname(a)}t||(t=s)}else t=process.cwd();let r=t??process.cwd(),n=uRe.join(r,"schemas_missing_examples.txt"),i=["# Schemas Missing Examples Report",`# Generated on: ${new Date().toISOString()}`,`# Total missing examples: ${this.missingExamples.length}`,"",...this.missingExamples.flatMap(o=>{let s=[];if(s.push(`${o.method} ${o.endpoint} - ${o.type.toUpperCase()} (${o.schemaType}): ${o.reason}`),o.operationSummary&&s.push(` Operation: ${o.operationSummary}`),o.operationDescription&&o.operationDescription!==o.operationSummary&&s.push(` Description: ${o.operationDescription}`),o.schemaDescription&&s.push(` ${o.type==="request"?"Request":"Response"} Schema: ${o.schemaDescription}`),o.autoGeneratedExample){s.push(" Auto-generated example:");let c=JSON.stringify(o.autoGeneratedExample,null,4).split(`
1496
1496
  `).map(u=>` ${u}`).join(`
1497
1497
  `);s.push(c)}return s.push(""),s}),""].join(`
1498
- `);try{S9e.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=ZDl(t.request),n=eRl(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:$Ei(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:$Ei(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,H4.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,H4.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,H4.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,H4.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&&!AG(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&&!AG(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 c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!AG(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&c.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?gG(p.schema):Dr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Di.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&&!AG(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),f!=null&&c.push({name:p.header,value:f})}let u=[];t.request!=null&&t.response!=null?u=XDl(i,o):t.request!=null?u=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(u=o.map(([p,d])=>({id:p,request:void 0,response:d})));let l=t.examples.filter(p=>s_t(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=>Pa(p));return u.length===0?[$4.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:void 0,response:void 0,codeSamples:l})]:u.map(({id:p,request:d,response:f})=>$4.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:d,response:f,codeSamples:l}))}convertCodeSamples(t){return t.map(r=>"language"in r?DH.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):DH.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?a_.Csharp:r.sdk,code:r.code})).filter(Pa)}isSchemaRequired(t){return Ifr(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function XDl(e,t){let r=[];if(e.length<=1){let[i,o]=e[0]??[];if(t.length===0)return r.push({id:i,request:o,response:void 0}),r;for(let[s,a]of t)r.push({id:s??i,request:o,response:a});return r}if(t.length<=1){let[i,o]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:o}),r;for(let[s,a]of e)r.push({id:s??i,request:a,response:o});return r}let n=new Set;for(let[i,o]of e){let s=t.find(([c])=>c==null)?.[1]??t[0]?.[1];if(i==null){if(s==null)continue;r.push({id:void 0,request:o,response:s});continue}let a=!1;for(let c=0;c<t.length;c++){let[u,l]=t[c];u==null||n.has(c)||i===u&&(r.push({id:i,request:o,response:l}),u!=null&&n.add(c),a=!0)}!a&&s!=null&&r.push({id:i,request:o,response:s})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[o,s]=t[i],a=e.find(([c])=>c==null)?.[1]??e[0]?.[1];a!=null&&r.push({id:o,request:a,response:s})}return r}function ZDl(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:tRl(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function eRl(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 AG(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return AG(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return AG(e.value.value);default:return!1}case"null":return!0;default:we(e)}}function tRl(e){return Dr.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:gG(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(Pa),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 O9e=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new wAe(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let s=[];for(let a of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!AG(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let u=[];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&&!AG(f)&&(f=void 0),!(d&&f==null)&&f!=null&&u.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=Mn(f.payload)?t.resolveSchemaReference(f.payload):f.payload,h=this.exampleTypeFactory.buildExample({schema:ic(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:c,headers:u,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),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!AG(c)&&(c=void 0),a&&c==null)return;c!=null&&i.push({name:s.name,value:c})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!AG(c)&&(c=void 0),a&&c==null)return;c!=null&&o.push({name:s.name,value:c})}for(let s of r){let a=this.exampleTypeFactory.buildExample({schema:s.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});a!=null&&n.messages.push({messageType:s.type,payload:a,description:void 0})}return n}isSchemaRequired(t){return Ifr(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 O0={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 Cfr(e){return qr(e,O0.FERN_EXAMPLES)??[]}function xfr(e,t){return t.includes("://")?t:`${e}://${t}`}function _fr(e){return e.startsWith("/")?e:"/"+e}function hTs({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[u,l]of Object.entries(i.components?.schemas??{})){let p=ic(l,!1,!1,e,[u],r,e.namespace);o[u]=p}let a=new O9e(o,e),c={};for(let[u,l]of Object.entries(i.servers??{})){let p=qr(l,O0.FERN_SERVER_NAME);c[u]={name:p??u,url:xfr(l.protocol,l.url)}}for(let[u,l]of Object.entries(i.channels??{})){let p=qr(l,O0.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${u} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(l.parameters!=null)for(let[A,b]of Object.entries(l.parameters??{})){let v=qr(b,O0.FERN_PARAMETER_NAME);d.push({name:A,description:b.description,parameterNameOverride:v,schema:b.schema!=null?ic(b.schema,!1,!1,e,t,r,e.namespace):Dr.primitive({schema:Di.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:sw(b),source:r,explode:void 0,clientDefault: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[b,v]of Object.entries(l.bindings.ws.headers.properties??{})){if(Mn(v)){let x=e.resolveSchemaReference(v),C=A.includes(b),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];f.push({name:b,schema:bM(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,env:void 0,availability:sw(x),source:r,clientDefault:void 0});continue}let E=A.includes(b),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];f.push({name:b,schema:ic(v,I,w,e,[...t,b],r,e.namespace),description:v.description,parameterNameOverride:void 0,env:void 0,availability:sw(v),source:r,clientDefault:void 0})}}if(l.bindings.ws.query!=null){let A=l.bindings.ws.query.required??[];for(let[b,v]of Object.entries(l.bindings.ws.query.properties??{})){if(Mn(v)){let x=e.resolveSchemaReference(v),C=A.includes(b),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];m.push({name:b,schema:bM(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,availability:sw(x),source:r,explode:void 0,clientDefault:void 0});continue}let E=A.includes(b),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];m.push({name:b,schema:ic(v,I,w,e,[...t,b],r,e.namespace),description:v.description,parameterNameOverride:void 0,availability:sw(v),source:r,explode:void 0,clientDefault:void 0})}}}let h;l.publish!=null&&("oneOf"in l.publish.message?h=dTs({generatedName:l.publish.operationId??"PublishEvent",event:l.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):h=mTs({action:"Publish",channelPath:u,message:l.publish.message,context:e,source:r}));let g;if(l.subscribe!=null&&("oneOf"in l.subscribe.message?g=dTs({generatedName:l.subscribe.operationId??"SubscribeEvent",event:l.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=mTs({action:"Subscribe",channelPath:u,message:l.subscribe.message,context:e,source:r})),f.length>0||m.length>0||h!=null||g!=null){let A=Cfr(l),b=[];if(A.length>0)b=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&&b.push(x)}let v=qr(l,O0.FERN_CHANNEL_ADDRESS),E=v??_fr(u),I=[];h!=null&&I.push({origin:"client",name:"publish",body:cd(h),methodName:l.publish!=null?qr(l.publish,O0.FERN_SDK_METHOD_NAME):void 0}),g!=null&&I.push({origin:"server",name:"subscribe",body:cd(g),methodName:l.subscribe!=null?qr(l.subscribe,O0.FERN_SDK_METHOD_NAME):void 0}),s[u]={audiences:qr(l,On.AUDIENCES)??[],handshake:{headers:f.map(w=>({...w,schema:cd(w.schema),env:w.env})),queryParameters:m.map(w=>({...w,schema:cd(w.schema)})),pathParameters:d.map(w=>({...w,schema:cd(w.schema)}))},groupName:e.resolveGroupName([qr(l,O0.FERN_SDK_GROUP_NAME)??u]),messages:I,servers:(l.servers?.map(w=>c[w])??Object.values(c)).filter(w=>w!=null&&w.name!=null).map(w=>({...w,name:w.name})),summary:qr(l,O0.FERN_DISPLAY_NAME),connectMethodName:qr(l,O0.FERN_SDK_METHOD_NAME),path:E,description:l.description,examples:b,source:r}}}return{groupedSchemas:_9e(e.namespace,o),channels:s??void 0,servers:Object.values(c).map(u=>({...u,name:u.name})),basePath:qr(i,O0.BASE_PATH)}}function dTs({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:s}){if("oneOf"in t.message&&t.message.oneOf!=null){let a=[],c=[];for(let u of t.message.oneOf){let l,p={type:"notFound"};if(Mn(u)){let d=r.resolveMessageReference(u);!Mn(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=u;c.push(p),a.push(l)}return vAe({description:t.description??t.message.description,availability:sw(t.message),subtypes:a,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:s.naming==="v2"?c:[]})}}function mTs({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return Mn(r.payload)&&(o=n.resolveSchemaReference(r.payload)),ic(o,!1,!1,n,[t,e],i,n.namespace)}}var Sfr=class extends x9e{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 c=t.$ref.split("/"),u=c[2],l=c[4],p=u?.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}};Tt();Ni();var gTs="#/channels/",ATs="#/servers/",HEi="$message.";function bTs({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){Efr();let o={},s={},a={},c=[],u={};e.logger.debug("Parsing V3 AsyncAPI...");let l=UH();for(let[x,C]of Object.entries(i.components?.schemas??{})){let _=l.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);o[_]=ic(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 G=e.resolveMessageReference(R);a[_].push({channelId:x,payload:G.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]=ic(_.payload,!1,!1,e,[x],r,e.namespace)}else{c.push(x);for(let{channelId:_,payload:R}of C){let G=`${_}_${x}`;s[_]||(s[_]={}),s[_][G]=ic(R,!1,!1,e,[G],r,e.namespace)}}let p={},d=UH();for(let[x,C]of Object.entries(s))for(let[_,R]of Object.entries(C)){let G=d.getUniqueSchemaId(_,e.logger,e.options.resolveSchemaCollisions);p[G]=R}let f=new O9e({...o,...p},e),m={};for(let[x,C]of Object.entries(i.servers??{})){let _=qr(C,O0.FERN_SERVER_NAME);m[x]={name:_??x,url:xfr(C.protocol,C.host)}}let h={},g=Object.keys(i.channels??{});for(let[x,C]of Object.entries(i.operations??{})){if(qr(C,O0.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 _=nRl(C);h[_]||(h[_]={subscribe:[],publish:[],__parsedMessages:[]});let R=qr(C,O0.FERN_SDK_METHOD_NAME);if(!C.messages||!Array.isArray(C.messages))continue;let G=C.messages.filter(z=>z!=null&&z.$ref!=null).map(z=>({ref:z,methodName:R})),V=h[_];if(V==null)throw new Error(`Internal error: channelEvents["${_}"] is unexpectedly undefined for operation ${x}`);if(C.action==="receive")V.subscribe.push(...G);else if(C.action==="send")V.publish.push(...G);else throw new Error(`Operation ${x} has an invalid action: ${C.action}`)}for(let[x,C]of Object.entries(h)){let _=[];_.push(...yTs({messages:C.subscribe,channelPath:x,origin:"server",messageSchemas:s[x]??{},duplicatedMessageIds:c,context:e})),_.push(...yTs({messages:C.publish,channelPath:x,origin:"client",messageSchemas:s[x]??{},duplicatedMessageIds:c,context:e})),h[x]!=null&&(h[x].__parsedMessages=_)}for(let[x,C]of Object.entries(i.channels??{})){if(qr(C,O0.IGNORE))continue;let _=[],R=[],G=[];if(C.parameters!=null)for(let[V,z]of Object.entries(C.parameters)){let K=e.isReferenceObject(z)?e.resolveParameterReference(z):z,{type:ie,parameterKey:q}=K.location!=null?iRl(K.location):{type:C.address?.includes(`={${V}}`)?"query":"path",parameterKey:V},H=qr(K,O0.FERN_PARAMETER_OPTIONAL),ye=Du(Jn(x))+Du(Jn(V)),Ee=K.schema!=null?Mn(K.schema)?bM(K.schema,!1,!1,e,[q],void 0,r,e.namespace):ic(K.schema,!1,!1,e,[q],r,e.namespace):ic({...K,type:"string",title:ye,example:K.examples?.[0],default:K.default,enum:K.enum,required:void 0},!1,!1,e,[q],r,e.namespace),Z=H?Dr.optional({value:Ee,description:void 0,availability:void 0,generatedName:"",title:ye,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Ee,te={name:q,description:K.description,parameterNameOverride:void 0,schema:Z,variableReference:void 0,availability:sw(z),source:r,explode:void 0,clientDefault:void 0};ie==="header"?_.push({...te,env:void 0}):ie==="path"?R.push(te):(ie==="payload"||ie==="query")&&G.push(te)}if(C.bindings?.ws?.query!=null){let V=new Set(G.map(K=>K.name)),z=new Set(C.bindings.ws.query.required??[]);for(let[K,ie]of Object.entries(C.bindings.ws.query.properties??{})){if(V.has(K))continue;if(Mn(ie)){let Ee=e.resolveSchemaReference(ie),Z=z.has(K),[te,be]=e.options.coerceOptionalSchemasToNullable?[!1,!Z]:[!Z,!1];G.push({name:K,schema:bM(ie,te,be,e,[x,K],void 0,r,e.namespace),description:Ee.description,parameterNameOverride:void 0,availability:sw(Ee),source:r,explode:void 0,clientDefault:void 0});continue}let q=z.has(K),[H,ye]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];G.push({name:K,schema:ic(ie,H,ye,e,[x,K],r,e.namespace),description:ie.description,parameterNameOverride:void 0,availability:sw(ie),source:r,explode:void 0,clientDefault:void 0})}}if(C.bindings?.ws?.headers!=null){let V=new Set(_.map(K=>K.name)),z=new Set(C.bindings.ws.headers.required??[]);for(let[K,ie]of Object.entries(C.bindings.ws.headers.properties??{})){if(V.has(K))continue;if(Mn(ie)){let Ee=e.resolveSchemaReference(ie),Z=z.has(K),[te,be]=e.options.coerceOptionalSchemasToNullable?[!1,!Z]:[!Z,!1];_.push({name:K,schema:bM(ie,te,be,e,[x,K],void 0,r,e.namespace),description:Ee.description,parameterNameOverride:void 0,env:void 0,availability:sw(Ee),source:r,clientDefault:void 0});continue}let q=z.has(K),[H,ye]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];_.push({name:K,schema:ic(ie,H,ye,e,[x,K],r,e.namespace),description:ie.description,parameterNameOverride:void 0,env:void 0,availability:sw(ie),source:r,clientDefault:void 0})}}if(_.length>0||G.length>0||h[x]!=null&&(h[x].publish!=null||h[x].subscribe!=null)){let V=Cfr(C),z=h[x]?.__parsedMessages??[],K=[];try{if(V.length>0)K=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:V,handshake:{headers:_,queryParameters:G},source:r,namespace:e.namespace});else{let Ee=[],{examplePublishMessage:Z,exampleSubscribeMessage:te}=sRl({messages:z,messageSchemas:s[x]??{}});Z!=null&&Ee.push(Z),te!=null&&Ee.push(te);let be=f.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:G},messages:Ee});be!=null&&K.push(be)}}catch(Ee){e.logger.warn(`Failed to build examples for channel ${x}: ${ji(Ee)}`)}let ie=qr(C,O0.FERN_SDK_GROUP_NAME),q=qr(C,O0.FERN_SDK_METHOD_NAME),H=(C.servers?.map(Ee=>oRl(m,Ee))??Object.values(m)).map(Ee=>({...Ee,name:Ee.name})),ye=C.address?.split("?")[0]??_fr(x);u[x]={audiences:qr(C,On.AUDIENCES)??[],handshake:{headers:_.map(Ee=>({...Ee,schema:cd(Ee.schema),env:Ee.env})),queryParameters:G.map(Ee=>({...Ee,schema:cd(Ee.schema)})),pathParameters:R.map(Ee=>({...Ee,parameterNameOverride:void 0,schema:cd(Ee.schema)}))},groupName:e.resolveGroupName(typeof ie=="string"?[ie]:ie??[x]),messages:z,summary:qr(C,O0.FERN_DISPLAY_NAME),connectMethodName:q,servers:H,path:ye,description:C.description,examples:K,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},b={},v=UH();for(let[x,C]of Object.entries(A)){let _=v.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);b[_]=cd(C)}let E=_9e(e.namespace,o),I=Object.values(m).map(x=>({...x,name:x.name})),w=qr(i,O0.BASE_PATH);return{groupedSchemas:E,channels:u,servers:I,basePath:w}}function rRl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function nRl(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(gTs))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return rRl(e.channel.$ref.substring(gTs.length))}function iRl(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(HEi))throw new Error(`Invalid location format: ${e}; expected ${HEi} prefix`);let n=t.substring(HEi.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 oRl(e,t){if(!t.$ref.startsWith(ATs))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(ATs.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function yTs({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,c)=>{try{let l=o.resolveMessageReference(a.ref,!0).name;i.includes(l)&&(l=`${t}_${l}`);let p=n[l];p!=null&&s.push({origin:r,name:l??`${r}Message${c+1}`,body:cd(p),methodName:a.methodName})}catch(u){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${ji(u)}`)}}),s}function sRl({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 ETs({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let s=[];if(o!=null&&s.push(o),parseFloat(e.asyncapi)<3){let a=e;a.tags?.[0]!=null?s.push(a.tags[0].name):i.naming!=="v2"&&s.push("websocket");let c=new vfr({document:a,taskContext:t,options:r,namespace:o});return hTs({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,c=new Sfr({document:a,taskContext:t,options:r,namespace:o});return bTs({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}Tt();Ni();Ni();function vTs(e){return qr(e,On.ASYNC_CONFIG)}var ITs="$request.";function wTs(e){let t=qr(e,On.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:aRl(t["stream-condition"]),streamRequestName:t["stream-request-name"],responseStream:t["response-stream"],response:t.response}}function aRl(e){return e.startsWith(ITs)?e.slice(ITs.length):e}function CTs(e){let t=e;if(t.cursor!=null)return BC.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return BC.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return BC.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return BC.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 BC.custom({results:i.results})}throw new Error("Invalid pagination extension")}function xTs(e,t){let r=qr(t,On.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=qr(e,On.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:CTs(n)}return CTs(r)}}function _Ts(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:T9e(n,t)}}}function STs(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function cRl(e){return e.includes("json")||e==="*/*"}function KEi({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Ofr({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function Ofr({mediaType:e,mediaTypeObject:t,context:r}){if(!cRl(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:T9e(t,r)}}function a_t({content:e,context:t}){let r=KEi({content:e,context:t});if(!r)return;let[n,i]=r;return Ofr({mediaType:n,mediaTypeObject:i,context:t})}function OTs(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:T9e(n,t)}}}function T9e(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=qr(e,j1.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let s=Mn(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}Tt();Tt();function TTs(e){let t=uRl(e),r={};return JEi({obj:t,occurrences:r,breadcrumbs:[]}),r}function JEi({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)JEi({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)JEi({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function uRl(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?c_t(r.get):void 0,put:r?.put!=null?c_t(r.put):void 0,post:r?.post!=null?c_t(r.post):void 0,patch:r?.patch!=null?c_t(r.patch):void 0,delete:r?.delete!=null?c_t(r.delete):void 0}]))}}function c_t(e){return{...e,requestBody:e.requestBody!=null?Mn(e.requestBody)?e.requestBody:lRl(e.requestBody):void 0}}function lRl(e){let t,r;for(let n in e.content){let i=Lf.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[Lf.MULTIPART_FORM_DATA]:r}}:e}var Tfr=class{endpoints;parser=new Wae;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 BTs="#/components/parameters/",PTs="#/components/responses/",DTs="#/components/examples/",RTs="#/components/requestBodies/",FTs="#/components/securitySchemes/",B9e=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=TTs(t),this.options=i,this.source=o,this.filter=new Tfr({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=s,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Mn(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(BTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(BTs.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(RTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(RTs.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(PTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(PTs.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(DTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(DTs.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(FTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(FTs.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;for(let[r,n]of Object.entries(this.document.components.schemas))!n||Mn(n)||t.set(r,qr(n,On.SDK_NAMESPACE)||this.namespace);return t}};var lRe=class extends B9e{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){}};Tt();var kfr=require("fs"),Nfr=require("path");var yt={};X(yt,{BRAND:()=>NRl,DIRTY:()=>pRe,EMPTY_PATH:()=>mRl,INVALID:()=>Rc,NEVER:()=>EFl,OK:()=>XT,ParseStatus:()=>Q1,Schema:()=>xp,ZodAny:()=>_Ae,ZodArray:()=>xce,ZodBigInt:()=>dRe,ZodBoolean:()=>mRe,ZodBranded:()=>l_t,ZodCatch:()=>xRe,ZodDate:()=>hRe,ZodDefault:()=>CRe,ZodDiscriminatedUnion:()=>Dfr,ZodEffects:()=>tz,ZodEnum:()=>IRe,ZodError:()=>Zk,ZodFirstPartyTypeKind:()=>au,ZodFunction:()=>Ffr,ZodIntersection:()=>bRe,ZodIssueCode:()=>gn,ZodLazy:()=>ERe,ZodLiteral:()=>vRe,ZodMap:()=>N9e,ZodNaN:()=>Q9e,ZodNativeEnum:()=>wRe,ZodNever:()=>yG,ZodNull:()=>ARe,ZodNullable:()=>GH,ZodNumber:()=>fRe,ZodObject:()=>eN,ZodOptional:()=>Z4,ZodParsedType:()=>ns,ZodPipeline:()=>p_t,ZodPromise:()=>SAe,ZodReadonly:()=>_Re,ZodRecord:()=>Rfr,ZodSchema:()=>xp,ZodSet:()=>j9e,ZodString:()=>xAe,ZodSymbol:()=>F9e,ZodTransformer:()=>tz,ZodTuple:()=>qH,ZodType:()=>xp,ZodUndefined:()=>gRe,ZodUnion:()=>yRe,ZodUnknown:()=>Cce,ZodVoid:()=>k9e,addIssueToContext:()=>So,any:()=>GRl,array:()=>KRl,bigint:()=>LRl,boolean:()=>GTs,coerce:()=>bFl,custom:()=>zTs,date:()=>URl,datetimeRegex:()=>LTs,defaultErrorMap:()=>Ice,discriminatedUnion:()=>ZRl,effect:()=>pFl,enum:()=>cFl,function:()=>oFl,getErrorMap:()=>P9e,getParsedType:()=>VH,instanceof:()=>QRl,intersection:()=>eFl,isAborted:()=>Bfr,isAsync:()=>D9e,isDirty:()=>Pfr,isValid:()=>CAe,late:()=>jRl,lazy:()=>sFl,literal:()=>aFl,makeIssue:()=>u_t,map:()=>nFl,nan:()=>MRl,nativeEnum:()=>uFl,never:()=>$Rl,null:()=>qRl,nullable:()=>dFl,number:()=>qTs,object:()=>JRl,objectUtil:()=>YEi,oboolean:()=>yFl,onumber:()=>AFl,optional:()=>fFl,ostring:()=>gFl,pipeline:()=>hFl,preprocess:()=>mFl,promise:()=>lFl,quotelessJson:()=>pRl,record:()=>rFl,set:()=>iFl,setErrorMap:()=>dRl,strictObject:()=>YRl,string:()=>VTs,symbol:()=>zRl,transformer:()=>pFl,tuple:()=>tFl,undefined:()=>VRl,union:()=>XRl,unknown:()=>WRl,util:()=>lf,void:()=>HRl});var lf;(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})(lf||(lf={}));var YEi;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(YEi||(YEi={}));var ns=lf.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),VH=e=>{switch(typeof e){case"undefined":return ns.undefined;case"string":return ns.string;case"number":return Number.isNaN(e)?ns.nan:ns.number;case"boolean":return ns.boolean;case"function":return ns.function;case"bigint":return ns.bigint;case"symbol":return ns.symbol;case"object":return Array.isArray(e)?ns.array:e===null?ns.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ns.promise:typeof Map<"u"&&e instanceof Map?ns.map:typeof Set<"u"&&e instanceof Set?ns.set:typeof Date<"u"&&e instanceof Date?ns.date:ns.object;default:return ns.unknown}};var gn=lf.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"]),pRl=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Zk=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,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};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,lf.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()}};Zk.create=e=>new Zk(e);var fRl=(e,t)=>{let r;switch(e.code){case gn.invalid_type:e.received===ns.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case gn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,lf.jsonStringifyReplacer)}`;break;case gn.unrecognized_keys:r=`Unrecognized key(s) in object: ${lf.joinValues(e.keys,", ")}`;break;case gn.invalid_union:r="Invalid input";break;case gn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${lf.joinValues(e.options)}`;break;case gn.invalid_enum_value:r=`Invalid enum value. Expected ${lf.joinValues(e.options)}, received '${e.received}'`;break;case gn.invalid_arguments:r="Invalid function arguments";break;case gn.invalid_return_type:r="Invalid function return type";break;case gn.invalid_date:r="Invalid date";break;case gn.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}"`:lf.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case gn.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 gn.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 gn.custom:r="Invalid input";break;case gn.invalid_intersection_types:r="Intersection results could not be merged";break;case gn.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case gn.not_finite:r="Number must be finite";break;default:r=t.defaultError,lf.assertNever(e)}return{message:r}},Ice=fRl;var kTs=Ice;function dRl(e){kTs=e}function P9e(){return kTs}var u_t=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="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},mRl=[];function So(e,t){let r=P9e(),n=u_t({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Ice?void 0:Ice].filter(i=>!!i)});e.common.issues.push(n)}var Q1=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 Rc;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 Rc;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}}},Rc=Object.freeze({status:"aborted"}),pRe=e=>({status:"dirty",value:e}),XT=e=>({status:"valid",value:e}),Bfr=e=>e.status==="aborted",Pfr=e=>e.status==="dirty",CAe=e=>e.status==="valid",D9e=e=>typeof Promise<"u"&&e instanceof Promise;var wa;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(wa||(wa={}));var ez=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}},NTs=(e,t)=>{if(CAe(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 Zk(e.common.issues);return this._error=r,this._error}}};function Xl(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:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var xp=class{get description(){return this._def.description}_getType(t){return VH(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:VH(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Q1,ctx:{common:t.parent.common,data:t.data,parsedType:VH(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(D9e(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:VH(t)},i=this._parseSync({data:t,path:n.path,parent:n});return NTs(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:VH(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return CAe(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=>CAe(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:VH(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(D9e(i)?i:Promise.resolve(i));return NTs(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:gn.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!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 tz({schema:this,typeName:au.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 Z4.create(this,this._def)}nullable(){return GH.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xce.create(this)}promise(){return SAe.create(this,this._def)}or(t){return yRe.create([this,t],this._def)}and(t){return bRe.create(this,t,this._def)}transform(t){return new tz({...Xl(this._def),schema:this,typeName:au.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new CRe({...Xl(this._def),innerType:this,defaultValue:r,typeName:au.ZodDefault})}brand(){return new l_t({typeName:au.ZodBranded,type:this,...Xl(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new xRe({...Xl(this._def),innerType:this,catchValue:r,typeName:au.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return p_t.create(this,t)}readonly(){return _Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},hRl=/^c[^\s-]{8,}$/i,gRl=/^[0-9a-z]+$/,ARl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yRl=/^[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,bRl=/^[a-z0-9_-]{21}$/i,ERl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vRl=/^[-+]?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)?)??$/,IRl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wRl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",XEi,CRl=/^(?:(?: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])$/,xRl=/^(?:(?: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])$/,_Rl=/^(([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]))$/,SRl=/^(([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])$/,ORl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TRl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,QTs="((\\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])))",BRl=new RegExp(`^${QTs}$`);function MTs(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 PRl(e){return new RegExp(`^${MTs(e)}$`)}function LTs(e){let t=`${QTs}T${MTs(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 DRl(e,t){return!!((t==="v4"||!t)&&CRl.test(e)||(t==="v6"||!t)&&_Rl.test(e))}function RRl(e,t){if(!ERl.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 FRl(e,t){return!!((t==="v4"||!t)&&xRl.test(e)||(t==="v6"||!t)&&SRl.test(e))}var xAe=class e extends xp{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ns.string){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.string,received:o.parsedType}),Rc}let n=new Q1,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),So(i,{code:gn.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),So(i,{code:gn.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?So(i,{code:gn.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&So(i,{code:gn.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")IRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"email",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")XEi||(XEi=new RegExp(wRl,"u")),XEi.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"emoji",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")yRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"uuid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")bRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"nanoid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")hRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cuid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")gRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cuid2",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ARl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"ulid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),So(i,{validation:"url",code:gn.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),So(i,{validation:"regex",code:gn.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),So(i,{code:gn.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),So(i,{code:gn.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?LTs(o).test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?BRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?PRl(o).test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?vRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"duration",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?DRl(t.data,o.version)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"ip",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?RRl(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"jwt",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?FRl(t.data,o.version)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cidr",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ORl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"base64",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?TRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"base64url",code:gn.invalid_string,message:o.message}),n.dirty()):lf.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:gn.invalid_string,...wa.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...wa.errToObj(t)})}url(t){return this._addCheck({kind:"url",...wa.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...wa.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...wa.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...wa.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...wa.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...wa.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...wa.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...wa.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...wa.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...wa.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...wa.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...wa.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,...wa.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,...wa.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...wa.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...wa.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...wa.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...wa.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...wa.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...wa.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...wa.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...wa.errToObj(r)})}nonempty(t){return this.min(1,wa.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}};xAe.create=e=>new xAe({checks:[],typeName:au.ZodString,coerce:e?.coerce??!1,...Xl(e)});function kRl(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 fRe=class e extends xp{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)!==ns.number){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.number,received:o.parsedType}),Rc}let n,i=new Q1;for(let o of this._def.checks)o.kind==="int"?lf.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),So(n,{code:gn.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),So(n,{code:gn.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),So(n,{code:gn.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?kRl(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),So(n,{code:gn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),So(n,{code:gn.not_finite,message:o.message}),i.dirty()):lf.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,wa.toString(r))}gt(t,r){return this.setLimit("min",t,!1,wa.toString(r))}lte(t,r){return this.setLimit("max",t,!0,wa.toString(r))}lt(t,r){return this.setLimit("max",t,!1,wa.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:wa.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:wa.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:wa.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:wa.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:wa.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:wa.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:wa.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:wa.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:wa.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:wa.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"&&lf.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)}};fRe.create=e=>new fRe({checks:[],typeName:au.ZodNumber,coerce:e?.coerce||!1,...Xl(e)});var dRe=class e extends xp{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)!==ns.bigint)return this._getInvalidInput(t);let n,i=new Q1;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),So(n,{code:gn.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),So(n,{code:gn.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),So(n,{code:gn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):lf.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return So(r,{code:gn.invalid_type,expected:ns.bigint,received:r.parsedType}),Rc}gte(t,r){return this.setLimit("min",t,!0,wa.toString(r))}gt(t,r){return this.setLimit("min",t,!1,wa.toString(r))}lte(t,r){return this.setLimit("max",t,!0,wa.toString(r))}lt(t,r){return this.setLimit("max",t,!1,wa.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:wa.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:wa.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:wa.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:wa.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:wa.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:wa.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}};dRe.create=e=>new dRe({checks:[],typeName:au.ZodBigInt,coerce:e?.coerce??!1,...Xl(e)});var mRe=class extends xp{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ns.boolean){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.boolean,received:n.parsedType}),Rc}return XT(t.data)}};mRe.create=e=>new mRe({typeName:au.ZodBoolean,coerce:e?.coerce||!1,...Xl(e)});var hRe=class e extends xp{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ns.date){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.date,received:o.parsedType}),Rc}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_date}),Rc}let n=new Q1,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),So(i,{code:gn.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),So(i,{code:gn.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):lf.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:wa.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:wa.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}};hRe.create=e=>new hRe({checks:[],coerce:e?.coerce||!1,typeName:au.ZodDate,...Xl(e)});var F9e=class extends xp{_parse(t){if(this._getType(t)!==ns.symbol){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.symbol,received:n.parsedType}),Rc}return XT(t.data)}};F9e.create=e=>new F9e({typeName:au.ZodSymbol,...Xl(e)});var gRe=class extends xp{_parse(t){if(this._getType(t)!==ns.undefined){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.undefined,received:n.parsedType}),Rc}return XT(t.data)}};gRe.create=e=>new gRe({typeName:au.ZodUndefined,...Xl(e)});var ARe=class extends xp{_parse(t){if(this._getType(t)!==ns.null){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.null,received:n.parsedType}),Rc}return XT(t.data)}};ARe.create=e=>new ARe({typeName:au.ZodNull,...Xl(e)});var _Ae=class extends xp{constructor(){super(...arguments),this._any=!0}_parse(t){return XT(t.data)}};_Ae.create=e=>new _Ae({typeName:au.ZodAny,...Xl(e)});var Cce=class extends xp{constructor(){super(...arguments),this._unknown=!0}_parse(t){return XT(t.data)}};Cce.create=e=>new Cce({typeName:au.ZodUnknown,...Xl(e)});var yG=class extends xp{_parse(t){let r=this._getOrReturnCtx(t);return So(r,{code:gn.invalid_type,expected:ns.never,received:r.parsedType}),Rc}};yG.create=e=>new yG({typeName:au.ZodNever,...Xl(e)});var k9e=class extends xp{_parse(t){if(this._getType(t)!==ns.undefined){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.void,received:n.parsedType}),Rc}return XT(t.data)}};k9e.create=e=>new k9e({typeName:au.ZodVoid,...Xl(e)});var xce=class e extends xp{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==ns.array)return So(r,{code:gn.invalid_type,expected:ns.array,received:r.parsedType}),Rc;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(So(r,{code:s?gn.too_big:gn.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&&(So(r,{code:gn.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&&(So(r,{code:gn.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 ez(r,s,r.path,a)))).then(s=>Q1.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new ez(r,s,r.path,a)));return Q1.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:wa.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:wa.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:wa.toString(r)}})}nonempty(t){return this.min(1,t)}};xce.create=(e,t)=>new xce({type:e,minLength:null,maxLength:null,exactLength:null,typeName:au.ZodArray,...Xl(t)});function R9e(e){if(e instanceof eN){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Z4.create(R9e(n))}return new eN({...e._def,shape:()=>t})}else return e instanceof xce?new xce({...e._def,type:R9e(e.element)}):e instanceof Z4?Z4.create(R9e(e.unwrap())):e instanceof GH?GH.create(R9e(e.unwrap())):e instanceof qH?qH.create(e.items.map(t=>R9e(t))):e}var eN=class e extends xp{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=lf.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ns.object){let u=this._getOrReturnCtx(t);return So(u,{code:gn.invalid_type,expected:ns.object,received:u.parsedType}),Rc}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof yG&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=o[u],p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ez(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof yG){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(So(i,{code:gn.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ez(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let p=await l.key,d=await l.value;u.push({key:p,value:d,alwaysSet:l.alwaysSet})}return u}).then(u=>Q1.mergeObjectSync(n,u)):Q1.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return wa.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:wa.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:au.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 lf.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 lf.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return R9e(this)}partial(t){let r={};for(let n of lf.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 lf.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Z4;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return UTs(lf.objectKeys(this.shape))}};eN.create=(e,t)=>new eN({shape:()=>e,unknownKeys:"strip",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});eN.strictCreate=(e,t)=>new eN({shape:()=>e,unknownKeys:"strict",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});eN.lazycreate=(e,t)=>new eN({shape:e,unknownKeys:"strip",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});var yRe=class extends xp{_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 Zk(a.ctx.common.issues));return So(r,{code:gn.invalid_union,unionErrors:s}),Rc}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 c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new Zk(c));return So(r,{code:gn.invalid_union,unionErrors:a}),Rc}}get options(){return this._def.options}};yRe.create=(e,t)=>new yRe({options:e,typeName:au.ZodUnion,...Xl(t)});var wce=e=>e instanceof ERe?wce(e.schema):e instanceof tz?wce(e.innerType()):e instanceof vRe?[e.value]:e instanceof IRe?e.options:e instanceof wRe?lf.objectValues(e.enum):e instanceof CRe?wce(e._def.innerType):e instanceof gRe?[void 0]:e instanceof ARe?[null]:e instanceof Z4?[void 0,...wce(e.unwrap())]:e instanceof GH?[null,...wce(e.unwrap())]:e instanceof l_t||e instanceof _Re?wce(e.unwrap()):e instanceof xRe?wce(e._def.innerType):[],Dfr=class e extends xp{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.object)return So(r,{code:gn.invalid_type,expected:ns.object,received:r.parsedType}),Rc;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}):(So(r,{code:gn.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Rc)}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=wce(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:au.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Xl(n)})}};function ZEi(e,t){let r=VH(e),n=VH(t);if(e===t)return{valid:!0,data:e};if(r===ns.object&&n===ns.object){let i=lf.objectKeys(t),o=lf.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=ZEi(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===ns.array&&n===ns.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],c=ZEi(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===ns.date&&n===ns.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var bRe=class extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Bfr(o)||Bfr(s))return Rc;let a=ZEi(o.value,s.value);return a.valid?((Pfr(o)||Pfr(s))&&r.dirty(),{status:r.value,value:a.data}):(So(n,{code:gn.invalid_intersection_types}),Rc)};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}))}};bRe.create=(e,t,r)=>new bRe({left:e,right:t,typeName:au.ZodIntersection,...Xl(r)});var qH=class e extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ns.array)return So(n,{code:gn.invalid_type,expected:ns.array,received:n.parsedType}),Rc;if(n.data.length<this._def.items.length)return So(n,{code:gn.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Rc;!this._def.rest&&n.data.length>this._def.items.length&&(So(n,{code:gn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ez(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Q1.mergeArray(r,s)):Q1.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};qH.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qH({items:e,typeName:au.ZodTuple,rest:null,...Xl(t)})};var Rfr=class e extends xp{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!==ns.object)return So(n,{code:gn.invalid_type,expected:ns.object,received:n.parsedType}),Rc;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new ez(n,a,n.path,a)),value:s._parse(new ez(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Q1.mergeObjectAsync(r,i):Q1.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof xp?new e({keyType:t,valueType:r,typeName:au.ZodRecord,...Xl(n)}):new e({keyType:xAe.create(),valueType:t,typeName:au.ZodRecord,...Xl(r)})}},N9e=class extends xp{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!==ns.map)return So(n,{code:gn.invalid_type,expected:ns.map,received:n.parsedType}),Rc;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new ez(n,a,n.path,[u,"key"])),value:o._parse(new ez(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return Rc;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Rc;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};N9e.create=(e,t,r)=>new N9e({valueType:t,keyType:e,typeName:au.ZodMap,...Xl(r)});var j9e=class e extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ns.set)return So(n,{code:gn.invalid_type,expected:ns.set,received:n.parsedType}),Rc;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(So(n,{code:gn.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&&(So(n,{code:gn.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(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Rc;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new ez(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:wa.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:wa.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};j9e.create=(e,t)=>new j9e({valueType:e,minSize:null,maxSize:null,typeName:au.ZodSet,...Xl(t)});var Ffr=class e extends xp{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.function)return So(r,{code:gn.invalid_type,expected:ns.function,received:r.parsedType}),Rc;function n(a,c){return u_t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P9e(),Ice].filter(u=>!!u),issueData:{code:gn.invalid_arguments,argumentsError:c}})}function i(a,c){return u_t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P9e(),Ice].filter(u=>!!u),issueData:{code:gn.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof SAe){let a=this;return XT(async function(...c){let u=new Zk([]),l=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),p=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(p,o).catch(f=>{throw u.addIssue(i(p,f)),u})})}else{let a=this;return XT(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Zk([n(c,u.error)]);let l=Reflect.apply(s,this,u.data),p=a._def.returns.safeParse(l,o);if(!p.success)throw new Zk([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:qH.create(t).rest(Cce.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||qH.create([]).rest(Cce.create()),returns:r||Cce.create(),typeName:au.ZodFunction,...Xl(n)})}},ERe=class extends xp{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})}};ERe.create=(e,t)=>new ERe({getter:e,typeName:au.ZodLazy,...Xl(t)});var vRe=class extends xp{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return So(r,{received:r.data,code:gn.invalid_literal,expected:this._def.value}),Rc}return{status:"valid",value:t.data}}get value(){return this._def.value}};vRe.create=(e,t)=>new vRe({value:e,typeName:au.ZodLiteral,...Xl(t)});function UTs(e,t){return new IRe({values:e,typeName:au.ZodEnum,...Xl(t)})}var IRe=class e extends xp{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return So(r,{expected:lf.joinValues(n),received:r.parsedType,code:gn.invalid_type}),Rc}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 So(r,{received:r.data,code:gn.invalid_enum_value,options:n}),Rc}return XT(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})}};IRe.create=UTs;var wRe=class extends xp{_parse(t){let r=lf.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ns.string&&n.parsedType!==ns.number){let i=lf.objectValues(r);return So(n,{expected:lf.joinValues(i),received:n.parsedType,code:gn.invalid_type}),Rc}if(this._cache||(this._cache=new Set(lf.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=lf.objectValues(r);return So(n,{received:n.data,code:gn.invalid_enum_value,options:i}),Rc}return XT(t.data)}get enum(){return this._def.values}};wRe.create=(e,t)=>new wRe({values:e,typeName:au.ZodNativeEnum,...Xl(t)});var SAe=class extends xp{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.promise&&r.common.async===!1)return So(r,{code:gn.invalid_type,expected:ns.promise,received:r.parsedType}),Rc;let n=r.parsedType===ns.promise?r.data:Promise.resolve(r.data);return XT(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};SAe.create=(e,t)=>new SAe({type:e,typeName:au.ZodPromise,...Xl(t)});var tz=class extends xp{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===au.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=>{So(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 Rc;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Rc:c.status==="dirty"?pRe(c.value):r.value==="dirty"?pRe(c.value):c});{if(r.value==="aborted")return Rc;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Rc:a.status==="dirty"?pRe(a.value):r.value==="dirty"?pRe(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c 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"?Rc:(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"?Rc:(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(!CAe(s))return Rc;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=>CAe(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Rc);lf.assertNever(i)}};tz.create=(e,t,r)=>new tz({schema:e,typeName:au.ZodEffects,effect:t,...Xl(r)});tz.createWithPreprocess=(e,t,r)=>new tz({schema:t,effect:{type:"preprocess",transform:e},typeName:au.ZodEffects,...Xl(r)});var Z4=class extends xp{_parse(t){return this._getType(t)===ns.undefined?XT(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Z4.create=(e,t)=>new Z4({innerType:e,typeName:au.ZodOptional,...Xl(t)});var GH=class extends xp{_parse(t){return this._getType(t)===ns.null?XT(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};GH.create=(e,t)=>new GH({innerType:e,typeName:au.ZodNullable,...Xl(t)});var CRe=class extends xp{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===ns.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};CRe.create=(e,t)=>new CRe({innerType:e,typeName:au.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xl(t)});var xRe=class extends xp{_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 D9e(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Zk(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zk(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xRe.create=(e,t)=>new xRe({innerType:e,typeName:au.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xl(t)});var Q9e=class extends xp{_parse(t){if(this._getType(t)!==ns.nan){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.nan,received:n.parsedType}),Rc}return{status:"valid",value:t.data}}};Q9e.create=e=>new Q9e({typeName:au.ZodNaN,...Xl(e)});var NRl=Symbol("zod_brand"),l_t=class extends xp{_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}},p_t=class e extends xp{_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"?Rc:o.status==="dirty"?(r.dirty(),pRe(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"?Rc: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:au.ZodPipeline})}},_Re=class extends xp{_parse(t){let r=this._def.innerType._parse(t),n=i=>(CAe(i)&&(i.value=Object.freeze(i.value)),i);return D9e(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};_Re.create=(e,t)=>new _Re({innerType:e,typeName:au.ZodReadonly,...Xl(t)});function jTs(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function zTs(e,t={},r){return e?_Ae.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=jTs(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=jTs(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):_Ae.create()}var jRl={object:eN.lazycreate},au;(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"})(au||(au={}));var QRl=(e,t={message:`Input not instance of ${e.name}`})=>zTs(r=>r instanceof e,t),VTs=xAe.create,qTs=fRe.create,MRl=Q9e.create,LRl=dRe.create,GTs=mRe.create,URl=hRe.create,zRl=F9e.create,VRl=gRe.create,qRl=ARe.create,GRl=_Ae.create,WRl=Cce.create,$Rl=yG.create,HRl=k9e.create,KRl=xce.create,JRl=eN.create,YRl=eN.strictCreate,XRl=yRe.create,ZRl=Dfr.create,eFl=bRe.create,tFl=qH.create,rFl=Rfr.create,nFl=N9e.create,iFl=j9e.create,oFl=Ffr.create,sFl=ERe.create,aFl=vRe.create,cFl=IRe.create,uFl=wRe.create,lFl=SAe.create,pFl=tz.create,fFl=Z4.create,dFl=GH.create,mFl=tz.createWithPreprocess,hFl=p_t.create,gFl=()=>VTs().optional(),AFl=()=>qTs().optional(),yFl=()=>GTs().optional(),bFl={string:(e=>xAe.create({...e,coerce:!0})),number:(e=>fRe.create({...e,coerce:!0})),boolean:(e=>mRe.create({...e,coerce:!0})),bigint:(e=>dRe.create({...e,coerce:!0})),date:(e=>hRe.create({...e,coerce:!0}))};var EFl=Rc;var vFl=yt.object({lang:yt.string(),label:yt.optional(yt.string()),source:yt.string()}),evi=yt.array(vFl);Tt();var WTs={README_EXT:"x-readme"};function IFl(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Ma(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function $Ts(e){let t=qr(e,WTs.README_EXT);if(!Ma(t))return[];let r=t["code-samples"];if(!IFl(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 wFl(e){return Ma(e)&&typeof e.$ref=="string"}function CFl(e,t){if(e!=null){if(typeof e=="string")return e;if(wFl(e)){let r=(0,Nfr.resolve)(t??process.cwd(),e.$ref);if((0,kfr.existsSync)(r))try{return(0,kfr.readFileSync)(r,"utf-8")}catch{return}}}}function xFl(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Ma(n))continue;let o=CFl(n.code,t);o!=null&&r.push({...n,code:o})}return r}function HTs(e,t,r){let n=qr(t,On.EXAMPLES),i=r.source.type==="openapi"?(0,Nfr.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!Ma(p))return p;let f=p["code-samples"];if(f!=null){let m=xFl(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=Km.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=t_t(t,j1.REDOCLY_CODE_SAMPLES_KEBAB,evi,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],u=[...t_t(t,j1.REDOCLY_CODE_SAMPLES_CAMEL,evi,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];u.length>0&&s.push({"code-samples":u.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let l=$Ts(t);return l.length>0&&s.push({"code-samples":l}),s.map($4.unknown)}function KTs(e){let t=qr(e,On.AVAILABILITY);if(t==="ga"||t==="generally-available")return o_.GenerallyAvailable;if(t==="beta"||t==="pre-release")return o_.Beta;if(t==="deprecated")return o_.Deprecated;if(e.deprecated)return o_.Deprecated}function JTs(e){let t=qr(e,On.RETRIES);if(t!=null&&t.disabled===!0)return Rg.RetriesConfiguration.disabled(t.disabled)}var _Fl="x-fern-default-url";function jfr(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=SFl(e);return{url:TFl({url:e.url,variables:e.variables??{}}),description:e.description,name:BFl(e,t),audiences:qr(e,On.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?OFl(e.variables):void 0,defaultUrl:r?n:void 0}}function SFl(e){let t=e[_Fl];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function OFl(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function TFl({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 BFl(e,t){let r=qr(e,[On.SERVER_NAME_V1,On.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 YTs(e){return qr(e,On.PARAMETER_NAME)}function XTs(e){return qr(e,On.SDK_VARIABLE)}function Qfr({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let c=Mn(a)?n.resolveParameterReference(a):a,u=qr(a,On.IGNORE)??qr(c,On.IGNORE);if(u!=null&&u){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let l=c.required??!1,p=sw(c),d=[...i,c.name],f=kb(d,n.options.preserveSchemaIds),m=c.in==="header",[h,g]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!l]:[!l,!1],A=c.schema!=null?ic(c.schema,h,g,n,d,o,n.namespace,!1,new Set,X4({schema:c,logger:n.logger})):l?Dr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Di.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:X4({schema:c,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Dr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Dr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Di.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:X4({schema:c,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(c.in==="header"&&c.schema!=null&&!Mn(c.schema)&&c.schema.default!=null){let E=c.schema.default;typeof E=="string"&&E.length>0&&(A=Dr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:LA.string(E),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let b=qr(a,On.FERN_DEFAULT)??qr(c,On.FERN_DEFAULT),v={name:c.name,schema:A,description:c.description,parameterNameOverride:YTs(c),availability:p,source:o,clientDefault:b};c.in==="query"?s.queryParameters.push({...v,explode:DFl(c)}):c.in==="path"?s.pathParameters.push({...v,variableReference:XTs(c),explode:RFl(c)}):c.in==="header"?!PFl.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?s.headers.push({...v,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return s}var PFl=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function DFl(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 RFl(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}Tt();function FFl({content:e,context:t}){for(let[r,n]of Object.entries(e))if(eBs({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function eBs({mediaType:e,mediaTypeObject:t,context:r}){if(Lf.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:T9e(t,r)}}function kFl({content:e,context:t}){for(let[r,n]of Object.entries(e))if(tBs({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function tBs({mediaType:e,mediaTypeObject:t,context:r}){if(Lf.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:T9e(t,r)}}function rBs({mediaType:e}){return Lf.parse(e)?.isBinary()??!1}function NFl({content:e}){for(let[t,r]of Object.entries(e))if(rBs({mediaType:t}))return[t,r]}function jFl(e,t){let r=Mn(e)?tvi(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!Mn(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function Lfr({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}){let a=NFl({content:e});if(a){let[d,f]=a;return WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}let c=kFl({content:e,context:n}),u=KEi({content:e,context:n}),l=QFl({json:u,multipart:c,document:r,visitor:{json:([d,f])=>WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),multipart:([d,f])=>WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),neither:()=>{}}});if(l)return l;let p=FFl({content:e,context:n});if(p){let[d,f]=p;return WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}}function QFl({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&&jFl(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function WH({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a}){let c=MFl({mediaTypeObject:t});if(rBs({mediaType:e}))return zD.octetStream({description:r,source:s,sdkMethodName:c,contentType:e});let u=tBs({mediaType:e,mediaTypeObject:t,context:i}),l=u?.schema,p=u?.encoding,d=u?.examples;if(l){let h=Mn(l)?tvi(l,n):{id:void 0,schema:l},g=ic(h.schema,!1,!1,i,o,s,a,!1),A=[];if(g.type==="object"){let b=new Set(h.schema.required??[]);for(let v of g.properties){let E=b.has(v.key),{isFile:I,isOptional:w,isArray:x,description:C}=Mfr({schema:v.schema,isOptional:!E});if(I){let _=ZTs(v.key,p);A.push({key:v.key,schema:RH.file({isOptional:w,isArray:x,description:C}),description:C,contentType:_,exploded:!1,encoding:_==null?i.options.defaultFormParameterEncoding:void 0})}else{let _=ZTs(v.key,p);A.push({key:v.key,schema:RH.json(v.schema),description:void 0,contentType:_,exploded:p?.[v.key]?.explode,encoding:_==null?i.options.defaultFormParameterEncoding:UFl(_)})}}}return zD.multipart({name:Mn(l)&&i.getNumberOfOccurrencesForRef(l)===1?h.id:void 0,description:h.schema.description,properties:A,source:s,sdkMethodName:c,fullExamples:d})}let f=Ofr({mediaType:e,mediaTypeObject:t,context:i});if(f){let h=ic(f.schema,!1,!1,i,o,s,a,!0);return zD.json({description:void 0,schema:h,contentType:f.contentType,fullExamples:f.examples,additionalProperties:!Mn(f.schema)&&n_t(f.schema.additionalProperties,i.options),source:s,sdkMethodName:c})}let m=eBs({mediaType:e,mediaTypeObject:t,context:i});if(m!=null&&m.schema!=null){let h=ic(m.schema,!1,!1,i,o,s,a,!1);return zD.formUrlEncoded({schema:h,description:r,contentType:m.contentType,source:s,fullExamples:m.examples,additionalProperties:!1,sdkMethodName:c})}}function MFl({mediaTypeObject:e}){return qr(e,On.SDK_METHOD_NAME)}var LFl={"application/json":"json"};function UFl(e){return e?LFl[e]:void 0}function tvi(e,t){if(!e.$ref.startsWith(cRe))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=w9e(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 Mn(n)?tvi(n,t):{id:r,schema:n}}function Mfr({schema:e,isOptional:t,isArray:r,description:n}){return VFl(e)?Mfr({schema:e.value,isOptional:!0,isArray:r,description:e.description}):qFl(e)?Mfr({schema:e.value,isOptional:t,isArray:r,description:e.description}):GFl(e)?Mfr({schema:e.value,isOptional:t,isArray:!0,description:e.description}):zFl(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 zFl(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function VFl(e){return e.type==="optional"}function qFl(e){return e.type==="nullable"}function GFl(e){return e.type==="array"}function ZTs(e,t){return t?.[e]?.contentType}Tt();var rvi={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"},nBs=new Set(Object.values(rvi));var WFl=["200","201","202","204"];function Ufr({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 c=$Fl({responses:t,context:r,source:a,namespace:r.namespace}),u=!1,l=!1,p;for(let d of i!=null?[i]:WFl){let f=t[d];if(f==null)continue;u=!0;let m=typeof d=="string"?parseInt(d):d;if(p==null){let h=iBs({operationContext:e,response:f,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace,statusCode:m});h!=null?p=h:m===204&&(l=!0)}else if(m===204){let h=Mn(f)?r.resolveResponseReference(f):f;a_t({context:r,content:h.content??{}})==null&&(l=!0)}}if(l&&p!=null&&p.type==="json"){let d=p.schema;d.type!=="optional"&&(p=ng.json({...p,schema:Dr.optional({value:d,description:d.type==="reference"?d.description:void 0,nameOverride:void 0,generatedName:"",groupName:void 0,namespace:void 0,availability:void 0,title:void 0,inline:void 0})}))}if(p==null&&!u&&t.default!=null&&(p=iBs({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace})),p!=null)switch(p.type){case"json":return{value:p,errors:c};case"streamingJson":case"streamingSse":return{value:p,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:p,errors:c};default:we(p)}return{value:void 0,errors:c}}function iBs({operationContext:e,streamFormat:t,streamTerminator:r,response:n,context:i,responseBreadcrumbs:o,source:s,namespace:a,statusCode:c}){let u=Mn(n)?i.resolveResponseReference(n):n;if(u.content!=null&&Object.entries(u.content).find(([f,m])=>{if(m.schema==null)return!1;let h=Mn(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?ng.bytes({description:u.description,source:s,statusCode:c}):ng.file({description:u.description,source:s,statusCode:c});let l=_Ts(u.content??{},i);if(l!=null&&t!=null)switch(t){case"json":return ng.streamingJson({statusCode:c,description:u.description,responseProperty:qr(e.operation,On.RESPONSE_PROPERTY),terminator:r,fullExamples:l.examples,schema:ic(l.schema,!1,!1,i,o,s,a),source:s});case"sse":return ng.streamingSse({description:u.description,responseProperty:void 0,terminator:r,fullExamples:l.examples,schema:ic(l.schema,!1,!1,i,o,s,a),source:s,statusCode:c})}let p=a_t({context:i,content:u.content??{}});if(p){if(t!=null)switch(t){case"json":return ng.streamingJson({description:u.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:ic(p.schema,!1,!1,i,o,s,a),source:s,statusCode:c});case"sse":return ng.streamingSse({description:u.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:ic(p.schema,!1,!1,i,o,s,a),source:s,statusCode:c})}return ng.json({description:u.description,schema:ic(p.schema,!1,!1,i,o,s,a),responseProperty:qr(e.operation,On.RESPONSE_PROPERTY),terminator:void 0,fullExamples:p.examples,source:s,statusCode:c})}for(let[d,f]of Object.entries(u.content??{})){let m=Lf.parse(d);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return ng.file({description:u.description,source:s,statusCode:c});if(m.isText()&&!d.includes("event-stream")){let h=f.schema;if(h==null)return ng.text({description:u.description,source:s,statusCode:c});let g=Mn(h)?i.resolveSchemaReference(h):h;return g.type==="string"&&g.format==="byte"?ng.file({description:u.description,source:s,statusCode:c}):ng.text({description:u.description,source:s,statusCode:c})}}}}function $Fl({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 c=Mn(s)?t.resolveResponseReference(s):s,u=OTs(c.content??{},t),l=rvi[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:c.description,schema:ic(u?.schema??{},!1,!1,t,[l,"Body"],r,n),fullExamples:u?.examples,source:r}}return i}function _ce({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,source:s,streamRequestNameOverride:a}){let{document:c,operation:u,path:l,method:p,baseBreadcrumbs:d,pathItem:f}=e,m=qr(u,On.IDEMPOTENT),h=qr(u,[On.REQUEST_NAME_V1,On.REQUEST_NAME_V2]),g=[...d,"Request"],A=Qfr({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:l,httpMethod:p,source:s}),b=/{([^}]+)}/g,v=[...l.matchAll(b)].map(z=>z[1]).filter(z=>z!==void 0),E=[...l.matchAll(b)].map(z=>z[1]);switch(t.options.pathParameterOrder){case Dn.PathParameterOrder.SpecOrder:{let z=E.filter(K=>!A.pathParameters.some(ie=>ie.name===K));if(z.length>0)for(let K of z)A.pathParameters.push({name:K??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Dr.primitive({schema:Di.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}break;case Dn.PathParameterOrder.UrlOrder:if(v.length>0){let z=new Map(A.pathParameters.map(q=>[q.name,q])),K=[],ie=new Set;for(let q of v){let H=z.get(q);ie.add(q),H?K.push(H):K.push({name:q,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Dr.primitive({schema:Di.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}for(let q of A.pathParameters)ie.has(q.name)||K.push(q);A.pathParameters=K}break;default:we(t.options.pathParameterOrder)}let I=(()=>{if(e.method==="GET")return[void 0];if(!u.requestBody)return[void 0];let z=Mn(u.requestBody)?t.resolveRequestBodyReference(u.requestBody):u.requestBody,K=Object.values(z.content).every(q=>KFl({mediaTypeObject:q})!=null),ie=[];if(K)return ie.push(...Object.entries(z.content).map(([q,H])=>{let ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:new lRe({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return oBs({context:t,convertedParameters:A})&&ye!=null&&(ye.type==="json"||ye.type==="formUrlEncoded")&&ye.schema.type!=="object"&&u.requestBody!=null?ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):u.requestBody!=null&&(ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),ye}).filter(q=>q!=null)),ie.length===0?[void 0]:ie;{let q=Lfr({content:z.content,description:z.description,document:c,context:new lRe({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return oBs({context:t,convertedParameters:A})&&q!=null&&(q.type==="json"||q.type==="formUrlEncoded")&&q.schema.type!=="object"&&u.requestBody!=null?q=Lfr({content:z.content,description:z.description,document:c,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):u.requestBody!=null&&(q=Lfr({content:z.content,description:z.description,document:c,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),[q]}})(),w=I.length>1,x=[...d,"Response"],C=Ufr({operationContext:e,streamFormat:i,streamTerminator:o,responses:u.responses,context:t,responseBreadcrumbs:x,responseStatusCode:r,source:s}),_=JTs(u),R=KTs(u),G=HTs(e,u,t),V=qr(u,On.SERVER_NAME_V2);return I.map(z=>({summary:u.summary,internal:qr(u,j1.INTERNAL),idempotent:m,audiences:qr(u,On.AUDIENCES)??[],operationId:u.operationId!=null&&n!=null?u.operationId+"_"+n:u.operationId,tags:t.resolveTagsToTagIds(u.tags),namespace:t.namespace,sdkName:JFl({operationContext:e,request:z}),pathParameters:A.pathParameters,queryParameters:A.queryParameters,headers:A.headers,requestNameOverride:a??h??void 0,generatedRequestName:kb(w?HFl({breadcrumbs:g,request:z}):g,t.options.preserveSchemaIds),request:z,response:C.value,errors:C.errors,servers:V!=null?[{name:V,url:void 0,audiences:void 0}]:(u.servers??f.servers??[]).map(K=>jfr(K,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:u.description,authed:XFl(u,c),security:YFl(u),availability:R,method:p,path:l,examples:G,pagination:e.pagination,source:s,retries:_}))}function HFl({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function KFl({mediaTypeObject:e}){return qr(e,On.SDK_METHOD_NAME)}function JFl({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 YFl(e){return e.security}function XFl(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function oBs({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function aBs({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,c=r.discriminant.value,u=r["response-status-code"],l=sBs({context:t,headerToIgnore:a,parameters:o}),p=sBs({context:t,headerToIgnore:a,parameters:s}),d=_ce({operationContext:{...e,pathItemParameters:l,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==u))}},context:t,streamFormat:void 0,source:n}),f=_ce({operationContext:{...e,pathItemParameters:l,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:u,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Dr.literal({nameOverride:void 0,generatedName:kb([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:LA.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n,clientDefault:void 0})}),{sync:d,async:f}}function sBs({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=Mn(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}Tt();var nvi="stream";function pBs({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:_ce({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=cBs({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0}),i=uBs({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let l=t.resolveSchemaReference(n.schemaReference),p=qr(l,On.TYPE_NAME);if(p!=null)return`${p}Streaming`}})(),s=_ce({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+nvi}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,nvi]},context:t,streamFormat:r.format,streamTerminator:r.terminator,suffix:nvi,source:t.source,streamRequestNameOverride:o});s.forEach(l=>{l.examples=l.examples.filter(p=>lBs(p,t)!==!1)});let a=cBs({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=uBs({operation:e.operation,response:r.response}),u=_ce({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:c}},context:t,source:t.source});return u.forEach(l=>{l.examples=l.examples.filter(p=>lBs(p,t)!==!0)}),{streaming:s,nonStreaming:u}}default:we(r)}}function cBs({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=Mn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=a_t({content:i.content,context:e});if(o==null)return;let s=Mn(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&Mn(a)&&(a=void 0);let c={...s,properties:{...s.properties,[r.streamConditionProperty]:{...a??{},type:"boolean","x-fern-boolean-literal":n}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{content:{[Lf.APPLICATION_JSON]:{schema:c}}},schemaReference:Mn(o.schema)?o.schema:void 0}}function uBs({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[Lf.APPLICATION_JSON]:{schema:t}}}}}function lBs(e,t){return e._visit({unknown:r=>{let n=Km.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var ABs=require("crypto");function ZFl(e){switch(e){case"unix-seconds":return Rg.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Rg.WebhookTimestampFormat.UnixMillis;case"iso8601":return Rg.WebhookTimestampFormat.Iso8601}}function fBs(e){if(e!=null)return{header:e.header,format:e.format!=null?ZFl(e.format):void 0,tolerance:e.tolerance}}function ekl(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Rg.WebhookPayloadComponent.Body;case"timestamp":return Rg.WebhookPayloadComponent.Timestamp;case"notification-url":return Rg.WebhookPayloadComponent.NotificationUrl;case"message-id":return Rg.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter,bodySort:tkl(e["body-sort"])}}function tkl(e){if(e!=null&&e==="alphabetical")return Rg.WebhookPayloadBodySort.Alphabetical}function rkl(e){if(e!=null)switch(e){case"sha256":return Rg.WebhookSignatureAlgorithm.Sha256;case"sha1":return Rg.WebhookSignatureAlgorithm.Sha1;case"sha384":return Rg.WebhookSignatureAlgorithm.Sha384;case"sha512":return Rg.WebhookSignatureAlgorithm.Sha512}}function dBs(e){if(e!=null)switch(e){case"base64":return Rg.WebhookSignatureEncoding.Base64;case"hex":return Rg.WebhookSignatureEncoding.Hex}}function nkl(e){if(e!=null)switch(e){case"rsa-sha256":return Rg.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Rg.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Rg.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Rg.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Rg.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Rg.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Rg.AsymmetricAlgorithm.Ed25519}}function hBs(e){if(e.type==="hmac")return Rg.WebhookSignatureVerification.hmac({header:e.header,algorithm:rkl(e.algorithm),encoding:dBs(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:ekl(e["payload-format"]),timestamp:fBs(e.timestamp)});if(e.type==="asymmetric"){let t=nkl(e["asymmetric-algorithm"]);return t==null?void 0:Rg.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:t,encoding:dBs(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],timestamp:fBs(e.timestamp)})}}function mBs(e){let t=qr(e,On.WEBHOOK_SIGNATURE);if(!(t==null||typeof t=="boolean"))return hBs(t)}function gBs(e,t){let r=qr(t,On.WEBHOOK_SIGNATURE);return r!=null?typeof r=="boolean"?mBs(e):hBs(r):mBs(e)}function yBs({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:c}=t,u=[...a,"Payload"],l=[...a,"Response"],p=Qfr({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:u,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??okl({path:o,method:s,sdkMethodName:c}),f=i.responses?Ufr({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:l,source:r}):void 0,m=gBs(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:kb([...u,v.name],e.options.preserveSchemaIds),availability:v.availability})),A=Dr.object({description:i.description,properties:g,nameOverride:void 0,generatedName:kb(u,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:qr(i,On.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:kb(u,e.options.preserveSchemaIds),payload:A,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let h=Mn(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([g,A])=>WH({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,b;return g.type==="multipart"?(A={name:g.name,properties:g.properties,description:g.description,source:g.source},b=Dr.unknown({nameOverride:void 0,generatedName:kb(u,e.options.preserveSchemaIds),title:void 0,description:g.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):b=g.schema,{summary:i.summary,audiences:qr(i,On.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:kb(u,e.options.preserveSchemaIds),payload:b,signatureVerification:m,multipartFormData:A,response:f?.value,description:i.description,examples:ikl(g.fullExamples),source:r}}).filter(g=>g!=null)}function ikl(e){if(e==null)return[];let t=[];for(let r of e){let n=IAe(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function okl({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=skl(e);if(n===e.toLowerCase())return e;let i=(0,ABs.createHash)("sha256").update(e).digest("hex").slice(0,8);return akl(`${n}_${t.toLowerCase()}_${i}`)}function skl(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function akl(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function ivi({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=qr(r,On.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=ckl(r,e),s=xTs(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:ukl({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:yBs({context:e,operationContext:a,source:e.source})};let c=wTs(r);if(c==null&&lkl({operation:r,context:e})&&(c={type:"stream",format:"sse",terminator:void 0}),c!=null){let p=pBs({context:e,operationContext:a,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let u=vTs(r);if(u!=null){let p=aBs({context:e,operationContext:a,asyncExtension:u,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:_ce({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function ckl(e,t){let r=qr(e,On.SDK_METHOD_NAME),n=qr(e,On.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function ukl({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(Jn(`${r}_${n.split("/").join("_")}`));return o}function lkl({operation:e,context:t}){if(e.responses==null)return!1;for(let[r,n]of Object.entries(e.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=Mn(n)?t.resolveResponseReference(n):n;if(o.content!=null&&STs(o.content))return!0}return!1}function bBs(e,t,r,n){let i=[],o=vBs(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=pkl({operation:a.operation}),u=ivi({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:c});u&&i.push(u)}return i}function EBs(e,t,r,n){let i=[],o=vBs(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=ivi({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});c&&i.push(c)}return i}function vBs(e){let t=[];return e.get!=null&&t.push({method:s_.Get,operation:e.get}),e.post!=null&&t.push({method:s_.Post,operation:e.post}),e.put!=null&&t.push({method:s_.Put,operation:e.put}),e.delete!=null&&t.push({method:s_.Delete,operation:e.delete}),e.patch!=null&&t.push({method:s_.Patch,operation:e.patch}),e.head!=null&&t.push({method:s_.Head,operation:e.head}),t}function pkl({operation:e}){return qr(e,[On.WEBHOOK])??!1}function IBs(e){let t=qr(e,On.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=qr(e,On.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function wBs(e){return qr(e,On.FERN_BASIC_AUTH)}function xBs(e,t,r,n){if(Mn(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return CBs(i,t,r)}return CBs(e,t,r)}function CBs(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=qr(e,j1.BEARER_FORMAT),i=qr(e,On.FERN_HEADER_AUTH);return i_.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??qr(e,On.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=qr(e,On.FERN_BEARER_TOKEN);return i_.bearer({tokenVariableName:n?.name??qr(e,On.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=wBs(e),i=IBs(e);return i_.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 i_.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return i_.oauth({scopesEnum:fkl(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 fkl(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=EAe({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=cd(n);if(i.type==="enum")return i}}function _Bs(e){return qr(e,On.BASE_PATH)}var dkl=yt.record(yt.string(),yt.object({summary:yt.string().optional(),description:yt.string().optional()}));function SBs({document:e,context:t}){return t_t(e,On.GROUPS,dkl,t.logger)}function OBs({context:e,document:t}){return qr(t,On.FERN_VERSION)??void 0}function TBs(e){let t=qr(e,On.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({header:n.header,name:n.name,optional:n.optional,env:n.env,clientDefault:n["x-fern-default"],schema:n.type!=null?r_t({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 BBs(e){let t=qr(e,On.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?r_t({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 PBs(e,t){let r=qr(e,On.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:kb([n],t),title:i.title,schema:Il.string({default:C9e(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 mkl="webhooks";function DBs(e){return qr(e,mkl)??{}}var f_t=class extends B9e{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 lRe({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 RBs(e){return qr(e,On.RESOLUTIONS)}function FBs({openapi:e}){let t=RBs(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=hkl({openapi:e,schemaReference:o,schemaName:n.name}),e=kBs({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function hkl({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 kBs({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,u)=>u.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let u=r.replace(i,c);return kBs({openapi:e,replaceReference:t,schemaReference:u,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),s=e;for(let c of o.slice(0,-1)){let u=s[c];if(u==null)return e;s=u}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}function jBs({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=FBs({openapi:e}),Ekl({openApi:e,taskContext:t}),Efr();let o=new f_t({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([G,V])=>{let z=xBs(V,n,t,o);return z==null?null:[G,z]}).filter(G=>G!==null)),a=e.security?.filter(G=>G!=null),c=new Set(Object.entries(s).map(([G,V])=>V.type==="basic"||V.type==="bearer"||V.type==="oauth"?"Authorization":V.type==="header"?V.headerName:null).filter(G=>G!=null)),u=PBs(e,r.preserveSchemaIds),l=TBs(e),p=BBs(e),d=r.audiences??[],f=[],m=[],h=new f_t({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});h.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([G,V])=>{if(V==null)return;let z=bBs(G,V,e,h);for(let K of z){let ie=NBs({operation:K});if(!(d.length>0&&!d.some(q=>ie.includes(q))))switch(K.type){case"async":f.push(...K.sync),f.push(...K.async);break;case"http":f.push(...K.value);break;case"streaming":f.push(...K.streaming),K.nonStreaming&&f.push(...K.nonStreaming);break;case"webhook":m.push(...K.value);break;default:we(K)}}}),Object.entries(DBs(e)).forEach(([G,V])=>{if(V==null)return;t.logger.debug(`Converting path ${G}`);let z=EBs(G,V,e,h);for(let K of z){let ie=NBs({operation:K});d.length>0&&!d.some(q=>ie.includes(q))||m.push(...K.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([G,V])=>{let z=qr(V,On.SDK_NAMESPACE);if(!Mn(V)){let K=qr(V,On.IGNORE);if(K!=null&&K)return[];if(nBs.has(G))return[G,ic({...V,"x-fern-type-name":`${G}Body`},!1,!1,h,[G],n,z??i)]}return[G,ic(V,!1,!1,h,[G],n,z??i)]}).filter(G=>G.length>0)),A=gkl(g,h,n),b=ykl(A,h),v=UH(),E={};for(let[G,V]of Object.entries(b)){let z=cd(V);if(h.isSchemaExcluded(G))continue;let K=v.getUniqueSchemaId(G,h.logger,r.resolveSchemaCollisions);E[K]=z}let I=new wAe(b,h.nonRequestReferencedSchemas,h),w=m.map(G=>{let z=G.examples;if(!r.disableExamples&&z.length===0){let K=I.buildExample({schema:G.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});K!=null&&(z=[{name:void 0,description:void 0,payload:K}])}return{...G,payload:cd(G.payload),examples:z}}),x=new wfr(b,h,l),C=f.map(G=>{let V=G.examples,z=V;if(!r.disableExamples&&(V.length===0||V.every(s_t))){let q=x.buildEndpointExample(G);q.length>0&&(z=[...q,...V.filter(H=>!s_t(H))])}let K=G.request,ie=G.response;return{...G,request:K?.type==="json"||K?.type==="formUrlEncoded"?{...K,schema:cd(K.schema)}:K,response:ie?.type==="json"?{...ie,schema:cd(ie.schema)}:ie,queryParameters:G.queryParameters.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,explode:q.explode,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),pathParameters:G.pathParameters.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,variableReference:q.variableReference,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),headers:G.headers.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,env:q.env,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),examples:z,errors:Jl(G.errors,q=>{let H=q.fullExamples?.map(ye=>{let Ee=IAe(ye.value);if(Ee!=null)return{name:ye.name,description:ye.description,example:Ee}}).filter(Pa);if(H?.length===0){let ye=I.buildExample({schema:q.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ye!=null&&H.push({name:void 0,description:void 0,example:ye})}return{generatedName:q.generatedName,nameOverride:q.nameOverride,schema:cd(q.schema),description:q.description,source:q.source,examples:H}}),retries:G.retries}});x.finalize();let _=SBs({document:e,context:h});return{apiVersion:OBs({context:h,document:e}),basePath:_Bs(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(_??{}).map(([G,V])=>[G,{summary:V.summary??void 0,description:V.description??void 0}])),servers:(e.servers??[]).map(G=>jfr(G,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(G=>[G.name,{id:G.name,description:G.description}])),orderedTagIds:e.tags?.map(G=>G.name)},endpoints:C,webhooks:w,channels:{},groupedSchemas:_9e(i,E),securitySchemes:s,security:a,hasEndpointsMarkedInternal:C.some(G=>G.internal),nonRequestReferencedSchemas:h.getReferencedSchemas(),variables:u,globalHeaders:l,idempotencyHeaders:p}}function gkl(e,t,r){if(t.options.removeDiscriminantsFromSchemas===Dn.RemoveDiscriminantsFromSchemas.Never)return e;let n=Akl(e,t),i={};for(let[o,s]of Object.entries(e)){if(s.type!=="object"){i[o]=s;continue}let a={$ref:`#/components/schemas/${o}`},c=t.getReferencesFromDiscriminatedUnion(a);if(c==null){i[o]=s;continue}if(t.getReferencedSchemas().has(o)){i[o]=s;continue}let l={...s,type:"object",properties:s.properties.filter(d=>!c.discriminants.has(d.key)),allOfPropertyConflicts:s.allOfPropertyConflicts.filter(d=>!c.discriminants.has(d.propertyKey)),source:r};i[o]=l;let p=ovi({schema:s,schemas:e});for(let d of[...new Set(p)]){if(n.has(d))continue;let f=i[d]??e[d];f==null||f.type!=="object"||(i[d]={...f,type:"object",properties:f.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:f.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return i}function Akl(e,t){let r=new Set;for(let[n,i]of Object.entries(e)){if(i.type!=="object")continue;let o={$ref:`#/components/schemas/${n}`};if(t.getReferencesFromDiscriminatedUnion(o)==null)for(let s of ovi({schema:i,schemas:e}))r.add(s)}return r}function ykl(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 u of i.properties)if(s.discriminants.has(u.key)){let l=s.discriminants.get(u.key);l!=null&&a.push({...u,schema:Dr.literal({nameOverride:void 0,generatedName:kb([i.generatedName,l],t.options.preserveSchemaIds),title:void 0,value:LA.string(l),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(u);let c={...i,type:"object",properties:a};r[n]=c}return r}function ovi({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(...ovi({schema:i,schemas:t}))}return r}function zfr(e){return[...new Set(e)]}var Vfr=new RegExp("[^\\x00-\\x7F]"),bkl=/(?:^|\n)\s*---\s*(?:\n|$)/;function Ekl({openApi:e,taskContext:t}){for(let r of e.tags??[])if(Vfr.test(r.name)){let n=[...r.name].filter(i=>Vfr.test(i));t.logger.error(`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR). Remove non-ASCII characters from the tag name.`)}for(let[r,n]of Object.entries(e.paths??{}))if(n!=null)for(let i of["get","post","put","delete","patch","options","head","trace"]){let o=n[i];if(o?.description!=null&&bkl.test(o.description)&&t.logger.error(`Description at paths.${r}.${i} contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. Remove the "---" delimiters from the description.`),o?.tags!=null&&(e.tags==null||e.tags.length===0)){for(let s of o.tags)if(Vfr.test(s)){let a=[...s].filter(c=>Vfr.test(c));t.logger.error(`Tag name "${s}" at paths.${r}.${i} contains non-ASCII characters: ${a.join(", ")}. Remove non-ASCII characters from the tag name.`)}}}}function NBs({operation:e}){let t=[];switch(e.type){case"async":t=zfr(e.async.flatMap(r=>r.audiences));break;case"http":t=zfr(e.value.flatMap(r=>r.audiences));break;case"streaming":t=zfr(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=zfr(e.value.flatMap(r=>r.audiences));break;default:we(e)}return t}function SRe({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:KT.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=jBs({taskContext:e,openApi:o.value,options:Y4({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=xkl(n,a,Y4({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let a=ETs({document:o.value,taskContext:e,options:Y4({options:o.settings,overrides:r}),source:s,asyncApiOptions:vkl({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(c=>({...c,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),a.channels!=null&&(n.channels={...n.channels,...a.channels}),a.groupedSchemas!=null&&(n.groupedSchemas=qfr(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath),i++;break}default:we(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?`
1498
+ `);try{S9e.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=ZDl(t.request),n=eRl(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:$Ei(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:$Ei(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,H4.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,H4.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,H4.withoutStreaming(m)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,H4.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&&!AG(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&&!AG(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 c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(f!=null&&!AG(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),d&&f==null)return[];f!=null&&c.push({name:p.name,value:f})}for(let p of this.globalHeaders){let d=p.schema!=null?gG(p.schema):Dr.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Di.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&&!AG(f)&&(this.logger.debug(`Expected a primitive example but got ${f.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),f=void 0),f!=null&&c.push({name:p.header,value:f})}let u=[];t.request!=null&&t.response!=null?u=XDl(i,o):t.request!=null?u=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(u=o.map(([p,d])=>({id:p,request:void 0,response:d})));let l=t.examples.filter(p=>s_t(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=>Pa(p));return u.length===0?[$4.full({name:void 0,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:void 0,response:void 0,codeSamples:l})]:u.map(({id:p,request:d,response:f})=>$4.full({name:p,description:void 0,pathParameters:s,queryParameters:a,headers:c,request:d,response:f,codeSamples:l}))}convertCodeSamples(t){return t.map(r=>"language"in r?DH.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):DH.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?a_.Csharp:r.sdk,code:r.code})).filter(Pa)}isSchemaRequired(t){return Ifr(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function XDl(e,t){let r=[];if(e.length<=1){let[i,o]=e[0]??[];if(t.length===0)return r.push({id:i,request:o,response:void 0}),r;for(let[s,a]of t)r.push({id:s??i,request:o,response:a});return r}if(t.length<=1){let[i,o]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:o}),r;for(let[s,a]of e)r.push({id:s??i,request:a,response:o});return r}let n=new Set;for(let[i,o]of e){let s=t.find(([c])=>c==null)?.[1]??t[0]?.[1];if(i==null){if(s==null)continue;r.push({id:void 0,request:o,response:s});continue}let a=!1;for(let c=0;c<t.length;c++){let[u,l]=t[c];u==null||n.has(c)||i===u&&(r.push({id:i,request:o,response:l}),u!=null&&n.add(c),a=!0)}!a&&s!=null&&r.push({id:i,request:o,response:s})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[o,s]=t[i],a=e.find(([c])=>c==null)?.[1]??e[0]?.[1];a!=null&&r.push({id:o,request:a,response:s})}return r}function ZDl(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:tRl(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function eRl(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 AG(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return AG(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return AG(e.value.value);default:return!1}case"null":return!0;default:we(e)}}function tRl(e){return Dr.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:gG(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(Pa),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 O9e=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new wAe(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let s=[];for(let a of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),f=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:a.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});f!=null&&!AG(f)&&(f=void 0),!(d&&f==null)&&f!=null&&c.push({name:p.name,value:f})}let u=[];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&&!AG(f)&&(f=void 0),!(d&&f==null)&&f!=null&&u.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=Mn(f.payload)?t.resolveSchemaReference(f.payload):f.payload,h=this.exampleTypeFactory.buildExample({schema:ic(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:c,headers:u,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),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!AG(c)&&(c=void 0),a&&c==null)return;c!=null&&i.push({name:s.name,value:c})}let o=[];for(let s of t.headers){let a=this.isSchemaRequired(s.schema),c=this.exampleTypeFactory.buildExample({schema:s.schema,exampleId:void 0,example:void 0,options:{name:s.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!AG(c)&&(c=void 0),a&&c==null)return;c!=null&&o.push({name:s.name,value:c})}for(let s of r){let a=this.exampleTypeFactory.buildExample({schema:s.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});a!=null&&n.messages.push({messageType:s.type,payload:a,description:void 0})}return n}isSchemaRequired(t){return Ifr(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 O0={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 Cfr(e){return qr(e,O0.FERN_EXAMPLES)??[]}function xfr(e,t){return t.includes("://")?t:`${e}://${t}`}function _fr(e){return e.startsWith("/")?e:"/"+e}function hTs({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},s={};for(let[u,l]of Object.entries(i.components?.schemas??{})){let p=ic(l,!1,!1,e,[u],r,e.namespace);o[u]=p}let a=new O9e(o,e),c={};for(let[u,l]of Object.entries(i.servers??{})){let p=qr(l,O0.FERN_SERVER_NAME);c[u]={name:p??u,url:xfr(l.protocol,l.url)}}for(let[u,l]of Object.entries(i.channels??{})){let p=qr(l,O0.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${u} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(l.parameters!=null)for(let[A,b]of Object.entries(l.parameters??{})){let v=qr(b,O0.FERN_PARAMETER_NAME);d.push({name:A,description:b.description,parameterNameOverride:v,schema:b.schema!=null?ic(b.schema,!1,!1,e,t,r,e.namespace):Dr.primitive({schema:Di.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:sw(b),source:r,explode:void 0,clientDefault: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[b,v]of Object.entries(l.bindings.ws.headers.properties??{})){if(Mn(v)){let x=e.resolveSchemaReference(v),C=A.includes(b),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];f.push({name:b,schema:bM(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,env:void 0,availability:sw(x),source:r,clientDefault:void 0});continue}let E=A.includes(b),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];f.push({name:b,schema:ic(v,I,w,e,[...t,b],r,e.namespace),description:v.description,parameterNameOverride:void 0,env:void 0,availability:sw(v),source:r,clientDefault:void 0})}}if(l.bindings.ws.query!=null){let A=l.bindings.ws.query.required??[];for(let[b,v]of Object.entries(l.bindings.ws.query.properties??{})){if(Mn(v)){let x=e.resolveSchemaReference(v),C=A.includes(b),[_,R]=e.options.coerceOptionalSchemasToNullable?[!1,!C]:[!C,!1];m.push({name:b,schema:bM(v,_,R,e,t,void 0,r,e.namespace),description:x.description,parameterNameOverride:void 0,availability:sw(x),source:r,explode:void 0,clientDefault:void 0});continue}let E=A.includes(b),[I,w]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];m.push({name:b,schema:ic(v,I,w,e,[...t,b],r,e.namespace),description:v.description,parameterNameOverride:void 0,availability:sw(v),source:r,explode:void 0,clientDefault:void 0})}}}let h;l.publish!=null&&("oneOf"in l.publish.message?h=dTs({generatedName:l.publish.operationId??"PublishEvent",event:l.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):h=mTs({action:"Publish",channelPath:u,message:l.publish.message,context:e,source:r}));let g;if(l.subscribe!=null&&("oneOf"in l.subscribe.message?g=dTs({generatedName:l.subscribe.operationId??"SubscribeEvent",event:l.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=mTs({action:"Subscribe",channelPath:u,message:l.subscribe.message,context:e,source:r})),f.length>0||m.length>0||h!=null||g!=null){let A=Cfr(l),b=[];if(A.length>0)b=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&&b.push(x)}let v=qr(l,O0.FERN_CHANNEL_ADDRESS),E=v??_fr(u),I=[];h!=null&&I.push({origin:"client",name:"publish",body:cd(h),methodName:l.publish!=null?qr(l.publish,O0.FERN_SDK_METHOD_NAME):void 0}),g!=null&&I.push({origin:"server",name:"subscribe",body:cd(g),methodName:l.subscribe!=null?qr(l.subscribe,O0.FERN_SDK_METHOD_NAME):void 0}),s[u]={audiences:qr(l,On.AUDIENCES)??[],handshake:{headers:f.map(w=>({...w,schema:cd(w.schema),env:w.env})),queryParameters:m.map(w=>({...w,schema:cd(w.schema)})),pathParameters:d.map(w=>({...w,schema:cd(w.schema)}))},groupName:e.resolveGroupName([qr(l,O0.FERN_SDK_GROUP_NAME)??u]),messages:I,servers:(l.servers?.map(w=>c[w])??Object.values(c)).filter(w=>w!=null&&w.name!=null).map(w=>({...w,name:w.name})),summary:qr(l,O0.FERN_DISPLAY_NAME),connectMethodName:qr(l,O0.FERN_SDK_METHOD_NAME),path:E,description:l.description,examples:b,source:r}}}return{groupedSchemas:_9e(e.namespace,o),channels:s??void 0,servers:Object.values(c).map(u=>({...u,name:u.name})),basePath:qr(i,O0.BASE_PATH)}}function dTs({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:s}){if("oneOf"in t.message&&t.message.oneOf!=null){let a=[],c=[];for(let u of t.message.oneOf){let l,p={type:"notFound"};if(Mn(u)){let d=r.resolveMessageReference(u);!Mn(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=u;c.push(p),a.push(l)}return vAe({description:t.description??t.message.description,availability:sw(t.message),subtypes:a,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:s.naming==="v2"?c:[]})}}function mTs({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return Mn(r.payload)&&(o=n.resolveSchemaReference(r.payload)),ic(o,!1,!1,n,[t,e],i,n.namespace)}}var Sfr=class extends x9e{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 c=t.$ref.split("/"),u=c[2],l=c[4],p=u?.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}};Tt();Ni();var gTs="#/channels/",ATs="#/servers/",HEi="$message.";function bTs({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){Efr();let o={},s={},a={},c=[],u={};e.logger.debug("Parsing V3 AsyncAPI...");let l=UH();for(let[x,C]of Object.entries(i.components?.schemas??{})){let _=l.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);o[_]=ic(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 G=e.resolveMessageReference(R);a[_].push({channelId:x,payload:G.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]=ic(_.payload,!1,!1,e,[x],r,e.namespace)}else{c.push(x);for(let{channelId:_,payload:R}of C){let G=`${_}_${x}`;s[_]||(s[_]={}),s[_][G]=ic(R,!1,!1,e,[G],r,e.namespace)}}let p={},d=UH();for(let[x,C]of Object.entries(s))for(let[_,R]of Object.entries(C)){let G=d.getUniqueSchemaId(_,e.logger,e.options.resolveSchemaCollisions);p[G]=R}let f=new O9e({...o,...p},e),m={};for(let[x,C]of Object.entries(i.servers??{})){let _=qr(C,O0.FERN_SERVER_NAME);m[x]={name:_??x,url:xfr(C.protocol,C.host)}}let h={},g=Object.keys(i.channels??{});for(let[x,C]of Object.entries(i.operations??{})){if(qr(C,O0.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 _=nRl(C);h[_]||(h[_]={subscribe:[],publish:[],__parsedMessages:[]});let R=qr(C,O0.FERN_SDK_METHOD_NAME);if(!C.messages||!Array.isArray(C.messages))continue;let G=C.messages.filter(z=>z!=null&&z.$ref!=null).map(z=>({ref:z,methodName:R})),V=h[_];if(V==null)throw new Error(`Internal error: channelEvents["${_}"] is unexpectedly undefined for operation ${x}`);if(C.action==="receive")V.subscribe.push(...G);else if(C.action==="send")V.publish.push(...G);else throw new Error(`Operation ${x} has an invalid action: ${C.action}`)}for(let[x,C]of Object.entries(h)){let _=[];_.push(...yTs({messages:C.subscribe,channelPath:x,origin:"server",messageSchemas:s[x]??{},duplicatedMessageIds:c,context:e})),_.push(...yTs({messages:C.publish,channelPath:x,origin:"client",messageSchemas:s[x]??{},duplicatedMessageIds:c,context:e})),h[x]!=null&&(h[x].__parsedMessages=_)}for(let[x,C]of Object.entries(i.channels??{})){if(qr(C,O0.IGNORE))continue;let _=[],R=[],G=[];if(C.parameters!=null)for(let[V,z]of Object.entries(C.parameters)){let K=e.isReferenceObject(z)?e.resolveParameterReference(z):z,{type:ie,parameterKey:q}=K.location!=null?iRl(K.location):{type:C.address?.includes(`={${V}}`)?"query":"path",parameterKey:V},H=qr(K,O0.FERN_PARAMETER_OPTIONAL),ye=Du(Jn(x))+Du(Jn(V)),Ee=K.schema!=null?Mn(K.schema)?bM(K.schema,!1,!1,e,[q],void 0,r,e.namespace):ic(K.schema,!1,!1,e,[q],r,e.namespace):ic({...K,type:"string",title:ye,example:K.examples?.[0],default:K.default,enum:K.enum,required:void 0},!1,!1,e,[q],r,e.namespace),Z=H?Dr.optional({value:Ee,description:void 0,availability:void 0,generatedName:"",title:ye,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}):Ee,te={name:q,description:K.description,parameterNameOverride:void 0,schema:Z,variableReference:void 0,availability:sw(z),source:r,explode:void 0,clientDefault:void 0};ie==="header"?_.push({...te,env:void 0}):ie==="path"?R.push(te):(ie==="payload"||ie==="query")&&G.push(te)}if(C.bindings?.ws?.query!=null){let V=new Set(G.map(K=>K.name)),z=new Set(C.bindings.ws.query.required??[]);for(let[K,ie]of Object.entries(C.bindings.ws.query.properties??{})){if(V.has(K))continue;if(Mn(ie)){let Ee=e.resolveSchemaReference(ie),Z=z.has(K),[te,be]=e.options.coerceOptionalSchemasToNullable?[!1,!Z]:[!Z,!1];G.push({name:K,schema:bM(ie,te,be,e,[x,K],void 0,r,e.namespace),description:Ee.description,parameterNameOverride:void 0,availability:sw(Ee),source:r,explode:void 0,clientDefault:void 0});continue}let q=z.has(K),[H,ye]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];G.push({name:K,schema:ic(ie,H,ye,e,[x,K],r,e.namespace),description:ie.description,parameterNameOverride:void 0,availability:sw(ie),source:r,explode:void 0,clientDefault:void 0})}}if(C.bindings?.ws?.headers!=null){let V=new Set(_.map(K=>K.name)),z=new Set(C.bindings.ws.headers.required??[]);for(let[K,ie]of Object.entries(C.bindings.ws.headers.properties??{})){if(V.has(K))continue;if(Mn(ie)){let Ee=e.resolveSchemaReference(ie),Z=z.has(K),[te,be]=e.options.coerceOptionalSchemasToNullable?[!1,!Z]:[!Z,!1];_.push({name:K,schema:bM(ie,te,be,e,[x,K],void 0,r,e.namespace),description:Ee.description,parameterNameOverride:void 0,env:void 0,availability:sw(Ee),source:r,clientDefault:void 0});continue}let q=z.has(K),[H,ye]=e.options.coerceOptionalSchemasToNullable?[!1,!q]:[!q,!1];_.push({name:K,schema:ic(ie,H,ye,e,[x,K],r,e.namespace),description:ie.description,parameterNameOverride:void 0,env:void 0,availability:sw(ie),source:r,clientDefault:void 0})}}if(_.length>0||G.length>0||h[x]!=null&&(h[x].publish!=null||h[x].subscribe!=null)){let V=Cfr(C),z=h[x]?.__parsedMessages??[],K=[];try{if(V.length>0)K=f.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:V,handshake:{headers:_,queryParameters:G},source:r,namespace:e.namespace});else{let Ee=[],{examplePublishMessage:Z,exampleSubscribeMessage:te}=sRl({messages:z,messageSchemas:s[x]??{}});Z!=null&&Ee.push(Z),te!=null&&Ee.push(te);let be=f.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:G},messages:Ee});be!=null&&K.push(be)}}catch(Ee){e.logger.warn(`Failed to build examples for channel ${x}: ${ji(Ee)}`)}let ie=qr(C,O0.FERN_SDK_GROUP_NAME),q=qr(C,O0.FERN_SDK_METHOD_NAME),H=(C.servers?.map(Ee=>oRl(m,Ee))??Object.values(m)).map(Ee=>({...Ee,name:Ee.name})),ye=C.address?.split("?")[0]??_fr(x);u[x]={audiences:qr(C,On.AUDIENCES)??[],handshake:{headers:_.map(Ee=>({...Ee,schema:cd(Ee.schema),env:Ee.env})),queryParameters:G.map(Ee=>({...Ee,schema:cd(Ee.schema)})),pathParameters:R.map(Ee=>({...Ee,parameterNameOverride:void 0,schema:cd(Ee.schema)}))},groupName:e.resolveGroupName(typeof ie=="string"?[ie]:ie??[x]),messages:z,summary:qr(C,O0.FERN_DISPLAY_NAME),connectMethodName:q,servers:H,path:ye,description:C.description,examples:K,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},b={},v=UH();for(let[x,C]of Object.entries(A)){let _=v.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);b[_]=cd(C)}let E=_9e(e.namespace,o),I=Object.values(m).map(x=>({...x,name:x.name})),w=qr(i,O0.BASE_PATH);return{groupedSchemas:E,channels:u,servers:I,basePath:w}}function rRl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function nRl(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(gTs))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return rRl(e.channel.$ref.substring(gTs.length))}function iRl(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(HEi))throw new Error(`Invalid location format: ${e}; expected ${HEi} prefix`);let n=t.substring(HEi.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 oRl(e,t){if(!t.$ref.startsWith(ATs))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(ATs.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function yTs({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let s=[];return e.forEach((a,c)=>{try{let l=o.resolveMessageReference(a.ref,!0).name;i.includes(l)&&(l=`${t}_${l}`);let p=n[l];p!=null&&s.push({origin:r,name:l??`${r}Message${c+1}`,body:cd(p),methodName:a.methodName})}catch(u){o.logger.warn(`Skipping message reference ${a.ref.$ref} in channel ${t}: ${ji(u)}`)}}),s}function sRl({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 ETs({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let s=[];if(o!=null&&s.push(o),parseFloat(e.asyncapi)<3){let a=e;a.tags?.[0]!=null?s.push(a.tags[0].name):i.naming!=="v2"&&s.push("websocket");let c=new vfr({document:a,taskContext:t,options:r,namespace:o});return hTs({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}else{let a=e,c=new Sfr({document:a,taskContext:t,options:r,namespace:o});return bTs({context:c,breadcrumbs:s,source:n,asyncApiOptions:i,document:a})}}Tt();Ni();Ni();function vTs(e){return qr(e,On.ASYNC_CONFIG)}var ITs="$request.";function wTs(e){let t=qr(e,On.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:aRl(t["stream-condition"]),streamRequestName:t["stream-request-name"],responseStream:t["response-stream"],response:t.response}}function aRl(e){return e.startsWith(ITs)?e.slice(ITs.length):e}function CTs(e){let t=e;if(t.cursor!=null)return BC.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return BC.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return BC.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return BC.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 BC.custom({results:i.results})}throw new Error("Invalid pagination extension")}function xTs(e,t){let r=qr(t,On.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=qr(e,On.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:CTs(n)}return CTs(r)}}function _Ts(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:T9e(n,t)}}}function STs(e){let t=Object.keys(e);return t.length===1&&t[0]!=null&&t[0].includes("text/event-stream")}function cRl(e){return e.includes("json")||e==="*/*"}function KEi({content:e,context:t}){for(let[r,n]of Object.entries(e))if(Ofr({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function Ofr({mediaType:e,mediaTypeObject:t,context:r}){if(!cRl(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:T9e(t,r)}}function a_t({content:e,context:t}){let r=KEi({content:e,context:t});if(!r)return;let[n,i]=r;return Ofr({mediaType:n,mediaTypeObject:i,context:t})}function OTs(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:T9e(n,t)}}}function T9e(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=qr(e,j1.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let s=Mn(o)?t.resolveExampleReference(o):o;return{name:s.summary??i,value:s.value,description:s.description}})),r}Tt();Tt();function TTs(e){let t=uRl(e),r={};return JEi({obj:t,occurrences:r,breadcrumbs:[]}),r}function JEi({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)JEi({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)JEi({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function uRl(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?c_t(r.get):void 0,put:r?.put!=null?c_t(r.put):void 0,post:r?.post!=null?c_t(r.post):void 0,patch:r?.patch!=null?c_t(r.patch):void 0,delete:r?.delete!=null?c_t(r.delete):void 0}]))}}function c_t(e){return{...e,requestBody:e.requestBody!=null?Mn(e.requestBody)?e.requestBody:lRl(e.requestBody):void 0}}function lRl(e){let t,r;for(let n in e.content){let i=Lf.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[Lf.MULTIPART_FORM_DATA]:r}}:e}var Tfr=class{endpoints;parser=new Wae;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 BTs="#/components/parameters/",PTs="#/components/responses/",DTs="#/components/examples/",RTs="#/components/requestBodies/",FTs="#/components/securitySchemes/",B9e=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=TTs(t),this.options=i,this.source=o,this.filter=new Tfr({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=s,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Mn(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(BTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(BTs.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(RTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(RTs.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(PTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(PTs.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(DTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(DTs.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(FTs))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(FTs.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return Mn(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;for(let[r,n]of Object.entries(this.document.components.schemas))!n||Mn(n)||t.set(r,qr(n,On.SDK_NAMESPACE)||this.namespace);return t}};var lRe=class extends B9e{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){}};Tt();var kfr=require("fs"),Nfr=require("path");var yt={};X(yt,{BRAND:()=>NRl,DIRTY:()=>pRe,EMPTY_PATH:()=>mRl,INVALID:()=>Rc,NEVER:()=>EFl,OK:()=>XT,ParseStatus:()=>Q1,Schema:()=>xp,ZodAny:()=>_Ae,ZodArray:()=>xce,ZodBigInt:()=>dRe,ZodBoolean:()=>mRe,ZodBranded:()=>l_t,ZodCatch:()=>xRe,ZodDate:()=>hRe,ZodDefault:()=>CRe,ZodDiscriminatedUnion:()=>Dfr,ZodEffects:()=>tz,ZodEnum:()=>IRe,ZodError:()=>Zk,ZodFirstPartyTypeKind:()=>au,ZodFunction:()=>Ffr,ZodIntersection:()=>bRe,ZodIssueCode:()=>gn,ZodLazy:()=>ERe,ZodLiteral:()=>vRe,ZodMap:()=>N9e,ZodNaN:()=>Q9e,ZodNativeEnum:()=>wRe,ZodNever:()=>yG,ZodNull:()=>ARe,ZodNullable:()=>GH,ZodNumber:()=>fRe,ZodObject:()=>eN,ZodOptional:()=>Z4,ZodParsedType:()=>ns,ZodPipeline:()=>p_t,ZodPromise:()=>SAe,ZodReadonly:()=>_Re,ZodRecord:()=>Rfr,ZodSchema:()=>xp,ZodSet:()=>j9e,ZodString:()=>xAe,ZodSymbol:()=>F9e,ZodTransformer:()=>tz,ZodTuple:()=>qH,ZodType:()=>xp,ZodUndefined:()=>gRe,ZodUnion:()=>yRe,ZodUnknown:()=>Cce,ZodVoid:()=>k9e,addIssueToContext:()=>So,any:()=>GRl,array:()=>KRl,bigint:()=>LRl,boolean:()=>GTs,coerce:()=>bFl,custom:()=>zTs,date:()=>URl,datetimeRegex:()=>LTs,defaultErrorMap:()=>Ice,discriminatedUnion:()=>ZRl,effect:()=>pFl,enum:()=>cFl,function:()=>oFl,getErrorMap:()=>P9e,getParsedType:()=>VH,instanceof:()=>QRl,intersection:()=>eFl,isAborted:()=>Bfr,isAsync:()=>D9e,isDirty:()=>Pfr,isValid:()=>CAe,late:()=>jRl,lazy:()=>sFl,literal:()=>aFl,makeIssue:()=>u_t,map:()=>nFl,nan:()=>MRl,nativeEnum:()=>uFl,never:()=>$Rl,null:()=>qRl,nullable:()=>dFl,number:()=>qTs,object:()=>JRl,objectUtil:()=>YEi,oboolean:()=>yFl,onumber:()=>AFl,optional:()=>fFl,ostring:()=>gFl,pipeline:()=>hFl,preprocess:()=>mFl,promise:()=>lFl,quotelessJson:()=>pRl,record:()=>rFl,set:()=>iFl,setErrorMap:()=>dRl,strictObject:()=>YRl,string:()=>VTs,symbol:()=>zRl,transformer:()=>pFl,tuple:()=>tFl,undefined:()=>VRl,union:()=>XRl,unknown:()=>WRl,util:()=>lf,void:()=>HRl});var lf;(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})(lf||(lf={}));var YEi;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(YEi||(YEi={}));var ns=lf.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),VH=e=>{switch(typeof e){case"undefined":return ns.undefined;case"string":return ns.string;case"number":return Number.isNaN(e)?ns.nan:ns.number;case"boolean":return ns.boolean;case"function":return ns.function;case"bigint":return ns.bigint;case"symbol":return ns.symbol;case"object":return Array.isArray(e)?ns.array:e===null?ns.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ns.promise:typeof Map<"u"&&e instanceof Map?ns.map:typeof Set<"u"&&e instanceof Set?ns.set:typeof Date<"u"&&e instanceof Date?ns.date:ns.object;default:return ns.unknown}};var gn=lf.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"]),pRl=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Zk=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,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};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,lf.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()}};Zk.create=e=>new Zk(e);var fRl=(e,t)=>{let r;switch(e.code){case gn.invalid_type:e.received===ns.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case gn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,lf.jsonStringifyReplacer)}`;break;case gn.unrecognized_keys:r=`Unrecognized key(s) in object: ${lf.joinValues(e.keys,", ")}`;break;case gn.invalid_union:r="Invalid input";break;case gn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${lf.joinValues(e.options)}`;break;case gn.invalid_enum_value:r=`Invalid enum value. Expected ${lf.joinValues(e.options)}, received '${e.received}'`;break;case gn.invalid_arguments:r="Invalid function arguments";break;case gn.invalid_return_type:r="Invalid function return type";break;case gn.invalid_date:r="Invalid date";break;case gn.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}"`:lf.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case gn.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 gn.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 gn.custom:r="Invalid input";break;case gn.invalid_intersection_types:r="Intersection results could not be merged";break;case gn.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case gn.not_finite:r="Number must be finite";break;default:r=t.defaultError,lf.assertNever(e)}return{message:r}},Ice=fRl;var kTs=Ice;function dRl(e){kTs=e}function P9e(){return kTs}var u_t=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="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},mRl=[];function So(e,t){let r=P9e(),n=u_t({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Ice?void 0:Ice].filter(i=>!!i)});e.common.issues.push(n)}var Q1=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 Rc;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 Rc;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}}},Rc=Object.freeze({status:"aborted"}),pRe=e=>({status:"dirty",value:e}),XT=e=>({status:"valid",value:e}),Bfr=e=>e.status==="aborted",Pfr=e=>e.status==="dirty",CAe=e=>e.status==="valid",D9e=e=>typeof Promise<"u"&&e instanceof Promise;var wa;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(wa||(wa={}));var ez=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}},NTs=(e,t)=>{if(CAe(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 Zk(e.common.issues);return this._error=r,this._error}}};function Xl(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:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var xp=class{get description(){return this._def.description}_getType(t){return VH(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:VH(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Q1,ctx:{common:t.parent.common,data:t.data,parsedType:VH(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(D9e(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:VH(t)},i=this._parseSync({data:t,path:n.path,parent:n});return NTs(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:VH(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return CAe(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=>CAe(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:VH(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(D9e(i)?i:Promise.resolve(i));return NTs(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:gn.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!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 tz({schema:this,typeName:au.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 Z4.create(this,this._def)}nullable(){return GH.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xce.create(this)}promise(){return SAe.create(this,this._def)}or(t){return yRe.create([this,t],this._def)}and(t){return bRe.create(this,t,this._def)}transform(t){return new tz({...Xl(this._def),schema:this,typeName:au.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new CRe({...Xl(this._def),innerType:this,defaultValue:r,typeName:au.ZodDefault})}brand(){return new l_t({typeName:au.ZodBranded,type:this,...Xl(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new xRe({...Xl(this._def),innerType:this,catchValue:r,typeName:au.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return p_t.create(this,t)}readonly(){return _Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},hRl=/^c[^\s-]{8,}$/i,gRl=/^[0-9a-z]+$/,ARl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yRl=/^[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,bRl=/^[a-z0-9_-]{21}$/i,ERl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vRl=/^[-+]?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)?)??$/,IRl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wRl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",XEi,CRl=/^(?:(?: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])$/,xRl=/^(?:(?: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])$/,_Rl=/^(([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]))$/,SRl=/^(([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])$/,ORl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TRl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,QTs="((\\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])))",BRl=new RegExp(`^${QTs}$`);function MTs(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 PRl(e){return new RegExp(`^${MTs(e)}$`)}function LTs(e){let t=`${QTs}T${MTs(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 DRl(e,t){return!!((t==="v4"||!t)&&CRl.test(e)||(t==="v6"||!t)&&_Rl.test(e))}function RRl(e,t){if(!ERl.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 FRl(e,t){return!!((t==="v4"||!t)&&xRl.test(e)||(t==="v6"||!t)&&SRl.test(e))}var xAe=class e extends xp{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ns.string){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.string,received:o.parsedType}),Rc}let n=new Q1,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),So(i,{code:gn.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),So(i,{code:gn.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?So(i,{code:gn.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&So(i,{code:gn.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")IRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"email",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")XEi||(XEi=new RegExp(wRl,"u")),XEi.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"emoji",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")yRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"uuid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")bRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"nanoid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")hRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cuid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")gRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cuid2",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ARl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"ulid",code:gn.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),So(i,{validation:"url",code:gn.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),So(i,{validation:"regex",code:gn.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),So(i,{code:gn.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),So(i,{code:gn.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?LTs(o).test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?BRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?PRl(o).test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{code:gn.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?vRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"duration",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?DRl(t.data,o.version)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"ip",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?RRl(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"jwt",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?FRl(t.data,o.version)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"cidr",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ORl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"base64",code:gn.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?TRl.test(t.data)||(i=this._getOrReturnCtx(t,i),So(i,{validation:"base64url",code:gn.invalid_string,message:o.message}),n.dirty()):lf.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:gn.invalid_string,...wa.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...wa.errToObj(t)})}url(t){return this._addCheck({kind:"url",...wa.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...wa.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...wa.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...wa.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...wa.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...wa.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...wa.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...wa.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...wa.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...wa.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...wa.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...wa.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,...wa.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,...wa.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...wa.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...wa.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...wa.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...wa.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...wa.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...wa.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...wa.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...wa.errToObj(r)})}nonempty(t){return this.min(1,wa.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}};xAe.create=e=>new xAe({checks:[],typeName:au.ZodString,coerce:e?.coerce??!1,...Xl(e)});function kRl(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 fRe=class e extends xp{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)!==ns.number){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.number,received:o.parsedType}),Rc}let n,i=new Q1;for(let o of this._def.checks)o.kind==="int"?lf.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),So(n,{code:gn.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),So(n,{code:gn.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),So(n,{code:gn.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?kRl(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),So(n,{code:gn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),So(n,{code:gn.not_finite,message:o.message}),i.dirty()):lf.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,wa.toString(r))}gt(t,r){return this.setLimit("min",t,!1,wa.toString(r))}lte(t,r){return this.setLimit("max",t,!0,wa.toString(r))}lt(t,r){return this.setLimit("max",t,!1,wa.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:wa.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:wa.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:wa.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:wa.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:wa.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:wa.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:wa.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:wa.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:wa.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:wa.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"&&lf.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)}};fRe.create=e=>new fRe({checks:[],typeName:au.ZodNumber,coerce:e?.coerce||!1,...Xl(e)});var dRe=class e extends xp{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)!==ns.bigint)return this._getInvalidInput(t);let n,i=new Q1;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),So(n,{code:gn.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),So(n,{code:gn.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),So(n,{code:gn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):lf.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return So(r,{code:gn.invalid_type,expected:ns.bigint,received:r.parsedType}),Rc}gte(t,r){return this.setLimit("min",t,!0,wa.toString(r))}gt(t,r){return this.setLimit("min",t,!1,wa.toString(r))}lte(t,r){return this.setLimit("max",t,!0,wa.toString(r))}lt(t,r){return this.setLimit("max",t,!1,wa.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:wa.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:wa.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:wa.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:wa.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:wa.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:wa.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}};dRe.create=e=>new dRe({checks:[],typeName:au.ZodBigInt,coerce:e?.coerce??!1,...Xl(e)});var mRe=class extends xp{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ns.boolean){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.boolean,received:n.parsedType}),Rc}return XT(t.data)}};mRe.create=e=>new mRe({typeName:au.ZodBoolean,coerce:e?.coerce||!1,...Xl(e)});var hRe=class e extends xp{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ns.date){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_type,expected:ns.date,received:o.parsedType}),Rc}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return So(o,{code:gn.invalid_date}),Rc}let n=new Q1,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),So(i,{code:gn.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),So(i,{code:gn.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):lf.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:wa.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:wa.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}};hRe.create=e=>new hRe({checks:[],coerce:e?.coerce||!1,typeName:au.ZodDate,...Xl(e)});var F9e=class extends xp{_parse(t){if(this._getType(t)!==ns.symbol){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.symbol,received:n.parsedType}),Rc}return XT(t.data)}};F9e.create=e=>new F9e({typeName:au.ZodSymbol,...Xl(e)});var gRe=class extends xp{_parse(t){if(this._getType(t)!==ns.undefined){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.undefined,received:n.parsedType}),Rc}return XT(t.data)}};gRe.create=e=>new gRe({typeName:au.ZodUndefined,...Xl(e)});var ARe=class extends xp{_parse(t){if(this._getType(t)!==ns.null){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.null,received:n.parsedType}),Rc}return XT(t.data)}};ARe.create=e=>new ARe({typeName:au.ZodNull,...Xl(e)});var _Ae=class extends xp{constructor(){super(...arguments),this._any=!0}_parse(t){return XT(t.data)}};_Ae.create=e=>new _Ae({typeName:au.ZodAny,...Xl(e)});var Cce=class extends xp{constructor(){super(...arguments),this._unknown=!0}_parse(t){return XT(t.data)}};Cce.create=e=>new Cce({typeName:au.ZodUnknown,...Xl(e)});var yG=class extends xp{_parse(t){let r=this._getOrReturnCtx(t);return So(r,{code:gn.invalid_type,expected:ns.never,received:r.parsedType}),Rc}};yG.create=e=>new yG({typeName:au.ZodNever,...Xl(e)});var k9e=class extends xp{_parse(t){if(this._getType(t)!==ns.undefined){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.void,received:n.parsedType}),Rc}return XT(t.data)}};k9e.create=e=>new k9e({typeName:au.ZodVoid,...Xl(e)});var xce=class e extends xp{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==ns.array)return So(r,{code:gn.invalid_type,expected:ns.array,received:r.parsedType}),Rc;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(So(r,{code:s?gn.too_big:gn.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&&(So(r,{code:gn.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&&(So(r,{code:gn.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 ez(r,s,r.path,a)))).then(s=>Q1.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new ez(r,s,r.path,a)));return Q1.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:wa.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:wa.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:wa.toString(r)}})}nonempty(t){return this.min(1,t)}};xce.create=(e,t)=>new xce({type:e,minLength:null,maxLength:null,exactLength:null,typeName:au.ZodArray,...Xl(t)});function R9e(e){if(e instanceof eN){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Z4.create(R9e(n))}return new eN({...e._def,shape:()=>t})}else return e instanceof xce?new xce({...e._def,type:R9e(e.element)}):e instanceof Z4?Z4.create(R9e(e.unwrap())):e instanceof GH?GH.create(R9e(e.unwrap())):e instanceof qH?qH.create(e.items.map(t=>R9e(t))):e}var eN=class e extends xp{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=lf.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ns.object){let u=this._getOrReturnCtx(t);return So(u,{code:gn.invalid_type,expected:ns.object,received:u.parsedType}),Rc}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof yG&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=o[u],p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ez(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof yG){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(So(i,{code:gn.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ez(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let p=await l.key,d=await l.value;u.push({key:p,value:d,alwaysSet:l.alwaysSet})}return u}).then(u=>Q1.mergeObjectSync(n,u)):Q1.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return wa.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:wa.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:au.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 lf.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 lf.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return R9e(this)}partial(t){let r={};for(let n of lf.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 lf.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Z4;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return UTs(lf.objectKeys(this.shape))}};eN.create=(e,t)=>new eN({shape:()=>e,unknownKeys:"strip",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});eN.strictCreate=(e,t)=>new eN({shape:()=>e,unknownKeys:"strict",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});eN.lazycreate=(e,t)=>new eN({shape:e,unknownKeys:"strip",catchall:yG.create(),typeName:au.ZodObject,...Xl(t)});var yRe=class extends xp{_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 Zk(a.ctx.common.issues));return So(r,{code:gn.invalid_union,unionErrors:s}),Rc}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 c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new Zk(c));return So(r,{code:gn.invalid_union,unionErrors:a}),Rc}}get options(){return this._def.options}};yRe.create=(e,t)=>new yRe({options:e,typeName:au.ZodUnion,...Xl(t)});var wce=e=>e instanceof ERe?wce(e.schema):e instanceof tz?wce(e.innerType()):e instanceof vRe?[e.value]:e instanceof IRe?e.options:e instanceof wRe?lf.objectValues(e.enum):e instanceof CRe?wce(e._def.innerType):e instanceof gRe?[void 0]:e instanceof ARe?[null]:e instanceof Z4?[void 0,...wce(e.unwrap())]:e instanceof GH?[null,...wce(e.unwrap())]:e instanceof l_t||e instanceof _Re?wce(e.unwrap()):e instanceof xRe?wce(e._def.innerType):[],Dfr=class e extends xp{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.object)return So(r,{code:gn.invalid_type,expected:ns.object,received:r.parsedType}),Rc;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}):(So(r,{code:gn.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Rc)}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=wce(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:au.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Xl(n)})}};function ZEi(e,t){let r=VH(e),n=VH(t);if(e===t)return{valid:!0,data:e};if(r===ns.object&&n===ns.object){let i=lf.objectKeys(t),o=lf.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=ZEi(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===ns.array&&n===ns.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],c=ZEi(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===ns.date&&n===ns.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var bRe=class extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Bfr(o)||Bfr(s))return Rc;let a=ZEi(o.value,s.value);return a.valid?((Pfr(o)||Pfr(s))&&r.dirty(),{status:r.value,value:a.data}):(So(n,{code:gn.invalid_intersection_types}),Rc)};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}))}};bRe.create=(e,t,r)=>new bRe({left:e,right:t,typeName:au.ZodIntersection,...Xl(r)});var qH=class e extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ns.array)return So(n,{code:gn.invalid_type,expected:ns.array,received:n.parsedType}),Rc;if(n.data.length<this._def.items.length)return So(n,{code:gn.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Rc;!this._def.rest&&n.data.length>this._def.items.length&&(So(n,{code:gn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ez(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Q1.mergeArray(r,s)):Q1.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};qH.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qH({items:e,typeName:au.ZodTuple,rest:null,...Xl(t)})};var Rfr=class e extends xp{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!==ns.object)return So(n,{code:gn.invalid_type,expected:ns.object,received:n.parsedType}),Rc;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new ez(n,a,n.path,a)),value:s._parse(new ez(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Q1.mergeObjectAsync(r,i):Q1.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof xp?new e({keyType:t,valueType:r,typeName:au.ZodRecord,...Xl(n)}):new e({keyType:xAe.create(),valueType:t,typeName:au.ZodRecord,...Xl(r)})}},N9e=class extends xp{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!==ns.map)return So(n,{code:gn.invalid_type,expected:ns.map,received:n.parsedType}),Rc;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new ez(n,a,n.path,[u,"key"])),value:o._parse(new ez(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return Rc;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return Rc;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};N9e.create=(e,t,r)=>new N9e({valueType:t,keyType:e,typeName:au.ZodMap,...Xl(r)});var j9e=class e extends xp{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ns.set)return So(n,{code:gn.invalid_type,expected:ns.set,received:n.parsedType}),Rc;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(So(n,{code:gn.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&&(So(n,{code:gn.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(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Rc;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new ez(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:wa.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:wa.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};j9e.create=(e,t)=>new j9e({valueType:e,minSize:null,maxSize:null,typeName:au.ZodSet,...Xl(t)});var Ffr=class e extends xp{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.function)return So(r,{code:gn.invalid_type,expected:ns.function,received:r.parsedType}),Rc;function n(a,c){return u_t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P9e(),Ice].filter(u=>!!u),issueData:{code:gn.invalid_arguments,argumentsError:c}})}function i(a,c){return u_t({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,P9e(),Ice].filter(u=>!!u),issueData:{code:gn.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof SAe){let a=this;return XT(async function(...c){let u=new Zk([]),l=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),p=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(p,o).catch(f=>{throw u.addIssue(i(p,f)),u})})}else{let a=this;return XT(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Zk([n(c,u.error)]);let l=Reflect.apply(s,this,u.data),p=a._def.returns.safeParse(l,o);if(!p.success)throw new Zk([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:qH.create(t).rest(Cce.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||qH.create([]).rest(Cce.create()),returns:r||Cce.create(),typeName:au.ZodFunction,...Xl(n)})}},ERe=class extends xp{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})}};ERe.create=(e,t)=>new ERe({getter:e,typeName:au.ZodLazy,...Xl(t)});var vRe=class extends xp{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return So(r,{received:r.data,code:gn.invalid_literal,expected:this._def.value}),Rc}return{status:"valid",value:t.data}}get value(){return this._def.value}};vRe.create=(e,t)=>new vRe({value:e,typeName:au.ZodLiteral,...Xl(t)});function UTs(e,t){return new IRe({values:e,typeName:au.ZodEnum,...Xl(t)})}var IRe=class e extends xp{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return So(r,{expected:lf.joinValues(n),received:r.parsedType,code:gn.invalid_type}),Rc}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 So(r,{received:r.data,code:gn.invalid_enum_value,options:n}),Rc}return XT(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})}};IRe.create=UTs;var wRe=class extends xp{_parse(t){let r=lf.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ns.string&&n.parsedType!==ns.number){let i=lf.objectValues(r);return So(n,{expected:lf.joinValues(i),received:n.parsedType,code:gn.invalid_type}),Rc}if(this._cache||(this._cache=new Set(lf.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=lf.objectValues(r);return So(n,{received:n.data,code:gn.invalid_enum_value,options:i}),Rc}return XT(t.data)}get enum(){return this._def.values}};wRe.create=(e,t)=>new wRe({values:e,typeName:au.ZodNativeEnum,...Xl(t)});var SAe=class extends xp{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==ns.promise&&r.common.async===!1)return So(r,{code:gn.invalid_type,expected:ns.promise,received:r.parsedType}),Rc;let n=r.parsedType===ns.promise?r.data:Promise.resolve(r.data);return XT(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};SAe.create=(e,t)=>new SAe({type:e,typeName:au.ZodPromise,...Xl(t)});var tz=class extends xp{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===au.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=>{So(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 Rc;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Rc:c.status==="dirty"?pRe(c.value):r.value==="dirty"?pRe(c.value):c});{if(r.value==="aborted")return Rc;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Rc:a.status==="dirty"?pRe(a.value):r.value==="dirty"?pRe(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c 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"?Rc:(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"?Rc:(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(!CAe(s))return Rc;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=>CAe(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Rc);lf.assertNever(i)}};tz.create=(e,t,r)=>new tz({schema:e,typeName:au.ZodEffects,effect:t,...Xl(r)});tz.createWithPreprocess=(e,t,r)=>new tz({schema:t,effect:{type:"preprocess",transform:e},typeName:au.ZodEffects,...Xl(r)});var Z4=class extends xp{_parse(t){return this._getType(t)===ns.undefined?XT(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Z4.create=(e,t)=>new Z4({innerType:e,typeName:au.ZodOptional,...Xl(t)});var GH=class extends xp{_parse(t){return this._getType(t)===ns.null?XT(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};GH.create=(e,t)=>new GH({innerType:e,typeName:au.ZodNullable,...Xl(t)});var CRe=class extends xp{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===ns.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};CRe.create=(e,t)=>new CRe({innerType:e,typeName:au.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xl(t)});var xRe=class extends xp{_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 D9e(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Zk(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zk(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xRe.create=(e,t)=>new xRe({innerType:e,typeName:au.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xl(t)});var Q9e=class extends xp{_parse(t){if(this._getType(t)!==ns.nan){let n=this._getOrReturnCtx(t);return So(n,{code:gn.invalid_type,expected:ns.nan,received:n.parsedType}),Rc}return{status:"valid",value:t.data}}};Q9e.create=e=>new Q9e({typeName:au.ZodNaN,...Xl(e)});var NRl=Symbol("zod_brand"),l_t=class extends xp{_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}},p_t=class e extends xp{_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"?Rc:o.status==="dirty"?(r.dirty(),pRe(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"?Rc: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:au.ZodPipeline})}},_Re=class extends xp{_parse(t){let r=this._def.innerType._parse(t),n=i=>(CAe(i)&&(i.value=Object.freeze(i.value)),i);return D9e(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};_Re.create=(e,t)=>new _Re({innerType:e,typeName:au.ZodReadonly,...Xl(t)});function jTs(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function zTs(e,t={},r){return e?_Ae.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=jTs(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=jTs(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):_Ae.create()}var jRl={object:eN.lazycreate},au;(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"})(au||(au={}));var QRl=(e,t={message:`Input not instance of ${e.name}`})=>zTs(r=>r instanceof e,t),VTs=xAe.create,qTs=fRe.create,MRl=Q9e.create,LRl=dRe.create,GTs=mRe.create,URl=hRe.create,zRl=F9e.create,VRl=gRe.create,qRl=ARe.create,GRl=_Ae.create,WRl=Cce.create,$Rl=yG.create,HRl=k9e.create,KRl=xce.create,JRl=eN.create,YRl=eN.strictCreate,XRl=yRe.create,ZRl=Dfr.create,eFl=bRe.create,tFl=qH.create,rFl=Rfr.create,nFl=N9e.create,iFl=j9e.create,oFl=Ffr.create,sFl=ERe.create,aFl=vRe.create,cFl=IRe.create,uFl=wRe.create,lFl=SAe.create,pFl=tz.create,fFl=Z4.create,dFl=GH.create,mFl=tz.createWithPreprocess,hFl=p_t.create,gFl=()=>VTs().optional(),AFl=()=>qTs().optional(),yFl=()=>GTs().optional(),bFl={string:(e=>xAe.create({...e,coerce:!0})),number:(e=>fRe.create({...e,coerce:!0})),boolean:(e=>mRe.create({...e,coerce:!0})),bigint:(e=>dRe.create({...e,coerce:!0})),date:(e=>hRe.create({...e,coerce:!0}))};var EFl=Rc;var vFl=yt.object({lang:yt.string(),label:yt.optional(yt.string()),source:yt.string()}),evi=yt.array(vFl);Tt();var WTs={README_EXT:"x-readme"};function IFl(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Ma(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function $Ts(e){let t=qr(e,WTs.README_EXT);if(!Ma(t))return[];let r=t["code-samples"];if(!IFl(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 wFl(e){return Ma(e)&&typeof e.$ref=="string"}function CFl(e,t){if(e!=null){if(typeof e=="string")return e;if(wFl(e)){let r=(0,Nfr.resolve)(t??process.cwd(),e.$ref);if((0,kfr.existsSync)(r))try{return(0,kfr.readFileSync)(r,"utf-8")}catch{return}}}}function xFl(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Ma(n))continue;let o=CFl(n.code,t);o!=null&&r.push({...n,code:o})}return r}function HTs(e,t,r){let n=qr(t,On.EXAMPLES),i=r.source.type==="openapi"?(0,Nfr.dirname)(r.source.file):void 0,s=(n??[]).map(p=>{if(!Ma(p))return p;let f=p["code-samples"];if(f!=null){let m=xFl(f,i);return{...p,"code-samples":m}}return p}).filter(p=>{let d=Km.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),a=t_t(t,j1.REDOCLY_CODE_SAMPLES_KEBAB,evi,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],u=[...t_t(t,j1.REDOCLY_CODE_SAMPLES_CAMEL,evi,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];u.length>0&&s.push({"code-samples":u.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let l=$Ts(t);return l.length>0&&s.push({"code-samples":l}),s.map($4.unknown)}function KTs(e){let t=qr(e,On.AVAILABILITY);if(t==="ga"||t==="generally-available")return o_.GenerallyAvailable;if(t==="beta"||t==="pre-release")return o_.Beta;if(t==="deprecated")return o_.Deprecated;if(e.deprecated)return o_.Deprecated}function JTs(e){let t=qr(e,On.RETRIES);if(t!=null&&t.disabled===!0)return Rg.RetriesConfiguration.disabled(t.disabled)}var _Fl="x-fern-default-url";function jfr(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=SFl(e);return{url:TFl({url:e.url,variables:e.variables??{}}),description:e.description,name:BFl(e,t),audiences:qr(e,On.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?OFl(e.variables):void 0,defaultUrl:r?n:void 0}}function SFl(e){let t=e[_Fl];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function OFl(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function TFl({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 BFl(e,t){let r=qr(e,[On.SERVER_NAME_V1,On.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 YTs(e){return qr(e,On.PARAMETER_NAME)}function XTs(e){return qr(e,On.SDK_VARIABLE)}function Qfr({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let s={pathParameters:[],queryParameters:[],headers:[]};for(let a of r){let c=Mn(a)?n.resolveParameterReference(a):a,u=qr(a,On.IGNORE)??qr(c,On.IGNORE);if(u!=null&&u){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let l=c.required??!1,p=sw(c),d=[...i,c.name],f=kb(d,n.options.preserveSchemaIds),m=c.in==="header",[h,g]=n.options.coerceOptionalSchemasToNullable&&!m?[!1,!l]:[!l,!1],A=c.schema!=null?ic(c.schema,h,g,n,d,o,n.namespace,!1,new Set,X4({schema:c,logger:n.logger})):l?Dr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Di.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:X4({schema:c,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Dr.optional({nameOverride:void 0,generatedName:f,title:void 0,value:Dr.primitive({nameOverride:void 0,generatedName:f,title:void 0,schema:Di.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:X4({schema:c,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(c.in==="header"&&c.schema!=null&&!Mn(c.schema)&&c.schema.default!=null){let E=c.schema.default;typeof E=="string"&&E.length>0&&(A=Dr.literal({nameOverride:void 0,generatedName:f,title:void 0,value:LA.string(E),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let b=qr(a,On.FERN_DEFAULT)??qr(c,On.FERN_DEFAULT),v={name:c.name,schema:A,description:c.description,parameterNameOverride:YTs(c),availability:p,source:o,clientDefault:b};c.in==="query"?s.queryParameters.push({...v,explode:DFl(c)}):c.in==="path"?s.pathParameters.push({...v,variableReference:XTs(c),explode:RFl(c)}):c.in==="header"?!PFl.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?s.headers.push({...v,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return s}var PFl=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function DFl(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 RFl(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}Tt();function FFl({content:e,context:t}){for(let[r,n]of Object.entries(e))if(eBs({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function eBs({mediaType:e,mediaTypeObject:t,context:r}){if(Lf.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:T9e(t,r)}}function kFl({content:e,context:t}){for(let[r,n]of Object.entries(e))if(tBs({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function tBs({mediaType:e,mediaTypeObject:t,context:r}){if(Lf.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:T9e(t,r)}}function rBs({mediaType:e}){return Lf.parse(e)?.isBinary()??!1}function NFl({content:e}){for(let[t,r]of Object.entries(e))if(rBs({mediaType:t}))return[t,r]}function jFl(e,t){let r=Mn(e)?tvi(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!Mn(i)&&i.type==="string"&&(i.format==="binary"||i.format==null&&i.contentMediaType==="application/octet-stream"))!=null}function Lfr({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}){let a=NFl({content:e});if(a){let[d,f]=a;return WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}let c=kFl({content:e,context:n}),u=KEi({content:e,context:n}),l=QFl({json:u,multipart:c,document:r,visitor:{json:([d,f])=>WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),multipart:([d,f])=>WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s}),neither:()=>{}}});if(l)return l;let p=FFl({content:e,context:n});if(p){let[d,f]=p;return WH({mediaType:d,mediaTypeObject:f,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:s})}}function QFl({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,o]=t??[void 0,void 0];return!i?.schema&&!o?.schema?e&&(i?.example!=null||i?.examples!=null&&Object.keys(i.examples).length>0)?n.json(e):n.neither():i?.schema&&o?.schema?i.schema&&jFl(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function WH({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:s,namespace:a}){let c=MFl({mediaTypeObject:t});if(rBs({mediaType:e}))return zD.octetStream({description:r,source:s,sdkMethodName:c,contentType:e});let u=tBs({mediaType:e,mediaTypeObject:t,context:i}),l=u?.schema,p=u?.encoding,d=u?.examples;if(l){let h=Mn(l)?tvi(l,n):{id:void 0,schema:l},g=ic(h.schema,!1,!1,i,o,s,a,!1),A=[];if(g.type==="object"){let b=new Set(h.schema.required??[]);for(let v of g.properties){let E=b.has(v.key),{isFile:I,isOptional:w,isArray:x,description:C}=Mfr({schema:v.schema,isOptional:!E});if(I){let _=ZTs(v.key,p);A.push({key:v.key,schema:RH.file({isOptional:w,isArray:x,description:C}),description:C,contentType:_,exploded:!1,encoding:_==null?i.options.defaultFormParameterEncoding:void 0})}else{let _=ZTs(v.key,p);A.push({key:v.key,schema:RH.json(v.schema),description:void 0,contentType:_,exploded:p?.[v.key]?.explode,encoding:_==null?i.options.defaultFormParameterEncoding:UFl(_)})}}}return zD.multipart({name:Mn(l)&&i.getNumberOfOccurrencesForRef(l)===1?h.id:void 0,description:h.schema.description,properties:A,source:s,sdkMethodName:c,fullExamples:d})}let f=Ofr({mediaType:e,mediaTypeObject:t,context:i});if(f){let h=ic(f.schema,!1,!1,i,o,s,a,!0);return zD.json({description:void 0,schema:h,contentType:f.contentType,fullExamples:f.examples,additionalProperties:!Mn(f.schema)&&n_t(f.schema.additionalProperties,i.options),source:s,sdkMethodName:c})}let m=eBs({mediaType:e,mediaTypeObject:t,context:i});if(m!=null&&m.schema!=null){let h=ic(m.schema,!1,!1,i,o,s,a,!1);return zD.formUrlEncoded({schema:h,description:r,contentType:m.contentType,source:s,fullExamples:m.examples,additionalProperties:!1,sdkMethodName:c})}}function MFl({mediaTypeObject:e}){return qr(e,On.SDK_METHOD_NAME)}var LFl={"application/json":"json"};function UFl(e){return e?LFl[e]:void 0}function tvi(e,t){if(!e.$ref.startsWith(cRe))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=w9e(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 Mn(n)?tvi(n,t):{id:r,schema:n}}function Mfr({schema:e,isOptional:t,isArray:r,description:n}){return VFl(e)?Mfr({schema:e.value,isOptional:!0,isArray:r,description:e.description}):qFl(e)?Mfr({schema:e.value,isOptional:t,isArray:r,description:e.description}):GFl(e)?Mfr({schema:e.value,isOptional:t,isArray:!0,description:e.description}):zFl(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 zFl(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function VFl(e){return e.type==="optional"}function qFl(e){return e.type==="nullable"}function GFl(e){return e.type==="array"}function ZTs(e,t){return t?.[e]?.contentType}Tt();var rvi={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"},nBs=new Set(Object.values(rvi));var WFl=["200","201","202","204"];function Ufr({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 c=$Fl({responses:t,context:r,source:a,namespace:r.namespace}),u=!1,l=!1,p;for(let d of i!=null?[i]:WFl){let f=t[d];if(f==null)continue;u=!0;let m=typeof d=="string"?parseInt(d):d;if(p==null){let h=iBs({operationContext:e,response:f,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace,statusCode:m});h!=null?p=h:m===204&&(l=!0)}else if(m===204){let h=Mn(f)?r.resolveResponseReference(f):f;a_t({context:r,content:h.content??{}})==null&&(l=!0)}}if(l&&p!=null&&p.type==="json"){let d=p.schema;d.type!=="optional"&&(p=ng.json({...p,schema:Dr.optional({value:d,description:d.type==="reference"?d.description:void 0,nameOverride:void 0,generatedName:"",groupName:void 0,namespace:void 0,availability:void 0,title:void 0,inline:void 0})}))}if(p==null&&!u&&t.default!=null&&(p=iBs({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,streamTerminator:s,source:a,namespace:r.namespace})),p!=null)switch(p.type){case"json":return{value:p,errors:c};case"streamingJson":case"streamingSse":return{value:p,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:p,errors:c};default:we(p)}return{value:void 0,errors:c}}function iBs({operationContext:e,streamFormat:t,streamTerminator:r,response:n,context:i,responseBreadcrumbs:o,source:s,namespace:a,statusCode:c}){let u=Mn(n)?i.resolveResponseReference(n):n;if(u.content!=null&&Object.entries(u.content).find(([f,m])=>{if(m.schema==null)return!1;let h=Mn(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?ng.bytes({description:u.description,source:s,statusCode:c}):ng.file({description:u.description,source:s,statusCode:c});let l=_Ts(u.content??{},i);if(l!=null&&t!=null)switch(t){case"json":return ng.streamingJson({statusCode:c,description:u.description,responseProperty:qr(e.operation,On.RESPONSE_PROPERTY),terminator:r,fullExamples:l.examples,schema:ic(l.schema,!1,!1,i,o,s,a),source:s});case"sse":return ng.streamingSse({description:u.description,responseProperty:void 0,terminator:r,fullExamples:l.examples,schema:ic(l.schema,!1,!1,i,o,s,a),source:s,statusCode:c})}let p=a_t({context:i,content:u.content??{}});if(p){if(t!=null)switch(t){case"json":return ng.streamingJson({description:u.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:ic(p.schema,!1,!1,i,o,s,a),source:s,statusCode:c});case"sse":return ng.streamingSse({description:u.description,responseProperty:void 0,terminator:r,fullExamples:p.examples,schema:ic(p.schema,!1,!1,i,o,s,a),source:s,statusCode:c})}return ng.json({description:u.description,schema:ic(p.schema,!1,!1,i,o,s,a),responseProperty:qr(e.operation,On.RESPONSE_PROPERTY),terminator:void 0,fullExamples:p.examples,source:s,statusCode:c})}for(let[d,f]of Object.entries(u.content??{})){let m=Lf.parse(d);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return ng.file({description:u.description,source:s,statusCode:c});if(m.isText()&&!d.includes("event-stream")){let h=f.schema;if(h==null)return ng.text({description:u.description,source:s,statusCode:c});let g=Mn(h)?i.resolveSchemaReference(h):h;return g.type==="string"&&g.format==="byte"?ng.file({description:u.description,source:s,statusCode:c}):ng.text({description:u.description,source:s,statusCode:c})}}}}function $Fl({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 c=Mn(s)?t.resolveResponseReference(s):s,u=OTs(c.content??{},t),l=rvi[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:c.description,schema:ic(u?.schema??{},!1,!1,t,[l,"Body"],r,n),fullExamples:u?.examples,source:r}}return i}function _ce({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,streamTerminator:o,source:s,streamRequestNameOverride:a}){let{document:c,operation:u,path:l,method:p,baseBreadcrumbs:d,pathItem:f}=e,m=qr(u,On.IDEMPOTENT),h=qr(u,[On.REQUEST_NAME_V1,On.REQUEST_NAME_V2]),g=[...d,"Request"],A=Qfr({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:l,httpMethod:p,source:s}),b=/{([^}]+)}/g,v=[...l.matchAll(b)].map(z=>z[1]).filter(z=>z!==void 0),E=[...l.matchAll(b)].map(z=>z[1]);switch(t.options.pathParameterOrder){case Dn.PathParameterOrder.SpecOrder:{let z=E.filter(K=>!A.pathParameters.some(ie=>ie.name===K));if(z.length>0)for(let K of z)A.pathParameters.push({name:K??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Dr.primitive({schema:Di.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}break;case Dn.PathParameterOrder.UrlOrder:if(v.length>0){let z=new Map(A.pathParameters.map(q=>[q.name,q])),K=[],ie=new Set;for(let q of v){let H=z.get(q);ie.add(q),H?K.push(H):K.push({name:q,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:s,schema:Dr.primitive({schema:Di.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0,clientDefault:void 0})}for(let q of A.pathParameters)ie.has(q.name)||K.push(q);A.pathParameters=K}break;default:we(t.options.pathParameterOrder)}let I=(()=>{if(e.method==="GET")return[void 0];if(!u.requestBody)return[void 0];let z=Mn(u.requestBody)?t.resolveRequestBodyReference(u.requestBody):u.requestBody,K=Object.values(z.content).every(q=>KFl({mediaTypeObject:q})!=null),ie=[];if(K)return ie.push(...Object.entries(z.content).map(([q,H])=>{let ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:new lRe({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return oBs({context:t,convertedParameters:A})&&ye!=null&&(ye.type==="json"||ye.type==="formUrlEncoded")&&ye.schema.type!=="object"&&u.requestBody!=null?ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):u.requestBody!=null&&(ye=WH({mediaType:q,mediaTypeObject:H,description:z.description,document:c,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),ye}).filter(q=>q!=null)),ie.length===0?[void 0]:ie;{let q=Lfr({content:z.content,description:z.description,document:c,context:new lRe({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:s,namespace:t.namespace});return oBs({context:t,convertedParameters:A})&&q!=null&&(q.type==="json"||q.type==="formUrlEncoded")&&q.schema.type!=="object"&&u.requestBody!=null?q=Lfr({content:z.content,description:z.description,document:c,context:t,requestBreadcrumbs:[...g,"Body"],source:s,namespace:t.namespace}):u.requestBody!=null&&(q=Lfr({content:z.content,description:z.description,document:c,context:t,requestBreadcrumbs:[...g],source:s,namespace:t.namespace})),[q]}})(),w=I.length>1,x=[...d,"Response"],C=Ufr({operationContext:e,streamFormat:i,streamTerminator:o,responses:u.responses,context:t,responseBreadcrumbs:x,responseStatusCode:r,source:s}),_=JTs(u),R=KTs(u),G=HTs(e,u,t),V=qr(u,On.SERVER_NAME_V2);return I.map(z=>({summary:u.summary,internal:qr(u,j1.INTERNAL),idempotent:m,audiences:qr(u,On.AUDIENCES)??[],operationId:u.operationId!=null&&n!=null?u.operationId+"_"+n:u.operationId,tags:t.resolveTagsToTagIds(u.tags),namespace:t.namespace,sdkName:JFl({operationContext:e,request:z}),pathParameters:A.pathParameters,queryParameters:A.queryParameters,headers:A.headers,requestNameOverride:a??h??void 0,generatedRequestName:kb(w?HFl({breadcrumbs:g,request:z}):g,t.options.preserveSchemaIds),request:z,response:C.value,errors:C.errors,servers:V!=null?[{name:V,url:void 0,audiences:void 0}]:(u.servers??f.servers??[]).map(K=>jfr(K,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:u.description,authed:XFl(u,c),security:YFl(u),availability:R,method:p,path:l,examples:G,pagination:e.pagination,source:s,retries:_}))}function HFl({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function KFl({mediaTypeObject:e}){return qr(e,On.SDK_METHOD_NAME)}function JFl({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 YFl(e){return e.security}function XFl(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function oBs({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function aBs({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:s}=e,a=r.discriminant.name,c=r.discriminant.value,u=r["response-status-code"],l=sBs({context:t,headerToIgnore:a,parameters:o}),p=sBs({context:t,headerToIgnore:a,parameters:s}),d=_ce({operationContext:{...e,pathItemParameters:l,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([m])=>parseInt(m)!==u))}},context:t,streamFormat:void 0,source:n}),f=_ce({operationContext:{...e,pathItemParameters:l,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:u,streamFormat:void 0,source:n});return f.forEach(m=>{m.headers.push({name:a,schema:Dr.literal({nameOverride:void 0,generatedName:kb([a],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:LA.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n,clientDefault:void 0})}),{sync:d,async:f}}function sBs({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=Mn(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}Tt();var nvi="stream";function pBs({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:_ce({operationContext:e,context:t,streamFormat:r.format,streamTerminator:r.terminator,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=cBs({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0}),i=uBs({operation:e.operation,response:r.responseStream}),o=(()=>{if(r.streamRequestName!=null)return r.streamRequestName;if(n?.schemaReference!=null){let l=t.resolveSchemaReference(n.schemaReference),p=qr(l,On.TYPE_NAME);if(p!=null)return`${p}Streaming`}})(),s=_ce({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+nvi}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,nvi]},context:t,streamFormat:r.format,streamTerminator:r.terminator,suffix:nvi,source:t.source,streamRequestNameOverride:o});s.forEach(l=>{l.examples=l.examples.filter(p=>lBs(p,t)!==!1)});let a=cBs({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=uBs({operation:e.operation,response:r.response}),u=_ce({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:c}},context:t,source:t.source});return u.forEach(l=>{l.examples=l.examples.filter(p=>lBs(p,t)!==!0)}),{streaming:s,nonStreaming:u}}default:we(r)}}function cBs({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=Mn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=a_t({content:i.content,context:e});if(o==null)return;let s=Mn(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(s.allOf==null&&s.properties==null)return;let a=s.properties?.[r.streamConditionProperty];a!=null&&Mn(a)&&(a=void 0);let c={...s,properties:{...s.properties,[r.streamConditionProperty]:{...a??{},type:"boolean","x-fern-boolean-literal":n}},title:void 0,required:[...s.required??[],r.streamConditionProperty]};return{requestBody:{content:{[Lf.APPLICATION_JSON]:{schema:c}}},schemaReference:Mn(o.schema)?o.schema:void 0}}function uBs({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[Lf.APPLICATION_JSON]:{schema:t}}}}}function lBs(e,t){return e._visit({unknown:r=>{let n=Km.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var ABs=require("crypto");function ZFl(e){switch(e){case"unix-seconds":return Rg.WebhookTimestampFormat.UnixSeconds;case"unix-millis":return Rg.WebhookTimestampFormat.UnixMillis;case"iso8601":return Rg.WebhookTimestampFormat.Iso8601}}function fBs(e){if(e!=null)return{header:e.header,format:e.format!=null?ZFl(e.format):void 0,tolerance:e.tolerance}}function ekl(e){if(e!=null)return{components:e.components.map(t=>{switch(t){case"body":return Rg.WebhookPayloadComponent.Body;case"timestamp":return Rg.WebhookPayloadComponent.Timestamp;case"notification-url":return Rg.WebhookPayloadComponent.NotificationUrl;case"message-id":return Rg.WebhookPayloadComponent.MessageId}}),delimiter:e.delimiter,bodySort:tkl(e["body-sort"])}}function tkl(e){if(e!=null&&e==="alphabetical")return Rg.WebhookPayloadBodySort.Alphabetical}function rkl(e){if(e!=null)switch(e){case"sha256":return Rg.WebhookSignatureAlgorithm.Sha256;case"sha1":return Rg.WebhookSignatureAlgorithm.Sha1;case"sha384":return Rg.WebhookSignatureAlgorithm.Sha384;case"sha512":return Rg.WebhookSignatureAlgorithm.Sha512}}function dBs(e){if(e!=null)switch(e){case"base64":return Rg.WebhookSignatureEncoding.Base64;case"hex":return Rg.WebhookSignatureEncoding.Hex}}function nkl(e){if(e!=null)switch(e){case"rsa-sha256":return Rg.AsymmetricAlgorithm.RsaSha256;case"rsa-sha384":return Rg.AsymmetricAlgorithm.RsaSha384;case"rsa-sha512":return Rg.AsymmetricAlgorithm.RsaSha512;case"ecdsa-sha256":return Rg.AsymmetricAlgorithm.EcdsaSha256;case"ecdsa-sha384":return Rg.AsymmetricAlgorithm.EcdsaSha384;case"ecdsa-sha512":return Rg.AsymmetricAlgorithm.EcdsaSha512;case"ed25519":return Rg.AsymmetricAlgorithm.Ed25519}}function hBs(e){if(e.type==="hmac")return Rg.WebhookSignatureVerification.hmac({header:e.header,algorithm:rkl(e.algorithm),encoding:dBs(e.encoding),signaturePrefix:e["signature-prefix"],payloadFormat:ekl(e["payload-format"]),timestamp:fBs(e.timestamp)});if(e.type==="asymmetric"){let t=nkl(e["asymmetric-algorithm"]);return t==null?void 0:Rg.WebhookSignatureVerification.asymmetric({header:e.header,asymmetricAlgorithm:t,encoding:dBs(e.encoding),signaturePrefix:e["signature-prefix"],jwksUrl:e["jwks-url"],keyIdHeader:e["key-id-header"],timestamp:fBs(e.timestamp)})}}function mBs(e){let t=qr(e,On.WEBHOOK_SIGNATURE);if(!(t==null||typeof t=="boolean"))return hBs(t)}function gBs(e,t){let r=qr(t,On.WEBHOOK_SIGNATURE);return r!=null?typeof r=="boolean"?mBs(e):hBs(r):mBs(e)}function yBs({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:s,baseBreadcrumbs:a,sdkMethodName:c}=t,u=[...a,"Payload"],l=[...a,"Response"],p=Qfr({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:u,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??okl({path:o,method:s,sdkMethodName:c}),f=i.responses?Ufr({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:l,source:r}):void 0,m=gBs(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:kb([...u,v.name],e.options.preserveSchemaIds),availability:v.availability})),A=Dr.object({description:i.description,properties:g,nameOverride:void 0,generatedName:kb(u,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:qr(i,On.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:kb(u,e.options.preserveSchemaIds),payload:A,signatureVerification:m,multipartFormData:void 0,response:f?.value,description:i.description,examples:[],source:r}]}let h=Mn(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([g,A])=>WH({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,b;return g.type==="multipart"?(A={name:g.name,properties:g.properties,description:g.description,source:g.source},b=Dr.unknown({nameOverride:void 0,generatedName:kb(u,e.options.preserveSchemaIds),title:void 0,description:g.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):b=g.schema,{summary:i.summary,audiences:qr(i,On.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:s,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:kb(u,e.options.preserveSchemaIds),payload:b,signatureVerification:m,multipartFormData:A,response:f?.value,description:i.description,examples:ikl(g.fullExamples),source:r}}).filter(g=>g!=null)}function ikl(e){if(e==null)return[];let t=[];for(let r of e){let n=IAe(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function okl({path:e,method:t,sdkMethodName:r}){if(r?.methodName!=null)return r.methodName;let n=skl(e);if(n===e.toLowerCase())return e;let i=(0,ABs.createHash)("sha256").update(e).digest("hex").slice(0,8);return akl(`${n}_${t.toLowerCase()}_${i}`)}function skl(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function akl(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function ivi({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=qr(r,On.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=ckl(r,e),s=xTs(e.document,r),a={...t,sdkMethodName:o,baseBreadcrumbs:ukl({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:yBs({context:e,operationContext:a,source:e.source})};let c=wTs(r);if(c==null&&lkl({operation:r,context:e})&&(c={type:"stream",format:"sse",terminator:void 0}),c!=null){let p=pBs({context:e,operationContext:a,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let u=vTs(r);if(u!=null){let p=aBs({context:e,operationContext:a,asyncExtension:u,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:_ce({context:e,operationContext:a,streamFormat:void 0,source:e.source})}}function ckl(e,t){let r=qr(e,On.SDK_METHOD_NAME),n=qr(e,On.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function ukl({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(Jn(`${r}_${n.split("/").join("_")}`));return o}function lkl({operation:e,context:t}){if(e.responses==null)return!1;for(let[r,n]of Object.entries(e.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=Mn(n)?t.resolveResponseReference(n):n;if(o.content!=null&&STs(o.content))return!0}return!1}function bBs(e,t,r,n){let i=[],o=vBs(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=pkl({operation:a.operation}),u=ivi({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:c});u&&i.push(u)}return i}function EBs(e,t,r,n){let i=[],o=vBs(t),s={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let a of o){if(n.filter.skipEndpoint({method:a.method,path:e})){n.logger.debug(`Skipping endpoint "${a.method} ${e}"`);continue}let c=ivi({context:n,pathItemContext:{...s,method:a.method},operation:a.operation,convertToWebhook:!0});c&&i.push(c)}return i}function vBs(e){let t=[];return e.get!=null&&t.push({method:s_.Get,operation:e.get}),e.post!=null&&t.push({method:s_.Post,operation:e.post}),e.put!=null&&t.push({method:s_.Put,operation:e.put}),e.delete!=null&&t.push({method:s_.Delete,operation:e.delete}),e.patch!=null&&t.push({method:s_.Patch,operation:e.patch}),e.head!=null&&t.push({method:s_.Head,operation:e.head}),t}function pkl({operation:e}){return qr(e,[On.WEBHOOK])??!1}function IBs(e){let t=qr(e,On.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=qr(e,On.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function wBs(e){return qr(e,On.FERN_BASIC_AUTH)}function xBs(e,t,r,n){if(Mn(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return CBs(i,t,r)}return CBs(e,t,r)}function CBs(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=qr(e,j1.BEARER_FORMAT),i=qr(e,On.FERN_HEADER_AUTH);return i_.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??qr(e,On.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=qr(e,On.FERN_BEARER_TOKEN);return i_.bearer({tokenVariableName:n?.name??qr(e,On.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=wBs(e),i=IBs(e);return i_.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 i_.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return i_.oauth({scopesEnum:fkl(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 fkl(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=EAe({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=cd(n);if(i.type==="enum")return i}}function _Bs(e){return qr(e,On.BASE_PATH)}var dkl=yt.record(yt.string(),yt.object({summary:yt.string().optional(),description:yt.string().optional()}));function SBs({document:e,context:t}){return t_t(e,On.GROUPS,dkl,t.logger)}function OBs({context:e,document:t}){return qr(t,On.FERN_VERSION)??void 0}function TBs(e){let t=qr(e,On.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({header:n.header,name:n.name,optional:n.optional,env:n.env,clientDefault:n["x-fern-default"],schema:n.type!=null?r_t({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 BBs(e){let t=qr(e,On.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?r_t({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 PBs(e,t){let r=qr(e,On.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:kb([n],t),title:i.title,schema:Il.string({default:C9e(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 mkl="webhooks";function DBs(e){return qr(e,mkl)??{}}var f_t=class extends B9e{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 lRe({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 RBs(e){return qr(e,On.RESOLUTIONS)}function FBs({openapi:e}){let t=RBs(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=hkl({openapi:e,schemaReference:o,schemaName:n.name}),e=kBs({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(s=>[i,s]))}}return e}function hkl({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 kBs({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,u)=>u.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let u=r.replace(i,c);return kBs({openapi:e,replaceReference:t,schemaReference:u,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),s=e;for(let c of o.slice(0,-1)){let u=s[c];if(u==null)return e;s=u}let a=o[o.length-1];return a==null||(s[a]={$ref:r}),e}function jBs({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=FBs({openapi:e}),Ekl({openApi:e,taskContext:t}),Efr();let o=new f_t({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),s=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([G,V])=>{let z=xBs(V,n,t,o);return z==null?null:[G,z]}).filter(G=>G!==null)),a=e.security?.filter(G=>G!=null),c=new Set(Object.entries(s).map(([G,V])=>V.type==="basic"||V.type==="bearer"||V.type==="oauth"?"Authorization":V.type==="header"?V.headerName:null).filter(G=>G!=null)),u=PBs(e,r.preserveSchemaIds),l=TBs(e),p=BBs(e),d=r.audiences??[],f=[],m=[],h=new f_t({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});h.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([G,V])=>{if(V==null)return;let z=bBs(G,V,e,h);for(let K of z){let ie=NBs({operation:K});if(!(d.length>0&&!d.some(q=>ie.includes(q))))switch(K.type){case"async":f.push(...K.sync),f.push(...K.async);break;case"http":f.push(...K.value);break;case"streaming":f.push(...K.streaming),K.nonStreaming&&f.push(...K.nonStreaming);break;case"webhook":m.push(...K.value);break;default:we(K)}}}),Object.entries(DBs(e)).forEach(([G,V])=>{if(V==null)return;t.logger.debug(`Converting path ${G}`);let z=EBs(G,V,e,h);for(let K of z){let ie=NBs({operation:K});d.length>0&&!d.some(q=>ie.includes(q))||m.push(...K.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([G,V])=>{let z=qr(V,On.SDK_NAMESPACE);if(!Mn(V)){let K=qr(V,On.IGNORE);if(K!=null&&K)return[];if(nBs.has(G))return[G,ic({...V,"x-fern-type-name":`${G}Body`},!1,!1,h,[G],n,z??i)]}return[G,ic(V,!1,!1,h,[G],n,z??i)]}).filter(G=>G.length>0)),A=gkl(g,h,n),b=ykl(A,h),v=UH(),E={};for(let[G,V]of Object.entries(b)){let z=cd(V);if(h.isSchemaExcluded(G))continue;let K=v.getUniqueSchemaId(G,h.logger,r.resolveSchemaCollisions);E[K]=z}let I=new wAe(b,h.nonRequestReferencedSchemas,h),w=m.map(G=>{let z=G.examples;if(!r.disableExamples&&z.length===0){let K=I.buildExample({schema:G.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});K!=null&&(z=[{name:void 0,description:void 0,payload:K}])}return{...G,payload:cd(G.payload),examples:z}}),x=new wfr(b,h,l),C=f.map(G=>{let V=G.examples,z=V;if(!r.disableExamples&&(V.length===0||V.every(s_t))){let q=x.buildEndpointExample(G);q.length>0&&(z=[...q,...V.filter(H=>!s_t(H))])}let K=G.request,ie=G.response;return{...G,request:K?.type==="json"||K?.type==="formUrlEncoded"?{...K,schema:cd(K.schema)}:K,response:ie?.type==="json"?{...ie,schema:cd(ie.schema)}:ie,queryParameters:G.queryParameters.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,explode:q.explode,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),pathParameters:G.pathParameters.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,variableReference:q.variableReference,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),headers:G.headers.map(q=>({description:q.description,name:q.name,schema:cd(q.schema),parameterNameOverride:q.parameterNameOverride,env:q.env,availability:q.availability,source:q.source,clientDefault:q.clientDefault})),examples:z,errors:Jl(G.errors,q=>{let H=q.fullExamples?.map(ye=>{let Ee=IAe(ye.value);if(Ee!=null)return{name:ye.name,description:ye.description,example:Ee}}).filter(Pa);if(H?.length===0){let ye=I.buildExample({schema:q.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ye!=null&&H.push({name:void 0,description:void 0,example:ye})}return{generatedName:q.generatedName,nameOverride:q.nameOverride,schema:cd(q.schema),description:q.description,source:q.source,examples:H}}),retries:G.retries}});x.finalize();let _=SBs({document:e,context:h});return{apiVersion:OBs({context:h,document:e}),basePath:_Bs(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(_??{}).map(([G,V])=>[G,{summary:V.summary??void 0,description:V.description??void 0}])),servers:(e.servers??[]).map(G=>jfr(G,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(G=>[G.name,{id:G.name,description:G.description}])),orderedTagIds:e.tags?.map(G=>G.name)},endpoints:C,webhooks:w,channels:{},groupedSchemas:_9e(i,E),securitySchemes:s,security:a,hasEndpointsMarkedInternal:C.some(G=>G.internal),nonRequestReferencedSchemas:h.getReferencedSchemas(),variables:u,globalHeaders:l,idempotencyHeaders:p}}function gkl(e,t,r){if(t.options.removeDiscriminantsFromSchemas===Dn.RemoveDiscriminantsFromSchemas.Never)return e;let n=Akl(e,t),i={};for(let[o,s]of Object.entries(e)){if(s.type!=="object"){i[o]=s;continue}let a={$ref:`#/components/schemas/${o}`},c=t.getReferencesFromDiscriminatedUnion(a);if(c==null){i[o]=s;continue}if(t.getReferencedSchemas().has(o)){i[o]=s;continue}let l={...s,type:"object",properties:s.properties.filter(d=>!c.discriminants.has(d.key)),allOfPropertyConflicts:s.allOfPropertyConflicts.filter(d=>!c.discriminants.has(d.propertyKey)),source:r};i[o]=l;let p=ovi({schema:s,schemas:e});for(let d of[...new Set(p)]){if(n.has(d))continue;let f=i[d]??e[d];f==null||f.type!=="object"||(i[d]={...f,type:"object",properties:f.properties.filter(m=>!c.discriminants.has(m.key)),allOfPropertyConflicts:f.allOfPropertyConflicts.filter(m=>!c.discriminants.has(m.propertyKey))})}}return i}function Akl(e,t){let r=new Set;for(let[n,i]of Object.entries(e)){if(i.type!=="object")continue;let o={$ref:`#/components/schemas/${n}`};if(t.getReferencesFromDiscriminatedUnion(o)==null)for(let s of ovi({schema:i,schemas:e}))r.add(s)}return r}function ykl(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 u of i.properties)if(s.discriminants.has(u.key)){let l=s.discriminants.get(u.key);l!=null&&a.push({...u,schema:Dr.literal({nameOverride:void 0,generatedName:kb([i.generatedName,l],t.options.preserveSchemaIds),title:void 0,value:LA.string(l),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else a.push(u);let c={...i,type:"object",properties:a};r[n]=c}return r}function ovi({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(...ovi({schema:i,schemas:t}))}return r}function zfr(e){return[...new Set(e)]}var Vfr=new RegExp("[^\\x00-\\x7F]"),bkl=/(?:^|\n)\s*---\s*(?:\n|$)/;function Ekl({openApi:e,taskContext:t}){for(let r of e.tags??[])if(Vfr.test(r.name)){let n=[...r.name].filter(i=>Vfr.test(i));t.logger.error(`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR). Remove non-ASCII characters from the tag name.`)}for(let[r,n]of Object.entries(e.paths??{}))if(n!=null)for(let i of["get","post","put","delete","patch","options","head","trace"]){let o=n[i];if(o?.description!=null&&bkl.test(o.description)&&t.logger.error(`Description at paths.${r}.${i} contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. Remove the "---" delimiters from the description.`),o?.tags!=null&&(e.tags==null||e.tags.length===0)){for(let s of o.tags)if(Vfr.test(s)){let a=[...s].filter(c=>Vfr.test(c));t.logger.error(`Tag name "${s}" at paths.${r}.${i} contains non-ASCII characters: ${a.join(", ")}. Remove non-ASCII characters from the tag name.`)}}}}function NBs({operation:e}){let t=[];switch(e.type){case"async":t=zfr(e.async.flatMap(r=>r.audiences));break;case"http":t=zfr(e.value.flatMap(r=>r.audiences));break;case"streaming":t=zfr(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=zfr(e.value.flatMap(r=>r.audiences));break;default:we(e)}return t}function SRe({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:KT.openapi({file:"<memory>"});switch(o.type){case"openapi":{let a=jBs({taskContext:e,openApi:o.value,options:Y4({options:o.settings,overrides:r}),source:s,namespace:o.namespace});n=xkl(n,a,Y4({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let a=ETs({document:o.value,taskContext:e,options:Y4({options:o.settings,overrides:r}),source:s,asyncApiOptions:vkl({options:o.settings}),namespace:o.namespace});a.servers!=null&&(n.websocketServers=[...n.websocketServers,...a.servers.map(c=>({...c,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),a.channels!=null&&(n.channels={...n.channels,...a.channels}),a.groupedSchemas!=null&&(n.groupedSchemas=qfr(n.groupedSchemas,a.groupedSchemas,r)),a.basePath!=null&&(n.basePath=a.basePath),i++;break}default:we(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?`
1499
1499
  `+s.stack:"")}return n}function vkl({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??kOs.naming}}function Gfr(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 avi(e){try{let n=new URL(e).hostname.split("."),i=new Set(["api","www","service","services","example","com","org","net","io"]);for(let s of n){let a=s.split("-")[0],c=a&&a.length>2?a:s;if(c&&!i.has(c.toLowerCase())&&c.length>2)return c.toLowerCase()}let o=n[0];return o&&o.length>0?o.toLowerCase():"api"}catch{let t=e.match(/https?:\/\/([^./-]+)/);return t&&t[1]?t[1].toLowerCase():"api"}}function svi(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 u of s)a[u]=o[u]??[];let c=JSON.stringify(a);i.has(c)||i.set(c,o)}return Array.from(i.values())}function Ikl(e,t){if(Ckl(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=Gfr(o);r.set(s,o.url)}let n=!0,i=!0;for(let o of t){if(o.type==="grouped")continue;let s=Gfr(o),a=r.get(s);a?a===o.url&&(i=!1):n=!1}return n&&i}function cvi(e){return e.defaultUrl??e.url}function wkl(e){if(e.length===0||!e[0])return"api";let t=e[0];return t.type==="grouped"?Object.keys(t.urls)[0]??"api":avi(cvi(t))}function Ckl(e){return e.some(t=>t.type==="grouped")}function xkl(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:qfr(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:svi(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(Ikl(e.servers,t.servers)){let o=[],s=[],a=wkl(t.servers),c=new Map;for(let p of e.servers)if(p.type==="grouped"){let d=p.name??"default";c.has(d)||c.set(d,{});let f=c.get(d);if(f)for(let[m,h]of Object.entries(p.urls))f[m]=h}else{let d=avi(cvi(p)),f=Gfr(p);c.has(f)||c.set(f,{});let m=c.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=Gfr(p);c.has(d)||c.set(d,{});let f=c.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 c.entries()){let f={type:"grouped",name:p,description:`${p} environment`,urls:d};o.push(f)}let u=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"?avi(cvi(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=[...u,...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:qfr(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:svi(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:qfr(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:svi(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 qfr(e,t,r){let n=UH(),i=r?.resolveSchemaCollisions??!1,o={...e.rootSchemas};for(let[s,a]of Object.entries(t.rootSchemas)){let c=n.getUniqueSchemaId(s,void 0,i);o[c]=a}e.rootSchemas=o;for(let[s,a]of Object.entries(t.namespacedSchemas))if(e.namespacedSchemas[s]!=null){let c=e.namespacedSchemas[s];for(let[u,l]of Object.entries(a)){let p=n.getUniqueSchemaId(u,void 0,i);c[p]=l}}else e.namespacedSchemas[s]=a;return e}var gLs=ve($gr(),1),Hgr={config:new gLs.Config({apis:{},styleguide:{plugins:[MEi],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function _G({options:e,overrides:t}={}){return{...Y4({options:e,overrides:t}),...JDe({options:e,overrides:t})}}var Vep={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",inferDefaultEnvironment:"inferDefaultEnvironment",wrapReferencesToNullableInOptional:"wrapReferencesToNullableInOptional",coerceOptionalSchemasToNullable:"coerceOptionalSchemasToNullable",removeDiscriminantsFromSchemas:"removeDiscriminantsFromSchemas",defaultIntegerFormat:"defaultIntegerFormat",pathParameterOrder:"pathParameterOrder",resolveSchemaCollisions:"resolveSchemaCollisions",inferForwardCompatible:"inferForwardCompatible",coerceConstsTo:"coerceConstsTo"};function qep(e,t,r){r!==void 0&&(e[t]=r)}function Kgr(e){let t={};if(e!=null)for(let[r,n]of Object.entries(Vep)){let i=e[r],o=Array.isArray(n)?n:[n];for(let s of o)qep(t,s,i)}return _G({options:t})}function U7e(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 xM(e){return e.swagger!=null}function $_i(e){return e.openapi!=null}Tt();kA();Ni();function rye(e,t={}){return{...Object.fromEntries(xb(e.namedDefinitionFiles).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...xb(e.importedDefinitions).reduce((r,[n,i])=>({...r,...BIt(rye(i.definition,{defaultURL:i.url}),(o,s)=>_E(n,Hs.of(s)))}),{})}}Tt();kA();Ni();function OSt(e,t={}){return{...Object.fromEntries(xb(e.packageMarkers).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...xb(e.importedDefinitions).reduce((r,[n,i])=>({...r,...BIt(OSt(i.definition,{defaultURL:i.url}),(o,s)=>_E(n,Hs.of(s)))}),{})}}function Gce(e){return{...OSt(e),...rye(e)}}function fz(e,t){return Gce(e.definition)[t]?.contents}Tt();kA();function Pv(e,t){for(let[r,n]of xb(Gce(e.definition)))t(r,n.contents,{isPackageMarker:TT(r)===vf,defaultUrl:n.defaultUrl})}Tt();function aFe(e,t){for(let[r,n]of xb(OSt(e.definition)))t(r,n.contents)}Tt();var ALs=ve(require("path"),1);async function Jgr({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 c=a.path.length>0?`${a.message} at "${Gep(a.path)}"`:a.message;return n4({content:c,prefix:" - "})}),s=[`Failed to parse file: ${ALs.default.relative(process.cwd(),n)}`,...o].join(`
1500
1500
  `);return r.failAndThrow(s)}function Gep(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}$t();var Jm=class e extends Error{constructor(){super(),Object.setPrototypeOf(this,e.prototype)}};var SG=class e extends Error{log;constructor(t){super(),this.log=t,Object.setPrototypeOf(this,e.prototype)}};var ei={Trace:"trace",Debug:"debug",Info:"info",Warn:"warn",Error:"error"},$1=Object.values(ei);var H_i=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(ei.Debug,...t)}info(...t){this.enabled&&this.log(ei.Info,...t)}warn(...t){this.enabled&&this.log(ei.Warn,...t)}error(...t){this.enabled&&this.log(ei.Error,...t)}trace(...t){this.enabled&&this.log(ei.Trace,...t)}};function H1(e){return new H_i(e)}var K_i=Object.freeze(H1(Wep));function Wep(e,...t){$ep(e)(...t)}function $ep(e){switch(e){case ei.Trace:return console.trace;case ei.Debug:return console.debug;case ei.Info:return console.info;case ei.Warn:return console.warn;case ei.Error:return console.error}}var If;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(If||(If={}));function TSt({logger:e=K_i}={}){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 Jm},failWithoutThrowing:(r,n)=>{t.failAndThrow(r,n)},getResult:()=>If.Success,addInteractiveTask:()=>{throw new Error("Not implemented")},runInteractiveTask:()=>{throw new Error("Not implemented")},instrumentPostHogEvent:()=>{throw new Error("Not implemented")}};return t}var yLs=ve(require("path"),1),Hep={dependencies:{}};async function bLs({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return Hep;let n={};for(let[i,o]of Object.entries(t.dependencies))if(Jep(o)){let s=Gt.of(yLs.default.join(e,o));await sr(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("/"),c=a[0],u=a[1];c!=null&&u!=null?n[i]={type:"version",organization:c,apiName:u,version:o}:r.failWithoutThrowing(`Failed to parse dependency: ${i}`)}return r.getResult()===If.Failure&&r.failAndThrow(),{dependencies:n}}var Kep=/^\.\.\/.*$/;function Jep(e){return Kep.test(e)}$t();var vLs=require("fs/promises");var ELs=yt.object({dependencies:yt.record(yt.string(),yt.string())});async function ILs({absolutePathToWorkspace:e,context:t}){let r=Ye(e,Be.of(_Es));if(!await sr(r))return;let n=await(0,vLs.readFile)(r),i=Tr.load(n.toString());return await Jgr({schema:ELs,value:i,context:t,filepathBeingParsed:r})}async function J_i({absolutePathToWorkspace:e,context:t}){let r=await ILs({absolutePathToWorkspace:e,context:t});return bLs({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}Tt();Zgr();function PLs(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=tAr(e);switch(r){case"dark":return{type:"dark",...eAr(e,t,"dark")};case"light":return{type:"light",...eAr(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:eAr(e,t,"dark"),light:eAr(e,t,"light")};default:we(r)}}function tAr({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return is(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return is(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return is(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 eAr(e,t,r){let n=m_(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??is.random(),i=m_(e.background,t,"background",r);return{accentPrimary:n.toRgb(),background:i?.toRgb(),border:m_(e.border,t,"border",r)?.toRgb(),sidebarBackground:m_(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:m_(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:m_(e.cardBackground,t,"card-background",r)?.toRgb(),accent1:m_(e.accent1,t,"accent-1",r)?.toRgb(),accent2:m_(e.accent2,t,"accent-2",r)?.toRgb(),accent3:m_(e.accent3,t,"accent-3",r)?.toRgb(),accent4:m_(e.accent4,t,"accent-4",r)?.toRgb(),accent5:m_(e.accent5,t,"accent-5",r)?.toRgb(),accent6:m_(e.accent6,t,"accent-6",r)?.toRgb(),accent7:m_(e.accent7,t,"accent-7",r)?.toRgb(),accent8:m_(e.accent8,t,"accent-8",r)?.toRgb(),accent9:m_(e.accent9,t,"accent-9",r)?.toRgb(),accent10:m_(e.accent10,t,"accent-10",r)?.toRgb(),accent11:m_(e.accent11,t,"accent-11",r)?.toRgb(),accent12:m_(e.accent12,t,"accent-12",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function PSt(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 m_(e,t,r,n){let i=PSt(e,r,n);if(i==null)return;let o=is(i);return o.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${n}`}' should be a hex color of the format #FFFFFF`),o}Tt();$t();var RLs=require("fs/promises");Ni();var DLs=100;async function vtp({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async n=>{let i=await(0,RLs.readFile)(n,"utf-8");return[w0(t,n),i]}));return Object.fromEntries(r)}async function FLs({files:e,absolutePathToFernFolder:t}){let r={};for(let n=0;n<e.length;n+=DLs){let i=e.slice(n,n+DLs),o=await vtp({files:i,absolutePathToFernFolder:t});Object.assign(r,o)}return r}function cFe({landingPage:e,navigation:t}){return i4([e?.absolutePath,...Itp(t)])}function Itp(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>rAr({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(n=>rAr({item:n}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>rAr({item:t}));case"versioned":return e.versions.flatMap(t=>cFe({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:cFe({landingPage:t.landingPage,navigation:t.navigation}));default:we(e)}}function rAr({item:e}){switch(e.type){case"apiSection":return i4([e.overviewAbsolutePath,...e.navigation.flatMap(t=>kLs({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return i4([e.overviewAbsolutePath,...e.contents.flatMap(t=>rAr({item:t}))]);case"changelog":return e.changelog;case"librarySection":return[];default:we(e)}}function kLs({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?i4([e.overviewAbsolutePath,...e.contents.flatMap(t=>kLs({item:t}))]):[]}Tt();sg();$t();var JTt=require("fs/promises");var Tha=ve(require("path"),1);$t();var Aki=require("fs/promises"),Sha=ve(b9(),1);function kEr({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function yki({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function NEr({absolutePath:e,readFileFn:t=(r,n)=>(0,Aki.readFile)(r,n)}){try{let r=await t(e,"utf-8"),{data:n}=(0,Sha.default)(r),i;if(n.position!=null){let c=typeof n.position=="string"?parseFloat(n.position):n.position;typeof c=="number"&&Number.isFinite(c)&&(i=c)}let o=typeof n.title=="string"&&n.title.trim().length>0?n.title.trim():void 0,s=n.hidden===!0?!0:void 0,a=n.noindex===!0?!0:void 0;return{position:i,title:o,hidden:s,noindex:a}}catch{return{position:void 0,title:void 0,hidden:void 0,noindex:void 0}}}function _ha({frontmatterTitle:e,useFrontmatterTitles:t,fallbackName:r}){return t&&e!=null?e:yki({name:r})}async function bki({directoryPath:e,titleSource:t,getDir:r=Sb,readFileFn:n=(i,o)=>(0,Aki.readFile)(i,o)}){let i=await r(e),o=t==="frontmatter",s=i.filter(d=>d.type==="file"&&!d.name.startsWith("_")&&(d.name.toLowerCase().endsWith(".md")||d.name.toLowerCase().endsWith(".mdx"))),a=i.filter(d=>d.type==="directory"&&!d.name.startsWith("_")),c=await Promise.all(s.map(d=>NEr({absolutePath:d.absolutePath,readFileFn:n}))),u=s.map((d,f)=>{let m=c[f];return{type:"page",title:_ha({frontmatterTitle:m?.title,useFrontmatterTitles:o,fallbackName:d.name}),absolutePath:d.absolutePath,slug:kEr({name:d.name}),icon:void 0,hidden:m?.hidden,noindex:m?.noindex,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0}}),l=await Promise.all(a.map(async d=>{let f=await bki({directoryPath:d.absolutePath,titleSource:t,getDir:r,readFileFn:n}),m=f.find(b=>b.type==="page"&&(b.slug==="index"||b.absolutePath.toLowerCase().endsWith("/index.mdx")||b.absolutePath.toLowerCase().endsWith("/index.md"))),h=m?f.filter(b=>b!==m):f,g=m?.type==="page"?await NEr({absolutePath:m.absolutePath,readFileFn:n}):void 0;return{section:{type:"section",title:_ha({frontmatterTitle:g?.title,useFrontmatterTitles:o,fallbackName:d.name}),slug:kEr({name:d.name}),icon:void 0,contents:h,collapsed:void 0,collapsible:void 0,collapsedByDefault:void 0,hidden:g?.hidden,skipUrlSlug:!1,overviewAbsolutePath:m?.type==="page"?m.absolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0},position:g?.position}})),p=[...u.map((d,f)=>({item:d,title:d.type==="page"?d.title:"",position:c[f]?.position})),...l.map(d=>({item:d.section,title:d.section.type==="section"?d.section.title:"",position:d.position}))];return p.sort((d,f)=>{let m=typeof d.position=="number",h=typeof f.position=="number";if(m&&!h)return-1;if(!m&&h)return 1;if(typeof d.position=="number"&&typeof f.position=="number"){let g=d.position-f.position;return g!==0?g:d.title.localeCompare(f.title,void 0,{sensitivity:"base"})}return d.title.localeCompare(f.title,void 0,{sensitivity:"base"})}),p.map(d=>d.item)}function WJp(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function Qb(e,t){if(e)return WJp(e)?Mb(e,t):e}async function YTt({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:n}){let{instances:i,title:o,tabs:s,products:a,versions:c,navigation:u,navbarLinks:l,footerLinks:p,defaultLanguage:d,metadata:f,redirects:m,logo:h,favicon:g,backgroundImage:A,colors:b,typography:v,layout:E,integrations:I,css:w,js:x,aiChat:C,aiSearch:_,agents:R,pageActions:G,experimental:V}=e,z=XTt(e.landingPage,r),K=e.settings?.folderTitleSource,ie=sYp({tabs:s,products:a,versions:c,navigation:u,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:K}),q=ie.then(ke=>FLs({files:cFe({navigation:ke,landingPage:z}),absolutePathToFernFolder:t})),H=$Jp(h,r),ye=Mb(g,r),Ee=HJp(A,r),Z=v!=null?aYp({rawTypography:v,absoluteFilepathToDocsConfig:r}):void 0,te=KJp(w,r),be=XJp(x,r),Ae=BYp(f,r),Te=iYp({rawPath:e.integrations?.context7,absoluteFilepathToDocsConfig:r,context:n}),[Se,pe,le,Fe,$e,kt,Ke]=await Promise.all([ie,q,Z,te,be,Ae,Te]),Le=rYp(e.theme),Xe=Le?.tabs!=null&&typeof Le.tabs=="object"?Le.tabs:void 0,Wt=Xe?.placement??E?.tabsPlacement??"sidebar",Ie=Xe?.alignment??"left";return Wt==="sidebar"&&Ie==="center"&&n.logger.warn("Tabs alignment 'center' is not supported when tabs placement is 'sidebar'. The alignment will be ignored."),{title:o,instances:i,roles:e.roles,libraries:EYp(e.libraries),pages:pe,landingPage:z,navigation:Se,navbarLinks:OYp(l,r),footerLinks:TYp(p),defaultLanguage:d,languages:e.languages,announcement:e.announcement,metadata:kt,redirects:m?.map(ke=>({...ke,permanent:ke?.permanent})),logo:H,favicon:ye,backgroundImage:Ee,colors:PLs(b,n),typography:le,layout:oYp(E,Xe?.alignment,Xe?.placement),settings:nYp(e.settings),context7File:Ke,theme:Le,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:Fe,js:$e,aiChatConfig:_??C,agents:R,pageActions:ZJp(G,r),header:Mb(e.header,r),footer:Mb(e.footer,r),experimental:V}}function $Jp(e,t){return e!=null?{dark:Mb(e.dark,t),light:Mb(e.light,t),height:e.height,href:e.href!=null?Pr.Url(e.href):void 0,rightText:e.rightText}:void 0}function HJp(e,t){if(e!=null)if(typeof e=="string"){let r=Mb(e,t);return{dark:r,light:r}}else{let r=Mb(e.dark,t),n=Mb(e.light,t);return{dark:r,light:n}}}async function KJp(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async n=>(await(0,JTt.readFile)(Mb(n,t))).toString()))}}function JJp(e){return Object.hasOwn(e,"url")}function YJp(e){return Object.hasOwn(e,"path")}async function XJp(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:Mb(o,t)}):JJp(o)?r.push({strategy:o.strategy,url:Pr.Url(o.url)}):YJp(o)&&n.push({absolutePath:Mb(o.path,t),strategy:o.strategy});return{remote:r,files:n}}function ZJp(e,t){return e==null?void 0:{default:e.default!=null?eYp(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=>tYp(n,t))}}}function eYp(e){switch(e){case"copy-page":return Pr.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return Pr.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return Pr.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return Pr.docs.v1.commons.PageActionOption.OpenAi;case"claude":return Pr.docs.v1.commons.PageActionOption.Claude;case"cursor":return Pr.docs.v1.commons.PageActionOption.Cursor;case"vscode":return Pr.docs.v1.commons.PageActionOption.Vscode;default:we(e)}}function tYp(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:Qb(e.icon,t),default:e.default}}function rYp(e){if(e==null)return;let t;if(e.tabs!=null&&typeof e.tabs=="object"){let r=e.tabs;t={style:r.style??"default",alignment:r.alignment,placement:r.placement}}else t=e.tabs??"default";return{sidebar:e.sidebar??"default",tabs:t,body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function nYp(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}}async function iYp({rawPath:e,absoluteFilepathToDocsConfig:t,context:r}){if(e==null)return;let n=Mb(e,t),i=await(0,JTt.readFile)(n,"utf8");try{JSON.parse(i)}catch(o){r.failAndThrow(`Invalid JSON in Context7 config file: ${e}`,o instanceof Error?o.message:String(o))}return n}function oYp(e,t,r){if(e==null&&t==null&&r==null)return;let n=t==="center"?"CENTER":"LEFT",i=r==="header"?Pr.docs.v1.commons.TabsPlacement.Header:r==="sidebar"?Pr.docs.v1.commons.TabsPlacement.Sidebar:void 0;return e==null?{...i!=null?{tabsPlacement:i}:{},tabsAlignment:n}:{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:jEr(e.pageWidth),contentWidth:jEr(e.contentWidth),sidebarWidth:jEr(e.sidebarWidth),headerHeight:jEr(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?Pr.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?Pr.docs.v1.commons.SearchbarPlacement.HeaderTabs:Pr.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?Pr.docs.v1.commons.SwitcherPlacement.Header:Pr.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:i??(e.tabsPlacement==="header"?Pr.docs.v1.commons.TabsPlacement.Header:Pr.docs.v1.commons.TabsPlacement.Sidebar),contentAlignment:e.contentAlignment==="left"?Pr.docs.v1.commons.ContentAlignment.Left:Pr.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?Pr.docs.v1.commons.HeaderPosition.Absolute:Pr.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1,tabsAlignment:n}}function jEr(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 Oha({versions:e,absolutePathToFernFolder:t,context:r,folderTitleSource:n}){let i=[];for(let o of e){let s=fo(t,o.path),a=Tr.load((await(0,JTt.readFile)(s)).toString()),c=[],u=nM(a,[],c);c.length>0&&r.logger.warn(`Version file ${o.path} contained null/undefined sections that were ignored: ${c.map(d=>d.join(".")).join(", ")}`);let l=t_.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(u),p=await Iki({tabs:l.tabs,rawNavigationConfig:l.navigation,absolutePathToFernFolder:t,absolutePathToConfig:s,context:r,folderTitleSource:n});i.push({landingPage:XTt(l.landingPage,s),version:o.displayName,navigation:p,availability:o.availability,slug:o.slug,hidden:o.hidden,viewers:x_(o.viewers),orphaned:o.orphaned,featureFlags:C_(o.featureFlag),announcement:o.announcement})}return{type:"versioned",versions:i}}async function sYp({tabs:e,products:t,versions:r,navigation:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:s,folderTitleSource:a}){if(n!=null)return await Iki({tabs:e,rawNavigationConfig:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:s,folderTitleSource:a});if(t!=null){let c=[];for(let u of t){let l=u.image!=null?fo(i,u.image):void 0;if("path"in u){let p,d=fo(i,u.path),f=Tr.load((await(0,JTt.readFile)(d)).toString()),m=[],h=nM(f,[],m);m.length>0&&s.logger.warn(`Product file ${u.path} contained null/undefined sections that were ignored: ${m.map(A=>A.join(".")).join(", ")}`);let g=t_.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);u.versions!=null&&u.versions.length>0?p=await Oha({versions:u.versions,absolutePathToFernFolder:i,context:s,folderTitleSource:a}):p=await Iki({tabs:g.tabs,rawNavigationConfig:g.navigation,absolutePathToFernFolder:i,absolutePathToConfig:d,context:s,folderTitleSource:a}),c.push({type:"internal",landingPage:XTt(g.landingPage,d),product:u.displayName,navigation:p,slug:u.slug,subtitle:u.subtitle,icon:Qb(u.icon,o)||"fa-solid fa-code",image:l,viewers:x_(u.viewers),orphaned:u.orphaned,featureFlags:C_(u.featureFlag),announcement:u.announcement})}else if("href"in u&&u.href!=null)c.push({type:"external",product:u.displayName,href:u.href,target:u.target,subtitle:u.subtitle,icon:Qb(u.icon,o)||"fa-solid fa-code",image:l,viewers:x_(u.viewers),orphaned:u.orphaned,featureFlags:C_(u.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await Oha({versions:r,absolutePathToFernFolder:i,context:s,folderTitleSource:a});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function C_(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 aYp({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await Eki({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await Eki({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await Eki({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function Eki({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await cYp(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function cYp(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:Mb(n.path,t),weight:uYp(n.weight),style:n.style})))}function uYp(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 lYp({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(SYp(t)){let a=await Promise.all(t.variants.map(async c=>{let u=await Promise.all(c.layout.map(l=>LEr({rawConfig:l,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:c.title,subtitle:c.subtitle,icon:Qb(c.icon,n),layout:u,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:x_(c.viewers),orphaned:c.orphaned,featureFlags:C_(c.featureFlag)}}));return{title:s.displayName,icon:Qb(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"variants",variants:a},viewers:x_(s.viewers),orphaned:s.orphaned,featureFlags:C_(s.featureFlag)}}if(_Yp(t)){let a=await Promise.all(t.layout.map(c=>LEr({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:s.displayName,icon:Qb(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"layout",layout:a},viewers:x_(s.viewers),orphaned:s.orphaned,featureFlags:C_(s.featureFlag)}}if(s.href!=null)return{title:s.displayName,icon:Qb(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"link",href:s.href,target:s.target},viewers:x_(s.viewers),orphaned:s.orphaned,featureFlags:C_(s.featureFlag)};if(s.changelog!=null)return{title:s.displayName,icon:Qb(s.icon,n),slug:s.slug,skipUrlSlug:s.skipSlug,hidden:s.hidden,child:{type:"changelog",changelog:await Nx(Mb(s.changelog,n),"{md,mdx}")},viewers:x_(s.viewers),orphaned:s.orphaned,featureFlags:C_(s.featureFlag)};we(s)}async function Iki({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o}){return xYp(t)?{type:"tabbed",items:await Promise.all(t.map(a=>lYp({tabs:e,item:a,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}:{type:"untabbed",items:await Promise.all(t.map(s=>LEr({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}}var pYp="Changelog";async function fYp({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){let o=Mb(e.folder,r);await sr(o)||n.failAndThrow(`Folder not found: ${e.folder}`),wki({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 bki({directoryPath:o,titleSource:s}),c=a.find(m=>m.type==="page"&&(m.slug==="index"||m.absolutePath.toLowerCase().endsWith("/index.mdx")||m.absolutePath.toLowerCase().endsWith("/index.md"))),u=c?a.filter(m=>m!==c):a,l=Tha.default.basename(o),p=s==="frontmatter"&&c?.type==="page"?(await NEr({absolutePath:c.absolutePath})).title:void 0,d=e.title??p??yki({name:l}),f=e.slug??kEr({name:l});return{type:"section",title:d,icon:Qb(e.icon,r),contents:u,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:c?.type==="page"?c.absolutePath:void 0,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag),availability:e.availability}}async function LEr({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){if(Bha(e))return XTt(e,r);if(mYp(e))return wki({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:Qb(e.icon,r),contents:await Promise.all(e.contents.map(o=>LEr({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:Mb(e.path,r),viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag),availability:e.availability};if(hYp(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:Qb(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:ZTt(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?dYp({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(o=>MEr(o,r,n))??[],overviewAbsolutePath:Mb(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:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)};if(Pha(e))return{type:"link",text:e.link,url:e.href,icon:Qb(e.icon,r),target:e.target};if(gYp(e))return{type:"changelog",changelog:await Nx(Mb(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:Qb(e.icon,r),title:e.title??pYp,slug:e.slug,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)};if(AYp(e))return await fYp({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i});if(yYp(e))return{type:"librarySection",libraryName:e.library,title:e.title??void 0,slug:e.slug??void 0,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)};we(e)}function XTt(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Mb(e.path,t),slug:e.slug,icon:Qb(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag),availability:e.availability}}function MEr(e,t,r){return typeof e=="string"?[{type:"item",value:e}]:Bha(e)?[XTt(e,t)]:Pha(e)?[{type:"link",text:e.link,url:e.href,icon:Qb(e.icon,t),target:e.target}]:vYp(e)?(r!=null&&wki({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:Mb(e.summary,t),contents:e.contents?.flatMap(n=>MEr(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:Qb(e.icon,t),playground:e.playground,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)}]):IYp(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:Qb(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)}]:wYp(e)?[{type:"operation",operation:e.operation,title:e.title,slug:e.slug,hidden:e.hidden,availability:e.availability,viewers:x_(e.viewers),orphaned:e.orphaned,featureFlags:C_(e.featureFlag)}]:Object.entries(e).map(([n,i])=>CYp(i)?{type:"package",title:i.title,package:n,overviewAbsolutePath:Mb(i.summary,t),contents:i.contents?.flatMap(o=>MEr(o,t,r))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:Qb(i.icon,t),playground:i.playground,availability:i.availability,viewers:x_(i.viewers),orphaned:i.orphaned,featureFlags:C_(i.featureFlag)}:{type:"package",title:void 0,package:n,overviewAbsolutePath:void 0,contents:i.flatMap(o=>MEr(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 dYp({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 Bha(e){return Ma(e)&&typeof e.page=="string"&&typeof e.path=="string"}function mYp(e){return e.section!=null}function hYp(e){return e.api!=null}function Pha(e){return t_.RawSchemas,Ma(e)&&typeof e.link=="string"&&typeof e.href=="string"}function gYp(e){return Ma(e)&&typeof e.changelog=="string"}function AYp(e){return Ma(e)&&typeof e.folder=="string"}function yYp(e){return Ma(e)&&typeof e.library=="string"}function bYp(e){return"git"in e}function EYp(e){if(e==null)return;let t={};for(let[r,n]of Object.entries(e)){if(!bYp(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 vYp(e){return Ma(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function IYp(e){return Ma(e)&&typeof e.endpoint=="string"}function wYp(e){return Ma(e)&&typeof e.operation=="string"}function CYp(e){return!Array.isArray(e)}function Mb(e,t){if(e!=null)return fo(Bn(t),e)}function xYp(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function _Yp(e){return"layout"in e&&Array.isArray(e.layout)}function SYp(e){return"variants"in e&&Array.isArray(e.variants)}function OYp(e,t){return e?.map(r=>{if(r.type==="github"){let i=r.value;return typeof i=="string"?{type:"github",url:Pr.Url(i),viewers:void 0,target:void 0}:{type:"github",url:Pr.Url(i.url),viewers:vki(i.viewers),target:i.target}}let n=vki(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:Qb(r.icon,t),rightIcon:Qb(r.rightIcon,t),rounded:r.rounded,viewers:n,links:r.links?.map(i=>({href:i.href,target:i.target,url:Pr.Url(i.url??i.href??"/"),text:i.text,icon:Qb(i.icon,t),rightIcon:Qb(i.rightIcon,t),rounded:i.rounded,viewers:vki(i.viewers)}))??[]}:{type:r.type,text:r.text,url:Pr.Url(r.href??r.url??"/"),target:r.target,icon:Qb(r.icon,t),rightIcon:Qb(r.rightIcon,t),rounded:r.rounded,viewers:n}})}function vki(e){if(e!=null)return Array.isArray(e)?e.map(t=>Pr.RoleId(t)):[Pr.RoleId(e)]}function TYp(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let n=e[r];n!=null&&t.push({type:r,value:Pr.Url(n)})}),t.length!==0)return t}async function BYp(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 QEr(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await QEr(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await QEr(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 QEr(e.ogBackgroundImage,t),nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function QEr(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Mb(e,t);return await sr(r)?{type:"filepath",value:r}:{type:"url",value:e}}function x_(e){if(e!=null){if(typeof e=="string")return[Pr.RoleId(e)];if(e.length!==0)return e.map(Pr.RoleId)}}function ZTt(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}function wki({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.`)}$t();var Rha=require("fs/promises");var Dha=yt.strictObject({organization:yt.string(),version:yt.string()});async function FM({directory:e,context:t}){let r=Ye(e,Be.of(BE)),n=await(0,Rha.readFile)(r),i=JSON.parse(n.toString()),o=await Jgr({schema:Dha,value:i,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:o,organization:o.organization,version:o.version}}var rt={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 zji=ve(b1(),1);var eBt={[rt.JAVA]:{version:"2.38.1"},[rt.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[rt.JAVA_MODEL]:{version:"1.0.0"},[rt.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[rt.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[rt.TYPESCRIPT]:{version:"0.0.247"},[rt.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[rt.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[rt.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[rt.PYTHON_PYDANTIC]:{version:"1.4.7"},[rt.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[rt.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[rt.GO_MODEL]:{version:"0.23.5"},[rt.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[rt.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[rt.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[rt.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[rt.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[rt.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[rt.CSHARP_MODEL]:{version:"0.0.1"},[rt.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[rt.SWIFT_MODEL]:{version:"0.0.0"},[rt.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[rt.PHP_MODEL]:{version:"0.0.0"},[rt.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[rt.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[rt.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var tBt="fernapi",tNe="fern-api";function D0(e){return e=M$e(e),e.includes("/")?e:`${tBt}/${e}`}function M$e(e){let t=`${tNe}/`;return e.startsWith(t)?`${tBt}/${e.slice(t.length)}`:e}function UEr(e,t){let r=`${tNe}/`;if(e.startsWith(r)){let n=`${tBt}/${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 rNe(e){let t=`${tBt}/`;return e.startsWith(t)?e.slice(t.length):e}function Cki(e,t){let r=nNe(e);return r??t.failAndThrow("Unrecognized generator: "+e)}var PYp={"fernapi/java-model":rt.JAVA_MODEL,"fernapi/fern-typescript-node-sdk":rt.TYPESCRIPT_SDK};function nNe(e){e=D0(e);let t=PYp[e];if(t!=null&&(e=t),DYp(e))return e}function DYp(e){return Object.values(rt).includes(e)}var SIr=ve(vHe(),1),Qva=ve(b1(),1);async function yB({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:n,includeMajor:i,context:o}){let s=Qva.default.parse(n),a="https://registry.buildwithfern.com",c=new SIr.FernRegistryClient({environment:a});o?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${i}, prior version: ${s}, FDR origin: ${a}`);let u={generator:apf(e,o),releaseTypes:[r??SIr.FernRegistry.generators.ReleaseType.Ga],cliVersion:t};!i&&s!=null&&(u.generatorMajorVersion=s.major),o?.logger.debug(`[FDR] getLatestGeneratorRelease request: ${JSON.stringify(u)}`);let l=await c.generators.versions.getLatestGeneratorRelease(u);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 apf(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 Mva({generatorsConfiguration:e,groupName:t=e[Dn.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:n}){if(t==null){let s=Object.keys(e.groups??{});if(s.length>0){let a=`No group specified. Use the --group option:
1501
1501
  `+s.map(c=>` \u203A ${c}`).join(`
@@ -1657,7 +1657,7 @@ ${_Ya.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&zWi(th
1657
1657
  `+P2e.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?P2e.default.cyan(kYa(t,this.opt.mask)):P2e.default.italic(P2e.default.dim("[hidden]")):this.opt.mask?kYa(t,this.opt.mask):P2e.default.italic(P2e.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 Vkr=ve(YC(),1);var FXa=ve(w$i(),1),Ukr=require("child_process"),BXe=require("fs"),Lkr=ve(require("path"),1),kXa=ve(require("os"),1),NXa=require("crypto"),aHi=ve(DXa(),1);var jkr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var gNt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var Qkr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var Mkr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function zkr(e="",t,r){let n=new cHi(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 RXa(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function bhd(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 cHi=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=bhd(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??kXa.default.tmpdir(),r=(0,NXa.randomUUID)(),n=RXa(this.fileOptions.prefix),i=RXa(this.fileOptions.postfix),o=`${n}${r}${i}`,s=Lkr.default.resolve(t,o),a=Lkr.default.resolve(t)+Lkr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,BXe.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new jkr(t)}}readTemporaryFile(){try{let t=(0,BXe.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,FXa.detect)(t)??"utf8";aHi.default.encodingExists(r)||(r="utf8"),this.text=aHi.default.decode(t,r)}}catch(t){throw new Qkr(t)}}removeTemporaryFile(){try{(0,BXe.unlinkSync)(this.tempFile)}catch(t){throw new Mkr(t)}}launchEditor(){try{let t=(0,Ukr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new gNt(t)}}launchEditorAsync(t){try{(0,Ukr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new gNt(r)}}};var jXa=ve(lL(),1);var ANt=class extends XC{_run(t){this.done=t,this.editorResult=new jXa.Subject;let r=TO(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"?Vkr.default.dim("Received"):Vkr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=Vkr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),zkr(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 zXa=require("stream");var LXa=ve(require("readline"),1),UXa=ve(MXa(),1),k2e=class{constructor(t){this.rl||=LXa.default.createInterface(vhd(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 vhd(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 UXa.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var yNt=class extends k2e{constructor(t={}){super(t),this.log=new zXa.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return tNt(this.rl,this.bottomBar.split(`
1658
1658
  `).length),this}updateBottomBar(t){return tNt(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+`
1659
1659
  `}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&&pkr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var gd=ve(lL(),1),GXa=ve(Dkt(),1);var qkr=ve(lL(),1),VXa=ve(Dkt(),1),Gkr=function(e,t,r){return typeof e[t]!="function"?(0,qkr.of)(e):(0,qkr.from)((0,VXa.default)(e[t])(r).then(n=>(e[t]=n,e)))};var qXa={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}},PXe=class extends k2e{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,gd.from)(t):(0,gd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,gd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,gd.from)([t]),this.process=n.pipe((0,gd.concatMap)(this.processQuestion.bind(this)),(0,gd.publish)()),this.process.connect(),this.process.pipe((0,gd.reduce)((i,o)=>(qXa.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,gd.defer)(()=>(0,gd.of)(t).pipe((0,gd.concatMap)(this.setDefaultType.bind(this)),(0,gd.concatMap)(this.filterIfRunnable.bind(this)),(0,gd.concatMap)(()=>Gkr(t,"message",this.answers)),(0,gd.concatMap)(()=>Gkr(t,"default",this.answers)),(0,gd.concatMap)(()=>Gkr(t,"choices",this.answers)),(0,gd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,gd.defer)(()=>(0,gd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,gd.defer)(()=>(0,gd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&qXa.get(this.answers,t.name)!==void 0)return gd.EMPTY;if(t.when===!1)return gd.EMPTY;if(typeof t.when!="function")return(0,gd.of)(t);let{answers:r}=this;return(0,gd.defer)(()=>(0,gd.from)((0,GXa.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,gd.filter)(n=>n!=null)))}};function WXa(e){let t=function(r,n){let i;try{i=new PXe(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",nNt),this.registerPrompt("input",B2e),this.registerPrompt("number",iNt),this.registerPrompt("confirm",oNt),this.registerPrompt("rawlist",sNt),this.registerPrompt("expand",aNt),this.registerPrompt("checkbox",cNt),this.registerPrompt("password",uNt),this.registerPrompt("editor",ANt)},t.restoreDefaultPrompts(),t}var lHi=WXa();function whd(e,t){lHi.registerPrompt(e,t)}function Chd(){lHi.restoreDefaultPrompts()}var xhd={prompt:lHi,ui:{BottomBar:yNt,Prompt:PXe},createPromptModule:WXa,registerPrompt:whd,restoreDefaultPrompts:Chd,Separator:vj},Zp=xhd;var DXe=require("path");function HXa(){let e=_hd();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function _hd(e=process.argv[1]?(0,DXe.dirname)(process.argv[1]):process.cwd(),t=DXe.sep==="\\"){let r=t?$Xa(e):e;return n=>{if(!n)return;let i=t?$Xa(n):n,{dir:o,base:s,ext:a}=DXe.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function $Xa(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var pHi=e=>{if("flags"in e){let t=KXa(e.flags),r=JXa(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,fHi(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Shd(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Shd(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 KXa=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,bNt(r)]).filter(([,t])=>t!==void 0)),JXa=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?fHi(n):void 0]}))};var bNt=e=>e===void 0?void 0:e.variant??e.enabled,fHi=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Wkr="0123456789abcdef",$kr=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+=Wkr.charAt(this.bytes[r]>>>4),t+=Wkr.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+=Wkr.charAt(this.bytes[r]>>>4),t+=Wkr.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}},dHi=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Ohd()}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 $kr.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,$kr.ofInner(t)}},Ohd=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),YXa,CEe=()=>Thd().toString(),Thd=()=>(YXa||(YXa=new dHi)).generate();var wj=(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 Bhd=["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"],XXa=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return Bhd.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var Dhd=Array.isArray,ZXa=Object.prototype,Kr0=ZXa.hasOwnProperty,mHi=ZXa.toString,hHi=Dhd||function(e){return mHi.call(e)==="[object Array]"};var gHi=e=>e===Object(e)&&!hHi(e);var RXe=e=>e===void 0,ENt=e=>mHi.call(e)=="[object String]",eZa=e=>ENt(e)&&e.trim().length===0;var tZa=e=>mHi.call(e)=="[object Number]"&&e===e;var AHi=e=>e instanceof Error;function Hkr(e){return e===null||typeof e!="object"}function N2e(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function rZa(e){return N2e(e,"ErrorEvent")}function FXe(e){return!RXe(Event)&&Rhd(e,Event)}function nZa(e){return N2e(e,"Object")}function Rhd(e,t){try{return e instanceof t}catch{return!1}}function vNt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),tZa(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),vNt(i||r,t,r,n))}var Fhd=864e5,Kkr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=vNt(t.bucketSize,0,100,t._logger),this._refillRate=vNt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=vNt(t.refillInterval,0,Fhd,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 Jkr=class{add(t){let r=CEe();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 khd(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var iZa=(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=>iZa(`${e} ${o}`,t,r)}},Nhd=e=>e();function oZa(e,t=Nhd){return iZa(e,t,khd())}var NXe="Mobile",Xkr="iOS",kXe="Android",sZa="Tablet",an0=kXe+" "+sZa;var jhd="Apple",cn0=jhd+" Watch",aZa="Safari",Zkr="BlackBerry",cZa="Samsung",Qhd=cZa+"Browser",Mhd=cZa+" Internet",eNr="Chrome",Lhd=eNr+" OS",Uhd=eNr+" "+Xkr,uZa="Internet Explorer",zhd=uZa+" "+NXe,bHi="Opera",un0=bHi+" Mini",lZa="Edge",Vhd="Microsoft "+lZa,EHi="Firefox",qhd=EHi+" "+Xkr,vHi="Nintendo",IHi="PlayStation",Ykr="Xbox",Ghd=kXe+" "+NXe,Whd=NXe+" "+aZa,INt="Windows",$hd=INt+" Phone";var pZa="Generic",ln0=pZa+" "+NXe.toLowerCase(),pn0=pZa+" "+sZa.toLowerCase(),Hhd="Konqueror",wR="(\\d+(\\.\\d+)?)",yHi=new RegExp("Version/"+wR),fn0=new RegExp(Ykr,"i"),dn0=new RegExp(IHi+" \\w+","i"),mn0=new RegExp(vHi+" \\w+","i"),Khd=new RegExp(Zkr+"|PlayBook|BB10","i"),Jhd={"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 hn0={[zhd]:[new RegExp("rv:"+wR)],[Vhd]:[new RegExp(lZa+"?\\/"+wR)],[eNr]:[new RegExp("("+eNr+"|CrMo)\\/"+wR)],[Uhd]:[new RegExp("CriOS\\/"+wR)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+wR)],[aZa]:[yHi],[Whd]:[yHi],[bHi]:[new RegExp("("+bHi+"|OPR)\\/"+wR)],[EHi]:[new RegExp(EHi+"\\/"+wR)],[qhd]:[new RegExp("FxiOS\\/"+wR)],[Hhd]:[new RegExp("Konqueror[:/]?"+wR,"i")],[Zkr]:[new RegExp(Zkr+" "+wR),yHi],[Ghd]:[new RegExp("android\\s"+wR,"i")],[Mhd]:[new RegExp(Qhd+"\\/"+wR)],[uZa]:[new RegExp("(rv:|MSIE )"+wR)],Mozilla:[new RegExp("rv:"+wR)]};var gn0=[[new RegExp(Ykr+"; "+Ykr+" (.*?)[);]","i"),e=>[Ykr,e&&e[1]||""]],[new RegExp(vHi,"i"),[vHi,""]],[new RegExp(IHi,"i"),[IHi,""]],[Khd,[Zkr,""]],[new RegExp(INt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[$hd,""];if(new RegExp(NXe).test(t)&&!/IEMobile\b/.test(t))return[INt+" "+NXe,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=Jhd[n]||"";return/arm/i.test(t)&&(i="RT"),[INt,i]}return[INt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Xkr,t.join(".")]}return[Xkr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=RXe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+kXe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+kXe+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[kXe,t.join(".")]}return[kXe,""]}],[/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/,[Lhd,""]],[/Linux|debian/i,["Linux",""]]];var fZa="utf8";function dZa(e,t){if(!e||typeof e!="string"||Yhd(e))throw new Error(t)}function Yhd(e){return e.trim().length===0}function mZa(e){return e?.replace(/\/+$/,"")}async function hZa(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 tNr(){return new Date().toISOString()}function xpe(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var gZa=e=>e instanceof Error;function wHi(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var rNr=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 AZa(){return"CompressionStream"in globalThis}async function CHi(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 j2e=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()}},jXe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function yZa(e){if(e instanceof j2e){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 xHi(e){return typeof e=="object"&&(e instanceof j2e||e instanceof jXe)}function bZa(e){return typeof e=="object"&&e instanceof j2e&&e.status===413}var wNt=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Jkr,this._events=new rNr,this._isInitialized=!1,dZa(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=mZa(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:xHi},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=oZa("[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=!AZa()||(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(wj.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(wj.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(wj.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:pHi(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof j2e)return{type:"api_error",statusCode:t.status};if(t instanceof jXe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=bNt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={};(o??this.disableGeoip)&&(a.geoip_disable=!0),s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let u=c.response;return u.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),u.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(wj.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(wj.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(wj.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(wj.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(wj.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xpe(()=>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:tNr()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,c=this.disableCompression?null:await CHi(s,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||s};try{await this.fetchWithRetry(a,u)}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:tNr(),uuid:n?.uuid?n.uuid:CEe()};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 yZa(t)})}async flush(){let t=wHi([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),wHi([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(wj.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(wj.Queue)||[]).slice(i.length);this.setPersistedProperty(wj.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:tNr()};this.historicalMigration&&(a.historical_migration=!0);let c=JSON.stringify(a),u=`${this.host}/batch/`,l=this.disableCompression?null:await CHi(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||c},d={retryCheck:f=>bZa(f)?!1:xHi(f)};try{await this.fetchWithRetry(u,p,d)}catch(f){if(bZa(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 jXe||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,fZa)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await hZa(async()=>{let a=new AbortController,c=i??this.requestTimeout,u=xpe(()=>a.abort(),c),l=null;try{l=await this.fetch(t,{signal:a.signal,...r})}catch(d){throw new jXe(d)}finally{clearTimeout(u)}if(!(r.mode==="no-cors")&&(l.status<200||l.status>=400))throw new j2e(l,s);return l},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(wj.Queue)||[]).length===0||(await this.flush(),r)););}catch(o){if(!xHi(o))throw o;await yZa(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=xpe(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}finally{clearTimeout(i)}}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var Cj={};X(Cj,{DOMExceptionCoercer:()=>THi,ErrorCoercer:()=>BHi,ErrorEventCoercer:()=>PHi,ErrorPropertiesBuilder:()=>_Hi,EventCoercer:()=>FHi,ObjectCoercer:()=>RHi,PrimitiveCoercer:()=>kHi,PromiseRejectionEventCoercer:()=>NHi,ReduceableCache:()=>jHi,StringCoercer:()=>DHi,chromeStackLineParser:()=>SHi,createDefaultStackParser:()=>fgd,createStackParser:()=>BZa,geckoStackLineParser:()=>OHi,nodeStackLineParser:()=>_Za,opera10StackLineParser:()=>wZa,opera11StackLineParser:()=>CZa,reverseAndStripFrames:()=>TZa,winjsStackLineParser:()=>IZa});var nNr,EZa,iNr;function vZa(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return iNr&&r.length===EZa||(EZa=r.length,iNr=r.reduce((n,i)=>{nNr||(nNr={});let o=nNr[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,nNr[i]=[u,l];break}}}return n},{})),iNr}var Zhd=4,_Hi=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&hHi(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:vZa(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=Zhd){let c=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var PO="?";function qZ(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?PO:r,in_app:!0};return RXe(n)||(o.lineno=n),RXe(i)||(o.colno=i),o}var oNr=(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]:PO,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var egd=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,tgd=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,rgd=/\((\S*)(?::(\d+))(?::(\d+))\)/,SHi=(e,t)=>{let r=egd.exec(e);if(r){let[,i,o,s]=r;return qZ(t,i,PO,+o,+s)}let n=tgd.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=rgd.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=oNr(n[1]||PO,n[2]);return qZ(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var ngd=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,igd=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,OHi=(e,t)=>{let r=ngd.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=igd.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]||PO;return[o,i]=oNr(o,i),qZ(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var ogd=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,IZa=(e,t)=>{let r=ogd.exec(e);return r?qZ(t,r[2],r[1]||PO,+r[3],r[4]?+r[4]:void 0):void 0};var sgd=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,wZa=(e,t)=>{let r=sgd.exec(e);return r?qZ(t,r[2],r[3]||PO,+r[1]):void 0},agd=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,CZa=(e,t)=>{let r=agd.exec(e);return r?qZ(t,r[5],r[3]||r[4]||PO,+r[1],+r[2]):void 0};var cgd=/^\s*[-]{4,}$/,ugd=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,_Za=(e,t)=>{let r=e.match(ugd);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||PO,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:xZa(r[3]),colno:xZa(r[4]),in_app:lgd(c||"",u),platform:t}}if(e.match(cgd))return{filename:e,platform:t}};function lgd(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 xZa(e){return parseInt(e||"",10)||void 0}var SZa=/\(error: (.*)\)/,OZa=50;function TZa(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,OZa).map(r=>({...r,filename:r.filename||pgd(t).filename,function:r.function||PO}))}function pgd(e){return e[e.length-1]||{}}function fgd(){return BZa("web:javascript",SHi,OHi)}function BZa(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
1660
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=SZa.test(a)?a.replace(SZa,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=OZa)break}}return TZa(i)}}var THi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ENt(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 N2e(t,"DOMException")}isDOMError(t){return N2e(t,"DOMError")}};var BHi=class{match(t){return AHi(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 PHi=class{constructor(){}match(t){return rZa(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 dgd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,DHi=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(dgd);return i&&(r=i[1],n=i[2]),[r,n]}};var PZa=["fatal","error","warning","log","info","debug"];function sNr(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 RHi=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 FXe(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=sNr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ENt(t)&&!eZa(t)&&PZa.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(gZa(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var FHi=class{match(t){return FXe(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${sNr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var kHi=class{match(t){return Hkr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var NHi=class{match(t){return N2e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!FXe(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Hkr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var jHi=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 FZa=require("fs"),kZa=require("readline"),aNr=new Cj.ReduceableCache(25),NZa=new Cj.ReduceableCache(20),QHi=7,mgd=1e3,hgd=1e4;async function jZa(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"||bgd(s)||Egd(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(NZa.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=Igd(o);if(s.every(c=>vgd(i,c)))continue;let a=wgd(aNr,i,{});n.push(ggd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Agd(e,aNr),aNr.reduce(),e}function ggd(e,t,r){return new Promise(n=>{let i=(0,FZa.createReadStream)(e),o=(0,kZa.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){NZa.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]=Cgd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Agd(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;ygd(r.lineno,r,n)}}function ygd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=QZa(e);i<e;i++){let o=r[i];if(o===void 0)return void DZa(t);t.pre_context.push(o)}if(r[e]===void 0)return void DZa(t);t.context_line=r[e];let n=MZa(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 DZa(e){delete e.pre_context,delete e.context_line,delete e.post_context}function bgd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Egd(e){return e.lineno!==void 0&&e.lineno>hgd||e.colno!==void 0&&e.colno>mgd}function vgd(e,t){let r=aNr.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 Igd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=RZa(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+QHi:(i.push(n),n=RZa(o)),t++}return i}function RZa(e){return[QZa(e),MZa(e)]}function QZa(e){return Math.max(1,e-QHi)}function MZa(e){return e+QHi}function wgd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Cgd(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 xgd(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 LZa(e,t){globalThis.process?.on("uncaughtException",xgd(e,t))}function UZa(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var _gd=2e3,E7=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Kkr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return gHi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(LZa(this.onException.bind(this),this.onFatalError.bind(this)),UZa(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(_gd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var zZa="5.28.6";var CNt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function VZa(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 Sgd=6e4,Ogd=1152921504606847e3,Tgd=["is_not"],QXe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Ad=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},GZ=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},cNr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof GZ||u instanceof Ad?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof GZ||u instanceof Ad?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Ad("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Ad("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Ad(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Ad("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Ad(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Ad(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Ad(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Ad(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Ad(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Ad(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof GZ)throw l;if(l instanceof Ad)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new Ad("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?HZa(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):$Za(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await qZa(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await qZa(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(Sgd,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 QXe(`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 QXe(`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 QXe(`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 QXe&&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=xpe(()=>{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 qZa(e,t,r=""){let n=await VZa(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/Ogd}function $Za(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 Ad("Operator is_not_set is not supported")}else throw new Ad(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!Tgd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return GZa(String(i))&&String(s).match(String(i))!==null;case"not_regex":return GZa(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Ad("Date operations cannot be performed on boolean values");let u=Fgd(String(i));if(u==null&&(u=WZa(i)),u==null)throw new Ad(`Invalid date: ${i}`);let l=WZa(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return Y5(DO(String(s)),DO(String(i)))===0;case"semver_neq":return Y5(DO(String(s)),DO(String(i)))!==0;case"semver_gt":return Y5(DO(String(s)),DO(String(i)))>0;case"semver_gte":return Y5(DO(String(s)),DO(String(i)))>=0;case"semver_lt":return Y5(DO(String(s)),DO(String(i)))<0;case"semver_lte":return Y5(DO(String(s)),DO(String(i)))<=0;case"semver_tilde":{let u=DO(String(s)),{lower:l,upper:p}=Pgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}case"semver_caret":{let u=DO(String(s)),{lower:l,upper:p}=Dgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}case"semver_wildcard":{let u=DO(String(s)),{lower:l,upper:p}=Rgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}default:throw new Ad(`Unknown operator: ${o}`)}}function Bgd(e,t){if(!(e in t))throw new GZ(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function HZa(e,t,r,n=!1){let i=String(e.value);Bgd(i,r);let o=r[i];return KZa(o,t,r,n)}function KZa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=KZa(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof GZ)throw c;if(c instanceof Ad)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Ad("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=HZa(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=$Za(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof GZ)throw c;if(c instanceof Ad)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Ad("can't match cohort without a given cohort property value");return i==="AND"}function GZa(e){try{return new RegExp(e),!0}catch{return!1}}function DO(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Ad(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new Ad(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function Y5(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Pgd(e){let t=DO(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function Dgd(e){let t=DO(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Rgd(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Ad(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new Ad(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new Ad(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function WZa(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 Ad(`${e} is in an invalid date format`)}throw new Ad(`The date provided ${e} must be a string, number, or date object`)}function Fgd(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 uNr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var kgd=100,JZa=3e4,Ngd=5e4,jgd=50,Qgd=500,lNr=class extends wNt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new uNr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,kgd):JZa,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new cNr({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 E7(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Ngd}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Qgd,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??jgd;this._waitUntilCycle.timer=xpe(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return zZa}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=JZa){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:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;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;b=w.id,E="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 GZ||x instanceof Ad)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!c){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=CNt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(CNt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(CNt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(CNt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=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:b,$feature_flag_version:v,$feature_flag_reason:E,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:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!c){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){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=xpe(()=>{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(nZa(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!E7.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(E7.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!E7.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(E7.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=CEe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!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"&&XXa(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 YZa=require("async_hooks"),pNr=class{constructor(){this.storage=new YZa.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 XZa="posthog-node";function Mgd(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[MHi.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var MHi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=XZa,this.name=XZa,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Mgd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};E7.errorPropertiesBuilder=new Cj.ErrorPropertiesBuilder([new Cj.EventCoercer,new Cj.ErrorCoercer,new Cj.ObjectCoercer,new Cj.StringCoercer,new Cj.PrimitiveCoercer],Cj.createStackParser("node:javascript",Cj.nodeStackLineParser),[HXa(),jZa]);var xEe=class extends lNr{getLibraryId(){return"posthog-node"}initializeContext(){return new pNr}};var fNr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new xEe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.62.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var xNt=class{async sendEvent(){}async identify(){}async flush(){}};$t();var MXe=require("fs/promises"),ZZa=require("os"),eec=require("path");var Lgd="id",Ugd=".fern",_Nt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new xEe(r),this.userId=t==null?void 0:tqi(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.62.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 Xy({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=Ye(Gt.of((0,ZZa.homedir)()),Be.of(Ugd),Be.of(Lgd));await sr(t)||(await(0,MXe.mkdir)((0,eec.dirname)(t),{recursive:!0}),await(0,MXe.writeFile)(t,F_())),this.persistedDistinctId=(await(0,MXe.readFile)(t)).toString()}return this.persistedDistinctId}};var LHi;async function LXe(){return LHi==null&&(LHi=await zgd()),LHi}async function zgd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new xNt;let r=await CTr();return r!=null?new _Nt({token:r,posthogApiKey:e}):await SZ()!=null?new fNr({posthogApiKey:e}):new _Nt({token:void 0,posthogApiKey:e})}catch{return new xNt}}Tt();var SNt=ve(require("process"),1);var nec=ve(KLi(),1),iec=ve(rec(),1);function Y_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Dle(e),e.length===0))return 0;e=e.replace((0,iec.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(nec.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function dNr(e){let t=0;for(let r of e.split(`
1660
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=SZa.test(a)?a.replace(SZa,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=OZa)break}}return TZa(i)}}var THi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ENt(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 N2e(t,"DOMException")}isDOMError(t){return N2e(t,"DOMError")}};var BHi=class{match(t){return AHi(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 PHi=class{constructor(){}match(t){return rZa(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 dgd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,DHi=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(dgd);return i&&(r=i[1],n=i[2]),[r,n]}};var PZa=["fatal","error","warning","log","info","debug"];function sNr(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 RHi=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 FXe(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=sNr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ENt(t)&&!eZa(t)&&PZa.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(gZa(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var FHi=class{match(t){return FXe(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${sNr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var kHi=class{match(t){return Hkr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var NHi=class{match(t){return N2e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!FXe(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Hkr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var jHi=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 FZa=require("fs"),kZa=require("readline"),aNr=new Cj.ReduceableCache(25),NZa=new Cj.ReduceableCache(20),QHi=7,mgd=1e3,hgd=1e4;async function jZa(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"||bgd(s)||Egd(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(NZa.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=Igd(o);if(s.every(c=>vgd(i,c)))continue;let a=wgd(aNr,i,{});n.push(ggd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Agd(e,aNr),aNr.reduce(),e}function ggd(e,t,r){return new Promise(n=>{let i=(0,FZa.createReadStream)(e),o=(0,kZa.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){NZa.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]=Cgd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Agd(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;ygd(r.lineno,r,n)}}function ygd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=QZa(e);i<e;i++){let o=r[i];if(o===void 0)return void DZa(t);t.pre_context.push(o)}if(r[e]===void 0)return void DZa(t);t.context_line=r[e];let n=MZa(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 DZa(e){delete e.pre_context,delete e.context_line,delete e.post_context}function bgd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Egd(e){return e.lineno!==void 0&&e.lineno>hgd||e.colno!==void 0&&e.colno>mgd}function vgd(e,t){let r=aNr.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 Igd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=RZa(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+QHi:(i.push(n),n=RZa(o)),t++}return i}function RZa(e){return[QZa(e),MZa(e)]}function QZa(e){return Math.max(1,e-QHi)}function MZa(e){return e+QHi}function wgd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Cgd(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 xgd(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 LZa(e,t){globalThis.process?.on("uncaughtException",xgd(e,t))}function UZa(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var _gd=2e3,E7=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Kkr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return gHi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(LZa(this.onException.bind(this),this.onFatalError.bind(this)),UZa(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(_gd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var zZa="5.28.6";var CNt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function VZa(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 Sgd=6e4,Ogd=1152921504606847e3,Tgd=["is_not"],QXe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Ad=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},GZ=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},cNr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof GZ||u instanceof Ad?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof GZ||u instanceof Ad?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Ad("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Ad("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Ad(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Ad("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Ad(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Ad(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Ad(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Ad(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Ad(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Ad(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof GZ)throw l;if(l instanceof Ad)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new Ad("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?HZa(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):$Za(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await qZa(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await qZa(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(Sgd,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 QXe(`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 QXe(`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 QXe(`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 QXe&&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=xpe(()=>{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 qZa(e,t,r=""){let n=await VZa(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/Ogd}function $Za(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 Ad("Operator is_not_set is not supported")}else throw new Ad(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!Tgd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return GZa(String(i))&&String(s).match(String(i))!==null;case"not_regex":return GZa(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Ad("Date operations cannot be performed on boolean values");let u=Fgd(String(i));if(u==null&&(u=WZa(i)),u==null)throw new Ad(`Invalid date: ${i}`);let l=WZa(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return Y5(DO(String(s)),DO(String(i)))===0;case"semver_neq":return Y5(DO(String(s)),DO(String(i)))!==0;case"semver_gt":return Y5(DO(String(s)),DO(String(i)))>0;case"semver_gte":return Y5(DO(String(s)),DO(String(i)))>=0;case"semver_lt":return Y5(DO(String(s)),DO(String(i)))<0;case"semver_lte":return Y5(DO(String(s)),DO(String(i)))<=0;case"semver_tilde":{let u=DO(String(s)),{lower:l,upper:p}=Pgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}case"semver_caret":{let u=DO(String(s)),{lower:l,upper:p}=Dgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}case"semver_wildcard":{let u=DO(String(s)),{lower:l,upper:p}=Rgd(String(i));return Y5(u,l)>=0&&Y5(u,p)<0}default:throw new Ad(`Unknown operator: ${o}`)}}function Bgd(e,t){if(!(e in t))throw new GZ(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function HZa(e,t,r,n=!1){let i=String(e.value);Bgd(i,r);let o=r[i];return KZa(o,t,r,n)}function KZa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=KZa(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof GZ)throw c;if(c instanceof Ad)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Ad("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=HZa(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=$Za(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof GZ)throw c;if(c instanceof Ad)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Ad("can't match cohort without a given cohort property value");return i==="AND"}function GZa(e){try{return new RegExp(e),!0}catch{return!1}}function DO(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Ad(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new Ad(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function Y5(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Pgd(e){let t=DO(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function Dgd(e){let t=DO(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Rgd(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Ad(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new Ad(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new Ad(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function WZa(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 Ad(`${e} is in an invalid date format`)}throw new Ad(`The date provided ${e} must be a string, number, or date object`)}function Fgd(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 uNr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var kgd=100,JZa=3e4,Ngd=5e4,jgd=50,Qgd=500,lNr=class extends wNt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new uNr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,kgd):JZa,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new cNr({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 E7(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Ngd}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Qgd,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??jgd;this._waitUntilCycle.timer=xpe(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return zZa}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=JZa){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:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;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;b=w.id,E="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 GZ||x instanceof Ad)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!c){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=CNt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(CNt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(CNt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(CNt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=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:b,$feature_flag_version:v,$feature_flag_reason:E,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:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!c){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){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=xpe(()=>{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(nZa(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!E7.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(E7.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!E7.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(E7.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=CEe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!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"&&XXa(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 YZa=require("async_hooks"),pNr=class{constructor(){this.storage=new YZa.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 XZa="posthog-node";function Mgd(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[MHi.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var MHi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=XZa,this.name=XZa,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Mgd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};E7.errorPropertiesBuilder=new Cj.ErrorPropertiesBuilder([new Cj.EventCoercer,new Cj.ErrorCoercer,new Cj.ObjectCoercer,new Cj.StringCoercer,new Cj.PrimitiveCoercer],Cj.createStackParser("node:javascript",Cj.nodeStackLineParser),[HXa(),jZa]);var xEe=class extends lNr{getLibraryId(){return"posthog-node"}initializeContext(){return new pNr}};var fNr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new xEe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.62.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var xNt=class{async sendEvent(){}async identify(){}async flush(){}};$t();var MXe=require("fs/promises"),ZZa=require("os"),eec=require("path");var Lgd="id",Ugd=".fern",_Nt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new xEe(r),this.userId=t==null?void 0:tqi(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.62.3",...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 Xy({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=Ye(Gt.of((0,ZZa.homedir)()),Be.of(Ugd),Be.of(Lgd));await sr(t)||(await(0,MXe.mkdir)((0,eec.dirname)(t),{recursive:!0}),await(0,MXe.writeFile)(t,F_())),this.persistedDistinctId=(await(0,MXe.readFile)(t)).toString()}return this.persistedDistinctId}};var LHi;async function LXe(){return LHi==null&&(LHi=await zgd()),LHi}async function zgd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new xNt;let r=await CTr();return r!=null?new _Nt({token:r,posthogApiKey:e}):await SZ()!=null?new fNr({posthogApiKey:e}):new _Nt({token:void 0,posthogApiKey:e})}catch{return new xNt}}Tt();var SNt=ve(require("process"),1);var nec=ve(KLi(),1),iec=ve(rec(),1);function Y_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Dle(e),e.length===0))return 0;e=e.replace((0,iec.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(nec.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function dNr(e){let t=0;for(let r of e.split(`
1661
1661
  `))t=Math.max(t,Y_(r));return t}var Cec=ve(zHi(),1);var qgd=/[\p{Lu}]/u,Ggd=/[\p{Ll}]/u,aec=/^[\p{Lu}](?![\p{Lu}])/gu,lec=/([\p{Alpha}\p{N}_]|$)/u,VHi=/[_.\- ]+/,Wgd=new RegExp("^"+VHi.source),cec=new RegExp(VHi.source+lec.source,"gu"),uec=new RegExp("\\d+"+lec.source,"gu"),$gd=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&qgd.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Ggd.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},Hgd=(e,t)=>(aec.lastIndex=0,e.replace(aec,r=>t(r))),Kgd=(e,t)=>(cec.lastIndex=0,uec.lastIndex=0,e.replace(cec,(r,n)=>t(n)).replace(uec,r=>t(r)));function qHi(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?VHi.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=$gd(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Wgd,""),e=t.preserveConsecutiveUppercase?Hgd(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Kgd(e,n))}var HHi=ve(fec(),1);var dec=(e=0)=>t=>`\x1B[${t+e}m`,mec=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,hec=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,Hb={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]}},Cs0=Object.keys(Hb.modifier),Zgd=Object.keys(Hb.color),eAd=Object.keys(Hb.bgColor),xs0=[...Zgd,...eAd];function tAd(){let e=new Map;for(let[t,r]of Object.entries(Hb)){for(let[n,i]of Object.entries(r))Hb[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Hb[n],e.set(i[0],i[1]);Object.defineProperty(Hb,t,{value:r,enumerable:!1})}return Object.defineProperty(Hb,"codes",{value:e,enumerable:!1}),Hb.color.close="\x1B[39m",Hb.bgColor.close="\x1B[49m",Hb.color.ansi=dec(),Hb.color.ansi256=mec(),Hb.color.ansi16m=hec(),Hb.bgColor.ansi=dec(10),Hb.bgColor.ansi256=mec(10),Hb.bgColor.ansi16m=hec(10),Object.defineProperties(Hb,{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=>Hb.rgbToAnsi256(...Hb.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)=>Hb.ansi256ToAnsi(Hb.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>Hb.ansi256ToAnsi(Hb.hexToAnsi256(t)),enumerable:!1}}),Hb}var rAd=tAd(),gec=rAd;var mNr=new Set(["\x1B","\x9B"]),nAd=39,WHi="\x07",bec="[",iAd="]",Eec="m",$Hi=`${iAd}8;;`,Aec=e=>`${mNr.values().next().value}${bec}${e}${Eec}`,yec=e=>`${mNr.values().next().value}${$Hi}${e}${WHi}`,oAd=e=>e.split(" ").map(t=>Y_(t)),GHi=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=Y_(Dle(e[e.length-1]));for(let[a,c]of n.entries()){let u=Y_(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),mNr.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith($Hi)),i){o?c===WHi&&(i=!1,o=!1):c===Eec&&(i=!1);continue}s+=u,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},sAd=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(Y_(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},aAd=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=oAd(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=Y_(a[a.length-1]);if(u!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),GHi(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){GHi(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){GHi(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>sAd(u)));let c=[...a.join(`
1662
1662
  `)];for(let[u,l]of c.entries()){if(n+=l,mNr.has(l)){let{groups:d}=new RegExp(`(?:\\${bec}(?<code>\\d+)m|\\${$Hi}(?<uri>.*)${WHi})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===nAd?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=gec.codes.get(Number(i));c[u+1]===`
1663
1663
  `?(o&&(n+=yec("")),i&&p&&(n+=Aec(p))):l===`
@@ -2197,7 +2197,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
2197
2197
  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=Ye(this.cwd,Be.of(Kp)),r=Ye(this.cwd,Be.of(fqe));if(await sr(t,"file"))return t;if(await sr(r,"file"))return r}};var YUt=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 JUt({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=Ye(n,Be.of(QD)),a=await sr(s,"directory"),c;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};c=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};c=p.fernYml}let u=Ye(this.cwd,Be.of(AI)),l=this.serializeFernYml(c);if(await(0,Amt.writeFile)(u,l,"utf-8"),this.deleteOriginals)for(let p of r)try{await(0,Amt.rm)(p),this.logger.debug(`Deleted ${p}`)}catch{t.push({type:"info",message:`Could not delete ${p}`})}return this.logger.info(`Created ${u}`),{success:!0,warnings:t,migratedFiles:r,outputPath:u}}async migrateSingleApi(t){let{fernDir:r,org:n,warnings:i,migratedFiles:o}=t,a=await new _Le({cwd:r}).migrate();i.push(...a.warnings),a.absoluteFilePath!=null&&o.push(a.absoluteFilePath);let c=await Ayo({fernDir:r,generatorsYmlApi:a.rawApi});i.push(...c.warnings);let u={org:n};return c.api!=null&&(u.api=c.api),a.sdks!=null&&(u.sdks=a.sdks),{success:!0,fernYml:u}}async migrateMultiApi(t){let{fernDir:r,apisDir:n,org:i,warnings:o,migratedFiles:s}=t,c=(await(0,Amt.readdir)(n,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>A.name);if(c.length===0)return o.push({type:"conflict",message:"No API directories found in fern/apis/"}),{success:!1,fernYml:{org:i}};let u={},l={targets:{}},p,d;for(let A of c){let b=Ye(n,Be.of(A)),E=await new _Le({cwd:b,apiName:A}).migrate();if(o.push(...E.warnings),E.absoluteFilePath!=null&&s.push(E.absoluteFilePath),u[A]=E.rawApi,E.sdks!=null){for(let[I,w]of Object.entries(E.sdks.targets))l.targets[I]=w;E.sdks.defaultGroup!=null&&p==null&&(p=E.sdks.defaultGroup),E.sdks.autorelease!=null&&d==null&&(d=E.sdks.autorelease)}}let f=await yyo({fernDir:r,apisDir:n,generatorsYmlApis:u});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 _Le({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()===cA)return this.cwd;let r=Ye(this.cwd,Be.of(cA));if(await sr(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)),Tr.dump(r,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1})}simplifySdks(t){let r={...t},n={};for(let[i,o]of Object.entries(t.targets)){let s=o.output;if(typeof s=="string"){n[i]=o;continue}if(s.git==null&&s.path!=null){n[i]={...o,output:s.path};continue}n[i]=o}return r.targets=n,r}};var byo=class{async handle(t,r){let i=await new YUt({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 on({message:"Migration failed"})}};function Eyo(e){let t=new byo;Wa(e,"migrate","Migrate legacy configuration files to fern.yml",(r,n)=>t.handle(r,n),r=>r.option("delete",{type:"boolean",description:"Keep original files after migration",default:!0}))}function vyo(e){IT(e,"config","Configure, edit, and inspect your settings",[Eyo])}var Iyo=class{async handle(t,r){let n=await t.loadWorkspaceOrThrow();if(n.docs==null)throw new on({message:`No docs configuration found in fern.yml.
2198
2198
 
2199
2199
  Add a 'docs:' section to your fern.yml to get started.`});let o=await new cOe({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 on.exit();return}if(o.violations.length>0)for(let a of o.violations){let c=a.severity==="warning"?Ce.yellow:Ce.red;process.stderr.write(`${c(`${a.displayRelativeFilepath}:${a.line}:${a.column}: ${a.message}`)}
2200
- `)}if(s)throw on.exit();if(o.warningCount>0){t.stderr.info(`${Oo.warning} ${Ce.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(Ce.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Oo.success} ${Ce.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>dee(i))),{success:!r,results:n}}};function wyo(e){let t=new Iyo;Wa(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var T6c=ve(require("net"),1),B6c=ve(require("os"),1),t5n=class extends Error{constructor(t){super(`${t} is locked`)}},ymt={old:new Set,young:new Set},Ebm=1e3*15;var XUt,vbm=()=>{let e=B6c.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},S6c=e=>new Promise((t,r)=>{let n=T6c.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),O6c=async(e,t)=>{if(e.host||e.port===0)return S6c(e);for(let r of t)try{await S6c({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},Ibm=function*(e){e&&(yield*e),yield 0};async function uOe(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)}XUt===void 0&&(XUt=setTimeout(()=>{XUt=void 0,ymt.old=ymt.young,ymt.young=new Set},Ebm),XUt.unref&&XUt.unref());let n=vbm();for(let i of Ibm(t))try{if(r.has(i))continue;let o=await O6c({...e,port:i},n);for(;ymt.old.has(o)||ymt.young.has(o);){if(i!==0)throw new t5n(i);o=await O6c({...e,port:i},n)}return ymt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof t5n))throw o}throw new Error("No available ports found")}Tt();sg();$t();var WZc=ve(_yo(),1),$Zc=ve(U5n(),1),_Vn=require("fs/promises"),HZc=ve(require("http"),1),KZc=ve(require("path"),1);var OWc=require("events"),W5n=ve(require("fs"),1),NLe=ve(require("path"),1);var lWc=ve(require("os"),1),pWc=300,gOe=20,w4t=1e7,fWc=lWc.default.platform();var jxm=fWc==="darwin",Gbo=fWc==="win32",AOe=jxm||Gbo,dWc=3e3,mWc=2e4,Wbo=1250;var tie;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(tie||(tie={}));var kLe;(function(e){e.CHANGE="change",e.RENAME="rename"})(kLe||(kLe={}));var C4t;(function(e){e.CHANGE="change",e.ERROR="error"})(C4t||(C4t={}));var Pc;(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"})(Pc||(Pc={}));var zF;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(zF||(zF={}));var Qxm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let E=Date.now(),I=E-c,w=E-u,x=I>=t||w>=o;return[E,x]},p=E=>{if(u=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(u=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-c,w=E-u,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,c=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},z5n=Qxm;var Jbo=ve(require("fs"),1),q5n=ve(require("path"),1);var bd=ve(require("fs"),1),tT=require("util");var pde=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},rie=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $bo=ve(require("process"),1),hWc=$bo.default.getuid?!$bo.default.getuid():!1,gWc=1e4,W2=()=>{};var x4t={isChangeErrorOk:e=>{if(!x4t.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!hWc&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!x4t.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(!x4t.isNodeError(e))throw e;if(!x4t.isChangeErrorOk(e))throw e}},xI=x4t;var Hbo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=gWc,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()}}}}},AWc=new Hbo;var fde=(e,t)=>function(n){return function i(...o){return AWc.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},dde=(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 Mxm={attempt:{chmod:pde((0,tT.promisify)(bd.default.chmod),xI.onChangeError),chown:pde((0,tT.promisify)(bd.default.chown),xI.onChangeError),close:pde((0,tT.promisify)(bd.default.close),W2),fsync:pde((0,tT.promisify)(bd.default.fsync),W2),mkdir:pde((0,tT.promisify)(bd.default.mkdir),W2),realpath:pde((0,tT.promisify)(bd.default.realpath),W2),stat:pde((0,tT.promisify)(bd.default.stat),W2),unlink:pde((0,tT.promisify)(bd.default.unlink),W2),chmodSync:rie(bd.default.chmodSync,xI.onChangeError),chownSync:rie(bd.default.chownSync,xI.onChangeError),closeSync:rie(bd.default.closeSync,W2),existsSync:rie(bd.default.existsSync,W2),fsyncSync:rie(bd.default.fsync,W2),mkdirSync:rie(bd.default.mkdirSync,W2),realpathSync:rie(bd.default.realpathSync,W2),statSync:rie(bd.default.statSync,W2),unlinkSync:rie(bd.default.unlinkSync,W2)},retry:{close:fde((0,tT.promisify)(bd.default.close),xI.isRetriableError),fsync:fde((0,tT.promisify)(bd.default.fsync),xI.isRetriableError),open:fde((0,tT.promisify)(bd.default.open),xI.isRetriableError),readFile:fde((0,tT.promisify)(bd.default.readFile),xI.isRetriableError),rename:fde((0,tT.promisify)(bd.default.rename),xI.isRetriableError),stat:fde((0,tT.promisify)(bd.default.stat),xI.isRetriableError),write:fde((0,tT.promisify)(bd.default.write),xI.isRetriableError),writeFile:fde((0,tT.promisify)(bd.default.writeFile),xI.isRetriableError),closeSync:dde(bd.default.closeSync,xI.isRetriableError),fsyncSync:dde(bd.default.fsyncSync,xI.isRetriableError),openSync:dde(bd.default.openSync,xI.isRetriableError),readFileSync:dde(bd.default.readFileSync,xI.isRetriableError),renameSync:dde(bd.default.renameSync,xI.isRetriableError),statSync:dde(bd.default.statSync,xI.isRetriableError),writeSync:dde(bd.default.writeSync,xI.isRetriableError),writeFileSync:dde(bd.default.writeFileSync,xI.isRetriableError)}},yWc=Mxm;var V5n=ve(require("fs"),1),_4t=ve(require("path"),1);var Kbo=()=>{};var Lxm=()=>{let e=Kbo,t=Kbo,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},bWc=Lxm;var Uxm=()=>{let{promise:e,resolve:t,isPending:r}=bWc(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},EWc=Uxm;var vWc={then:e=>{e()}};var IWc=e=>Array.isArray(e)?e:[e],wWc=e=>typeof e=="function";var zxm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=IWc(o).map(Z=>wWc(Z)?Z:te=>Z.test(te)),a=Z=>s.some(te=>te(Z)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=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:b,map:v},{promise:x,increment:C,decrement:_}=EWc(),R=0,G=(Z,te,be,Ae)=>{E.has(te)||R>=i||(R+=1,Z.directories.push(te),Z.directoriesNames.add(be),l.push(te),p.add(be),d.propertyIsEnumerable(be)||(d[be]=[]),d[be].push(te),E.add(te),!(Ae>=n)&&(R>=i||H(te,Ae+1)))},V=(Z,te,be)=>{E.has(te)||R>=i||(R+=1,Z.files.push(te),Z.filesNames.add(be),f.push(te),m.add(be),h.propertyIsEnumerable(be)||(h[be]=[]),h[be].push(te),E.add(te))},z=(Z,te,be,Ae)=>{E.has(te)||R>=i||(R+=1,Z.symlinks.push(te),Z.symlinksNames.add(be),g.push(te),A.add(be),b.propertyIsEnumerable(be)||(b[be]=[]),b[be].push(te),E.add(te),r&&(Ae>=n||R>=i||ye(te,Ae+1)))},K=(Z,te,be,Ae,Te)=>{c.aborted||a(te)||(Ae.isDirectory()?G(Z,te,be,Te):Ae.isFile()?V(Z,te,be):Ae.isSymbolicLink()&&z(Z,te,be,Te))},ie=(Z,te,be,Ae)=>{if(c.aborted)return;let Te=te===_4t.default.sep?"":_4t.default.sep,Se=be.name,pe=`${te}${Te}${Se}`;a(pe)||(be.isDirectory()?G(Z,pe,Se,Ae):be.isFile()?V(Z,pe,Se):be.isSymbolicLink()&&z(Z,pe,Se,Ae))},q=(Z,te,be,Ae)=>{for(let Te=0,Se=be.length;Te<Se;Te++)ie(Z,te,be[Te],Ae)},H=(Z,te)=>{c.aborted||te>n||R>=i||(C(),V5n.default.readdir(Z,{withFileTypes:!0},(be,Ae)=>{if(be||c.aborted||!Ae.length)return _();(u(Ae)||vWc).then(()=>{let Se=v[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};q(Se,Z,Ae,te),_()})}))},ye=(Z,te)=>{C(),V5n.default.realpath(Z,(be,Ae)=>{if(be||c.aborted)return _();V5n.default.stat(Ae,(Te,Se)=>{if(Te||c.aborted)return _();let pe=_4t.default.basename(Ae),le=v[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(le,Ae,pe,Se,te),_()})})};return(async(Z,te=1)=>(Z=_4t.default.normalize(Z),E.add(Z),H(Z,te),await x,c.aborted?I:w))(e)},CWc=zxm;var nie={lang:{debounce:z5n,attempt:e=>{try{return e()}catch(t){return nie.lang.castError(t)}},castArray:e=>nie.lang.isArray(e)?e:[e],castError:e=>nie.lang.isError(e)?e:nie.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(nie.lang.isNaN(e))return nie.lang.isNaN(t);if(nie.lang.isPrimitive(e)||nie.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(q5n.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Jbo.default.realpathSync.native(e):Jbo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===q5n.default.sep&&t.length-e.length>q5n.default.sep.length,poll:(e,t=mWc)=>yWc.retry.stat(t)(e,{bigint:!0}).catch(nie.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 CWc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Hl=nie;var G5n=ve(require("path"),1);var Ybo=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||Hl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=pWc){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Hl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Pc.CHANGE&&a===Pc.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===Pc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Pc.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??gOe:Math.min(1,this.options.depth??gOe),s=this.options.limit??w4t,[a,c]=await Hl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Hl.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(Pc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!AOe&&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(Pc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Pc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(G5n.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Pc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(G5n.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(Pc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Pc.ADD?this.onTargetAdd(n):r===Pc.ADD_DIR?this.onTargetAddDir(n):r===Pc.CHANGE?this.onTargetChange(n):r===Pc.UNLINK?this.onTargetUnlink(n):r===Pc.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=kLe.CHANGE,r){if(this.watcher.isClosed())return;let n=G5n.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){Gbo&&t.code==="EPERM"?this.onWatcherChange(kLe.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(C4t.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(C4t.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(kLe.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&AOe&&this.options.native!==!1?this.options.depth??gOe:Math.min(1,this.options.depth??gOe),n=this.options.limit??w4t,[i,o]=await Hl.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(kLe.CHANGE,a,t)}))}}},xWc=Ybo;var VF={interval:100,intervalId:void 0,fns:new Map,init:()=>{VF.intervalId||(VF.intervalId=setInterval(VF.resolve,VF.interval))},reset:()=>{VF.intervalId&&(clearInterval(VF.intervalId),delete VF.intervalId)},add:(e,t)=>{VF.fns.set(e,Date.now()+t),VF.init()},remove:e=>{VF.fns.delete(e)},resolve:()=>{if(!VF.fns.size)return VF.reset();let e=Date.now();for(let[t,r]of VF.fns)r>=e||(VF.remove(t),t())}},S4t=VF;var O4t=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Wbo){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(Hl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),S4t.remove(u)},u=()=>{c(),a()};S4t.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Wbo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),S4t.remove(u)},u=()=>{c(),a()};S4t.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Pc.ADD,tie.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,Pc.ADD_DIR,tie.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,Pc.UNLINK,tie.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,Pc.UNLINK_DIR,tie.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}}};O4t.DIR_EVENTS={add:Pc.ADD_DIR,rename:Pc.RENAME_DIR,unlink:Pc.UNLINK_DIR};O4t.FILE_EVENTS={add:Pc.ADD,change:Pc.CHANGE,rename:Pc.RENAME,unlink:Pc.UNLINK};var _Wc=O4t;var Xbo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Hl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Hl.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(Hl.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(Hl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Hl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Hl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},Zbo=Xbo;var e0o=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}},SWc=e0o;var t0o=class{constructor(){this.inos={},this.paths=new Zbo,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 Hl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new SWc(n)}reset(){this.inos={},this.paths=new Zbo,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,Pc.ADD,i),[Pc.ADD];if(i.isDirectory())return this.updateIno(t,Pc.ADD_DIR,i),[Pc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Pc.UNLINK,n),[Pc.UNLINK];if(n.isDirectory())return this.updateIno(t,Pc.UNLINK_DIR,n),[Pc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Pc.CHANGE,i),[Pc.CHANGE]);if(i.isDirectory())return this.updateIno(t,Pc.UNLINK,n),this.updateIno(t,Pc.ADD_DIR,i),[Pc.UNLINK,Pc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Pc.UNLINK_DIR,n),this.updateIno(t,Pc.ADD,i),[Pc.UNLINK_DIR,Pc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Pc.UNLINK_DIR,n),this.updateIno(t,Pc.ADD_DIR,i),[Pc.UNLINK_DIR,Pc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?tie.FILE:tie.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)}}},r0o=t0o;var n0o=class e extends OWc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(zF.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(zF.CLOSE,i)),this._readyWait=new Promise(i=>this.on(zF.READY,i)),this._locker=new _Wc(this),this._roots=new Set,this._poller=new r0o,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&&(Hl.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(zF.CLOSE))}error(t){if(this.isClosed())return!1;let r=Hl.lang.castError(t);return this.emit(zF.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(zF.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(zF.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Hl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Hl.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)Hl.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 xWc(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=Hl.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=NLe.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??gOe))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&AOe&&l.options.native!==!1)))return!0;if(!AOe)break;let u=NLe.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Hl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||AOe&&r.native!==!1?r:{...r,recursive:!1},l={watcher:W5n.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=NLe.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||AOe&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??gOe,a=r.limit??w4t,[c]=await Hl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Hl.fs.getDepth(t);for(let p of c){let d=Hl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(zF.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(zF.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=NLe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new r0o,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 Hl.lang.noop;if(this.pollerExists(t,r))return Hl.lang.noop;let i={...r,interval:r.pollingInterval??dWc},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(zF.CLOSE,a),W5n.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(zF.CLOSE,a),W5n.default.unwatchFile(t,n)};return Hl.lang.attempt(s),()=>Hl.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=Hl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Hl.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=NLe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Hl.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=NLe.default.dirname(t);return(await Hl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Hl.lang.noop){if(Hl.lang.isFunction(t))return this.watch([],{},t);if(Hl.lang.isUndefined(t))return this.watch([],r,n);if(Hl.lang.isFunction(r))return this.watch(t,{},r);if(Hl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Hl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Hl.lang.noop&&this.on(zF.ALL,n),r.readdirMap=void 0,this.ready())}},$5n=n0o;c3n();$t();var Vmt=require("fs/promises"),R$c=require("os"),F$c=ve(require("path"),1),mSm=".fern",hSm="logs";function gSm(){return"cli@4.62.1"}var zLe=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ye(Gt.of((0,R$c.homedir)()),Be.of(mSm)),r=Ye(t,Be.of(hSm));await sr(r)||await(0,Vmt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ye(r,Be.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${F$c.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2200
+ `)}if(s)throw on.exit();if(o.warningCount>0){t.stderr.info(`${Oo.warning} ${Ce.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(Ce.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Oo.success} ${Ce.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>dee(i))),{success:!r,results:n}}};function wyo(e){let t=new Iyo;Wa(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var T6c=ve(require("net"),1),B6c=ve(require("os"),1),t5n=class extends Error{constructor(t){super(`${t} is locked`)}},ymt={old:new Set,young:new Set},Ebm=1e3*15;var XUt,vbm=()=>{let e=B6c.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},S6c=e=>new Promise((t,r)=>{let n=T6c.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),O6c=async(e,t)=>{if(e.host||e.port===0)return S6c(e);for(let r of t)try{await S6c({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},Ibm=function*(e){e&&(yield*e),yield 0};async function uOe(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)}XUt===void 0&&(XUt=setTimeout(()=>{XUt=void 0,ymt.old=ymt.young,ymt.young=new Set},Ebm),XUt.unref&&XUt.unref());let n=vbm();for(let i of Ibm(t))try{if(r.has(i))continue;let o=await O6c({...e,port:i},n);for(;ymt.old.has(o)||ymt.young.has(o);){if(i!==0)throw new t5n(i);o=await O6c({...e,port:i},n)}return ymt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof t5n))throw o}throw new Error("No available ports found")}Tt();sg();$t();var WZc=ve(_yo(),1),$Zc=ve(U5n(),1),_Vn=require("fs/promises"),HZc=ve(require("http"),1),KZc=ve(require("path"),1);var OWc=require("events"),W5n=ve(require("fs"),1),NLe=ve(require("path"),1);var lWc=ve(require("os"),1),pWc=300,gOe=20,w4t=1e7,fWc=lWc.default.platform();var jxm=fWc==="darwin",Gbo=fWc==="win32",AOe=jxm||Gbo,dWc=3e3,mWc=2e4,Wbo=1250;var tie;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(tie||(tie={}));var kLe;(function(e){e.CHANGE="change",e.RENAME="rename"})(kLe||(kLe={}));var C4t;(function(e){e.CHANGE="change",e.ERROR="error"})(C4t||(C4t={}));var Pc;(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"})(Pc||(Pc={}));var zF;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(zF||(zF={}));var Qxm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let E=Date.now(),I=E-c,w=E-u,x=I>=t||w>=o;return[E,x]},p=E=>{if(u=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(u=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-c,w=E-u,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,c=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},z5n=Qxm;var Jbo=ve(require("fs"),1),q5n=ve(require("path"),1);var bd=ve(require("fs"),1),tT=require("util");var pde=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},rie=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $bo=ve(require("process"),1),hWc=$bo.default.getuid?!$bo.default.getuid():!1,gWc=1e4,W2=()=>{};var x4t={isChangeErrorOk:e=>{if(!x4t.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!hWc&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!x4t.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(!x4t.isNodeError(e))throw e;if(!x4t.isChangeErrorOk(e))throw e}},xI=x4t;var Hbo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=gWc,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()}}}}},AWc=new Hbo;var fde=(e,t)=>function(n){return function i(...o){return AWc.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},dde=(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 Mxm={attempt:{chmod:pde((0,tT.promisify)(bd.default.chmod),xI.onChangeError),chown:pde((0,tT.promisify)(bd.default.chown),xI.onChangeError),close:pde((0,tT.promisify)(bd.default.close),W2),fsync:pde((0,tT.promisify)(bd.default.fsync),W2),mkdir:pde((0,tT.promisify)(bd.default.mkdir),W2),realpath:pde((0,tT.promisify)(bd.default.realpath),W2),stat:pde((0,tT.promisify)(bd.default.stat),W2),unlink:pde((0,tT.promisify)(bd.default.unlink),W2),chmodSync:rie(bd.default.chmodSync,xI.onChangeError),chownSync:rie(bd.default.chownSync,xI.onChangeError),closeSync:rie(bd.default.closeSync,W2),existsSync:rie(bd.default.existsSync,W2),fsyncSync:rie(bd.default.fsync,W2),mkdirSync:rie(bd.default.mkdirSync,W2),realpathSync:rie(bd.default.realpathSync,W2),statSync:rie(bd.default.statSync,W2),unlinkSync:rie(bd.default.unlinkSync,W2)},retry:{close:fde((0,tT.promisify)(bd.default.close),xI.isRetriableError),fsync:fde((0,tT.promisify)(bd.default.fsync),xI.isRetriableError),open:fde((0,tT.promisify)(bd.default.open),xI.isRetriableError),readFile:fde((0,tT.promisify)(bd.default.readFile),xI.isRetriableError),rename:fde((0,tT.promisify)(bd.default.rename),xI.isRetriableError),stat:fde((0,tT.promisify)(bd.default.stat),xI.isRetriableError),write:fde((0,tT.promisify)(bd.default.write),xI.isRetriableError),writeFile:fde((0,tT.promisify)(bd.default.writeFile),xI.isRetriableError),closeSync:dde(bd.default.closeSync,xI.isRetriableError),fsyncSync:dde(bd.default.fsyncSync,xI.isRetriableError),openSync:dde(bd.default.openSync,xI.isRetriableError),readFileSync:dde(bd.default.readFileSync,xI.isRetriableError),renameSync:dde(bd.default.renameSync,xI.isRetriableError),statSync:dde(bd.default.statSync,xI.isRetriableError),writeSync:dde(bd.default.writeSync,xI.isRetriableError),writeFileSync:dde(bd.default.writeFileSync,xI.isRetriableError)}},yWc=Mxm;var V5n=ve(require("fs"),1),_4t=ve(require("path"),1);var Kbo=()=>{};var Lxm=()=>{let e=Kbo,t=Kbo,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},bWc=Lxm;var Uxm=()=>{let{promise:e,resolve:t,isPending:r}=bWc(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},EWc=Uxm;var vWc={then:e=>{e()}};var IWc=e=>Array.isArray(e)?e:[e],wWc=e=>typeof e=="function";var zxm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=IWc(o).map(Z=>wWc(Z)?Z:te=>Z.test(te)),a=Z=>s.some(te=>te(Z)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=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:b,map:v},{promise:x,increment:C,decrement:_}=EWc(),R=0,G=(Z,te,be,Ae)=>{E.has(te)||R>=i||(R+=1,Z.directories.push(te),Z.directoriesNames.add(be),l.push(te),p.add(be),d.propertyIsEnumerable(be)||(d[be]=[]),d[be].push(te),E.add(te),!(Ae>=n)&&(R>=i||H(te,Ae+1)))},V=(Z,te,be)=>{E.has(te)||R>=i||(R+=1,Z.files.push(te),Z.filesNames.add(be),f.push(te),m.add(be),h.propertyIsEnumerable(be)||(h[be]=[]),h[be].push(te),E.add(te))},z=(Z,te,be,Ae)=>{E.has(te)||R>=i||(R+=1,Z.symlinks.push(te),Z.symlinksNames.add(be),g.push(te),A.add(be),b.propertyIsEnumerable(be)||(b[be]=[]),b[be].push(te),E.add(te),r&&(Ae>=n||R>=i||ye(te,Ae+1)))},K=(Z,te,be,Ae,Te)=>{c.aborted||a(te)||(Ae.isDirectory()?G(Z,te,be,Te):Ae.isFile()?V(Z,te,be):Ae.isSymbolicLink()&&z(Z,te,be,Te))},ie=(Z,te,be,Ae)=>{if(c.aborted)return;let Te=te===_4t.default.sep?"":_4t.default.sep,Se=be.name,pe=`${te}${Te}${Se}`;a(pe)||(be.isDirectory()?G(Z,pe,Se,Ae):be.isFile()?V(Z,pe,Se):be.isSymbolicLink()&&z(Z,pe,Se,Ae))},q=(Z,te,be,Ae)=>{for(let Te=0,Se=be.length;Te<Se;Te++)ie(Z,te,be[Te],Ae)},H=(Z,te)=>{c.aborted||te>n||R>=i||(C(),V5n.default.readdir(Z,{withFileTypes:!0},(be,Ae)=>{if(be||c.aborted||!Ae.length)return _();(u(Ae)||vWc).then(()=>{let Se=v[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};q(Se,Z,Ae,te),_()})}))},ye=(Z,te)=>{C(),V5n.default.realpath(Z,(be,Ae)=>{if(be||c.aborted)return _();V5n.default.stat(Ae,(Te,Se)=>{if(Te||c.aborted)return _();let pe=_4t.default.basename(Ae),le=v[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(le,Ae,pe,Se,te),_()})})};return(async(Z,te=1)=>(Z=_4t.default.normalize(Z),E.add(Z),H(Z,te),await x,c.aborted?I:w))(e)},CWc=zxm;var nie={lang:{debounce:z5n,attempt:e=>{try{return e()}catch(t){return nie.lang.castError(t)}},castArray:e=>nie.lang.isArray(e)?e:[e],castError:e=>nie.lang.isError(e)?e:nie.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(nie.lang.isNaN(e))return nie.lang.isNaN(t);if(nie.lang.isPrimitive(e)||nie.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(q5n.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Jbo.default.realpathSync.native(e):Jbo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===q5n.default.sep&&t.length-e.length>q5n.default.sep.length,poll:(e,t=mWc)=>yWc.retry.stat(t)(e,{bigint:!0}).catch(nie.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 CWc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Hl=nie;var G5n=ve(require("path"),1);var Ybo=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||Hl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=pWc){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Hl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Pc.CHANGE&&a===Pc.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===Pc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Pc.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??gOe:Math.min(1,this.options.depth??gOe),s=this.options.limit??w4t,[a,c]=await Hl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Hl.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(Pc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!AOe&&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(Pc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Pc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(G5n.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Pc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(G5n.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(Pc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Pc.ADD?this.onTargetAdd(n):r===Pc.ADD_DIR?this.onTargetAddDir(n):r===Pc.CHANGE?this.onTargetChange(n):r===Pc.UNLINK?this.onTargetUnlink(n):r===Pc.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=kLe.CHANGE,r){if(this.watcher.isClosed())return;let n=G5n.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){Gbo&&t.code==="EPERM"?this.onWatcherChange(kLe.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(C4t.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(C4t.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(kLe.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&AOe&&this.options.native!==!1?this.options.depth??gOe:Math.min(1,this.options.depth??gOe),n=this.options.limit??w4t,[i,o]=await Hl.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(kLe.CHANGE,a,t)}))}}},xWc=Ybo;var VF={interval:100,intervalId:void 0,fns:new Map,init:()=>{VF.intervalId||(VF.intervalId=setInterval(VF.resolve,VF.interval))},reset:()=>{VF.intervalId&&(clearInterval(VF.intervalId),delete VF.intervalId)},add:(e,t)=>{VF.fns.set(e,Date.now()+t),VF.init()},remove:e=>{VF.fns.delete(e)},resolve:()=>{if(!VF.fns.size)return VF.reset();let e=Date.now();for(let[t,r]of VF.fns)r>=e||(VF.remove(t),t())}},S4t=VF;var O4t=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Wbo){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(Hl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),S4t.remove(u)},u=()=>{c(),a()};S4t.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Wbo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),S4t.remove(u)},u=()=>{c(),a()};S4t.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Pc.ADD,tie.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,Pc.ADD_DIR,tie.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,Pc.UNLINK,tie.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,Pc.UNLINK_DIR,tie.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}}};O4t.DIR_EVENTS={add:Pc.ADD_DIR,rename:Pc.RENAME_DIR,unlink:Pc.UNLINK_DIR};O4t.FILE_EVENTS={add:Pc.ADD,change:Pc.CHANGE,rename:Pc.RENAME,unlink:Pc.UNLINK};var _Wc=O4t;var Xbo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Hl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Hl.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(Hl.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(Hl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Hl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Hl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},Zbo=Xbo;var e0o=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}},SWc=e0o;var t0o=class{constructor(){this.inos={},this.paths=new Zbo,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 Hl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new SWc(n)}reset(){this.inos={},this.paths=new Zbo,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,Pc.ADD,i),[Pc.ADD];if(i.isDirectory())return this.updateIno(t,Pc.ADD_DIR,i),[Pc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Pc.UNLINK,n),[Pc.UNLINK];if(n.isDirectory())return this.updateIno(t,Pc.UNLINK_DIR,n),[Pc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Pc.CHANGE,i),[Pc.CHANGE]);if(i.isDirectory())return this.updateIno(t,Pc.UNLINK,n),this.updateIno(t,Pc.ADD_DIR,i),[Pc.UNLINK,Pc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Pc.UNLINK_DIR,n),this.updateIno(t,Pc.ADD,i),[Pc.UNLINK_DIR,Pc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Pc.UNLINK_DIR,n),this.updateIno(t,Pc.ADD_DIR,i),[Pc.UNLINK_DIR,Pc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?tie.FILE:tie.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)}}},r0o=t0o;var n0o=class e extends OWc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(zF.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(zF.CLOSE,i)),this._readyWait=new Promise(i=>this.on(zF.READY,i)),this._locker=new _Wc(this),this._roots=new Set,this._poller=new r0o,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&&(Hl.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(zF.CLOSE))}error(t){if(this.isClosed())return!1;let r=Hl.lang.castError(t);return this.emit(zF.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(zF.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(zF.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Hl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Hl.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)Hl.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 xWc(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=Hl.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=NLe.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??gOe))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&AOe&&l.options.native!==!1)))return!0;if(!AOe)break;let u=NLe.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Hl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||AOe&&r.native!==!1?r:{...r,recursive:!1},l={watcher:W5n.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=NLe.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||AOe&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??gOe,a=r.limit??w4t,[c]=await Hl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Hl.fs.getDepth(t);for(let p of c){let d=Hl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(zF.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(zF.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=NLe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new r0o,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 Hl.lang.noop;if(this.pollerExists(t,r))return Hl.lang.noop;let i={...r,interval:r.pollingInterval??dWc},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(zF.CLOSE,a),W5n.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(zF.CLOSE,a),W5n.default.unwatchFile(t,n)};return Hl.lang.attempt(s),()=>Hl.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=Hl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Hl.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=NLe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Hl.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=NLe.default.dirname(t);return(await Hl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Hl.lang.noop){if(Hl.lang.isFunction(t))return this.watch([],{},t);if(Hl.lang.isUndefined(t))return this.watch([],r,n);if(Hl.lang.isFunction(r))return this.watch(t,{},r);if(Hl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Hl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Hl.lang.noop&&this.on(zF.ALL,n),r.readdirMap=void 0,this.ready())}},$5n=n0o;c3n();$t();var Vmt=require("fs/promises"),R$c=require("os"),F$c=ve(require("path"),1),mSm=".fern",hSm="logs";function gSm(){return"cli@4.62.3"}var zLe=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ye(Gt.of((0,R$c.homedir)()),Be.of(mSm)),r=Ye(t,Be.of(hSm));await sr(r)||await(0,Vmt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ye(r,Be.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${F$c.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2201
2201
  `);await(0,Vmt.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)+`
2202
2202
  `;try{await(0,Vmt.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:gSm(),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 x0o={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function k$c(e){let t=ASm();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i}=e,o=new Map;function s(c){let u=JSON.stringify(c),l=[];for(let[p]of o)try{p.send(u)}catch{l.push(p)}for(let p of l){let d=o.get(p);d&&(clearInterval(d.pingInterval),o.delete(p))}}let a=t.serve({port:r,fetch(c,u){if(c.method==="OPTIONS")return new Response(null,{status:204,headers:x0o});let l=new URL(c.url);if(c.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(c,{data:{connectionId:`${Date.now()}`}});return}if(c.method==="POST"&&l.pathname==="/v2/registry/docs/load-with-url")return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...x0o}});let p=/^\/_local\/(.*)/.exec(l.pathname);return c.method==="GET"&&p!=null?new Response(t.file(`/${p[1]}`),{headers:x0o}):new Response("Not Found",{status:404})},websocket:{open(c){let{connectionId:u}=c.data,l=setInterval(()=>{let p=o.get(c);if(!p)return;let d=Date.now();if(d-p.lastPong>9e4){c.close();return}try{c.send(JSON.stringify({type:"ping",timestamp:d}))}catch{c.close()}},3e4);o.set(c,{pingInterval:l,lastPong:Date.now()});try{c.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(c,u){try{let l=JSON.parse(u.toString());if(l.type==="pong"){let p=o.get(c);p&&(p.lastPong=Date.now())}else zLe.isMetricsMessage(l)&&n.logFrontendMetrics(l)}catch{}},close(c){let u=o.get(c);u&&(clearInterval(u.pingInterval),o.delete(c))}}});return{sendData:s,stop:c=>a.stop(c)}}function ASm(){return globalThis.Bun}$t();var ovo=ve(F0o(),1),QZc=ve($Eo(),1),$2=require("fs/promises"),MZc=require("os"),LZc=ve(Qx(),1),UZc=ve(NZc(),1),EVn=process.platform==="win32",ivo=Ce.cyan("[docs]:"),$Bm="etag",HBm=23,jZc=e=>e.padEnd(HBm," "),KBm="preview",JBm="app-preview",YBm="bundle",XBm=".next",ZBm="standalone",ePm=".fern",tPm="packages/fern-docs/bundle/.next/server/instrumentation.js",rPm=".npmrc",nPm=".pnpmfile.cjs",iPm="pnpm-workspace.yaml",oPm='Cannot find matching keyid: {"signatures":';function sPm(){return Ye(Gt.of((0,MZc.homedir)()),Be.of(ePm))}function aht({app:e=!1}){return Ye(sPm(),Be.of(e?JBm:KBm))}function OOe({app:e=!1}){return Ye(aht({app:e}),Be.of(e?XBm:YBm))}function szt({app:e=!1}){return Ye(OOe({app:e}),Be.of(ZBm))}function aPm({app:e=!1}){return Ye(szt({app:e}),Be.of(tPm))}function cPm({app:e=!1}){return Ye(szt({app:e}),Be.of(iPm))}function uPm({app:e=!1}){return Ye(szt({app:e}),Be.of(nPm))}function lPm({app:e=!1}){return Ye(szt({app:e}),Be.of(rPm))}function YLe(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function pPm({app:e=!1}){return Ye(aht({app:e}),Be.of($Bm))}var fPm=`module.exports = {
2203
2203
  hooks: {
@@ -2239,7 +2239,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
2239
2239
 
2240
2240
  Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`:r}function aFm(e,t){return t!=null&&t.includes("Invalid authorization token")?"Your authentication token is invalid or expired. Please run 'fern login' to re-authenticate.":`You are not authorized to publish docs under organization '${e}'. Please run 'fern login' to ensure you are logged in with the correct account.
2241
2241
 
2242
- Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}function cFm(e){if(e==null)return{code:void 0,message:void 0};let t=e.body;if(t!=null&&typeof t=="object"){let n=typeof t.code=="string"?t.code:void 0,i=typeof t.message=="string"?t.message:void 0;return{code:n,message:i}}return{code:void 0,message:typeof t=="string"&&t.length>0?t:typeof e.errorMessage=="string"?e.errorMessage:typeof e.message=="string"?e.message:void 0}}function uFm(e){try{return new URL(FF(e)).pathname}catch{return}}async function lFm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await pFm({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:Pr.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 c={};for(let[u,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function Ttu(e){return e.replace(/^https:\/\//,"")}async function pFm({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&&Ttu(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 fFm({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 fFm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=Dn.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!u.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 ${u.body.version} for package "${a}"`),{version:u.body.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function dFm({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&&Ttu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=XLe({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=cg({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new nh(r,e),dynamicGeneratorConfig:u}),d=VNe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function mFm({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 hFm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(Ce.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function gFm(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 Btu(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 mzt=[60*1e3,300*1e3,300*1e3];async function hzt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d,deployerAuthor:f}){let m=a&&!n.config.settings?.substituteEnvVars;n.config=_b(n.config,{onError:v=>i.failAndThrow(v)},{substituteAsEmpty:m});let h=n.config.instances;if(h.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(h.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${h[0]?.url})`);return}let g=h.find(v=>v.url===s)??h[0];if(g==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let A=[];g.customDomain!=null&&(typeof g.customDomain=="string"?A.push(g.customDomain):Array.isArray(g.customDomain)&&A.push(...g.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${g.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let b;return await i.runInteractiveTask({name:g.url},async()=>{let v=performance.now(),E=()=>Stu({docsWorkspace:n,customDomains:A,domain:g.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:g.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:g.audiences?Array.isArray(g.audiences)?g.audiences:[g.audiences]:void 0,docsUrl:g.url,cliVersion:p,ciSource:d,deployerAuthor:f});for(let w=0;;w++)try{b=await E();break}catch(x){if(!(x instanceof pht)||w>=mzt.length){if(x instanceof pht)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw x}let C=mzt[w]??mzt[mzt.length-1]??6e4,_=C/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${_} minute${_===1?"":"s"} (attempt ${w+1}/${mzt.length})...`),await new Promise(R=>setTimeout(R,C))}let I=performance.now()-v;i.logger.debug(`Docs publishing completed in ${I.toFixed(0)}ms`)}),b}var g8n=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 dg({context:this.context,task:this.task});try{let o=await hzt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,previewId:void 0,disableTemplates:void 0,skipUpload:n,cliVersion:"4.62.1"});return i.getResult()===If.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:ji(o)}}}};Tt();var fht=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
2242
+ Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}function cFm(e){if(e==null)return{code:void 0,message:void 0};let t=e.body;if(t!=null&&typeof t=="object"){let n=typeof t.code=="string"?t.code:void 0,i=typeof t.message=="string"?t.message:void 0;return{code:n,message:i}}return{code:void 0,message:typeof t=="string"&&t.length>0?t:typeof e.errorMessage=="string"?e.errorMessage:typeof e.message=="string"?e.message:void 0}}function uFm(e){try{return new URL(FF(e)).pathname}catch{return}}async function lFm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await pFm({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:Pr.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 c={};for(let[u,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function Ttu(e){return e.replace(/^https:\/\//,"")}async function pFm({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&&Ttu(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 fFm({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 fFm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=Dn.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!u.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 ${u.body.version} for package "${a}"`),{version:u.body.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function dFm({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&&Ttu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=XLe({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=cg({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new nh(r,e),dynamicGeneratorConfig:u}),d=VNe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function mFm({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 hFm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(Ce.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function gFm(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 Btu(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 mzt=[60*1e3,300*1e3,300*1e3];async function hzt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d,deployerAuthor:f}){let m=a&&!n.config.settings?.substituteEnvVars;n.config=_b(n.config,{onError:v=>i.failAndThrow(v)},{substituteAsEmpty:m});let h=n.config.instances;if(h.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(h.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${h[0]?.url})`);return}let g=h.find(v=>v.url===s)??h[0];if(g==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let A=[];g.customDomain!=null&&(typeof g.customDomain=="string"?A.push(g.customDomain):Array.isArray(g.customDomain)&&A.push(...g.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${g.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let b;return await i.runInteractiveTask({name:g.url},async()=>{let v=performance.now(),E=()=>Stu({docsWorkspace:n,customDomains:A,domain:g.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:g.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:g.audiences?Array.isArray(g.audiences)?g.audiences:[g.audiences]:void 0,docsUrl:g.url,cliVersion:p,ciSource:d,deployerAuthor:f});for(let w=0;;w++)try{b=await E();break}catch(x){if(!(x instanceof pht)||w>=mzt.length){if(x instanceof pht)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw x}let C=mzt[w]??mzt[mzt.length-1]??6e4,_=C/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${_} minute${_===1?"":"s"} (attempt ${w+1}/${mzt.length})...`),await new Promise(R=>setTimeout(R,C))}let I=performance.now()-v;i.logger.debug(`Docs publishing completed in ${I.toFixed(0)}ms`)}),b}var g8n=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new dg({context:this.context,task:this.task});try{let s=await hzt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"4.62.3"});return o.getResult()===If.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:ji(s)}}}};Tt();var fht=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
2243
2243
  `),this.stream.write(`${Ce.cyan("\u25C6")} ${Ce.bold(t.title)}
2244
2244
  `),t.subtitle!=null&&this.stream.write(` ${Ce.dim(t.subtitle)}
2245
2245
  `),this.stream.write(`
@@ -2258,7 +2258,7 @@ ${i}${Ce.dim(`... ${c} earlier logs hidden ...`)}${u}`:u}getMaxLogMessageLength(
2258
2258
 
2259
2259
  Add a 'docs:' section to your fern.yml to get started.`});let s=this.resolveInstanceUrl({instances:o.docs.raw.instances,instance:r.instance});if(!r.preview&&t.isTTY&&!r.force&&!await this.confirmPublish(s)){t.stderr.info("Docs publish cancelled.");return}let c=new aOe({context:t}).adapt(o),u=c.docsWorkspaces;if(u==null)throw new on({message:`No docs configuration found in fern.yml.
2260
2260
 
2261
- Add a 'docs:' section to your fern.yml to get started.`});let l=await iv(c),p=await this.getToken(t);await t.verifyOrgAccess({organization:o.org,token:p});let d=await this.setupTaskGroup({context:t,instanceUrl:s,org:o.org,title:n.title,stageOverrides:i}),f=d.getTask("publish");if(f==null)throw new on({message:"Internal error; task 'publish' not found"});f.start(),f.stage.validation.start();try{let g=await new cOe({context:t,task:f.getTask()}).check({workspace:o,strict:r.strict});if(g.hasErrors||r.strict&&g.hasWarnings)throw new k0e(g.violations)}catch(h){let g=ji(h);f.stage.validation.fail(g)}if(f.getTask().status!=="error"){f.stage.validation.complete(),f.stage.publish.start();let g=await new g8n({context:t,task:f.getTask(),project:c,docsWorkspace:u,ossWorkspaces:l,token:p}).publish({instanceUrl:s,preview:r.preview,skipUpload:r["skip-upload"]||void 0});if(!g.success)f.stage.publish.fail(g.error);else{f.stage.publish.complete();let A=g.url!=null?[g.url]:void 0;f.complete(A)}}if(d.finish({successMessage:n.success,errorMessage:n.error}).failedCount>0)throw on.exit()}resolveInstanceUrl({instances:t,instance:r}){if(t.length===0)throw new on({message:`No docs instances configured.
2261
+ Add a 'docs:' section to your fern.yml to get started.`});let l=await iv(c),p=await this.getToken(t);await t.verifyOrgAccess({organization:o.org,token:p});let d=await this.setupTaskGroup({context:t,instanceUrl:s,org:o.org,title:n.title,stageOverrides:i}),f=d.getTask("publish");if(f==null)throw new on({message:"Internal error; task 'publish' not found"});f.start(),f.stage.validation.start();try{let g=await new cOe({context:t,task:f.getTask()}).check({workspace:o,strict:r.strict});if(g.hasErrors||r.strict&&g.hasWarnings)throw new k0e(g.violations)}catch(h){let g=ji(h);f.stage.validation.fail(g)}if(f.getTask().status!=="error"){f.stage.validation.complete(),f.stage.publish.start();let g=await new g8n({context:t,task:f.getTask(),project:c,docsWorkspace:u,ossWorkspaces:l,token:p}).publish({instanceUrl:s,preview:r.preview,previewId:r.previewId,skipUpload:r["skip-upload"]||void 0});if(!g.success)f.stage.publish.fail(g.error);else{f.stage.publish.complete();let A=g.url!=null?[g.url]:void 0;f.complete(A)}}if(d.finish({successMessage:n.success,errorMessage:n.error}).failedCount>0)throw on.exit()}resolveInstanceUrl({instances:t,instance:r}){if(t.length===0)throw new on({message:`No docs instances configured.
2262
2262
 
2263
2263
  Add an instance to the 'docs:' section of your fern.yml.`});if(r!=null){let i=t.find(o=>o.url===r);if(i==null){let o=t.map(s=>` - ${s.url}`).join(`
2264
2264
  `);throw new on({message:`No docs instance found with URL '${r}'.
@@ -2275,7 +2275,7 @@ ${i}
2275
2275
  Use --instance <url> to select one.`})}let n=t[0];if(n==null)throw new on({message:`No docs instances configured.
2276
2276
 
2277
2277
  Add an instance to the 'docs:' section of your fern.yml.`});return n.url}async confirmPublish(t){let{confirm:r}=await Zp.prompt([{type:"confirm",name:"confirm",message:`This will affect a production site ${Ce.cyan(t)}. Are you sure you want to continue?`,default:!1}]);return r}async setupTaskGroup({context:t,instanceUrl:r,org:n,title:i,stageOverrides:o}){let s=new y8n({context:t});return s.addTask({id:"publish",name:r,stageOverrides:o}),await s.start({title:i,subtitle:`org: ${n}`}),t.onShutdown(()=>{s.finish({successMessage:i,errorMessage:`${i} interrupted`})}),s}getToken(t){if(process.env.FERN_FDR_ORIGIN!=null){let n=process.env.FERN_TOKEN;if(n==null)throw new on({message:"No organization token found. Please set the FERN_TOKEN environment variable."});return Promise.resolve({type:"organization",value:n})}return t.getTokenOrPrompt()}};function Kvo(e){let t=new gzt;Wa(e,"publish","Publish your documentation site",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Docs publish timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("force",{type:"boolean",default:!1,description:"Skip confirmation prompts"}).option("instance",{type:"string",description:"Select which docs instance to publish"}).option("strict",{type:"boolean",default:!1,description:"Treat all validation warnings (including broken links) as errors"}).option("preview",{type:"boolean",default:!1,description:"Generate a preview link instead of publishing to production",hidden:!0}))}var AFm=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Jvo=class{async handle(t,r){if(!this.isPreviewUrl(r.url))throw new on({message:`Invalid preview URL: ${r.url}
2278
- Preview URLs follow the pattern: {org}-preview-{hash}.docs.buildwithfern.com`});let n=await t.getTokenOrPrompt(),i=mR({token:n.value});t.stderr.debug(`Deleting preview site: ${r.url}`);let o=await i.docs.v2.write.deleteDocsSite({url:r.url});if(!o.ok)switch(o.error.error){case"UnauthorizedError":throw on.unauthorized("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":throw on.notFound(`Preview site not found: ${r.url}`);default:throw new on({message:`Failed to delete preview site: ${r.url}`})}t.stderr.info(Ce.green(`Successfully deleted preview site: ${r.url}`))}isPreviewUrl(t){let r=t.toLowerCase().trim();r.startsWith("https://")?r=r.slice(8):r.startsWith("http://")&&(r=r.slice(7));let n=r.indexOf("/");return n!==-1&&(r=r.slice(0,n)),AFm.test(r)}};function Yvo(e){let t=new Jvo;Wa(e,"delete <url>","Delete a preview deployment",async(r,n)=>{await t.handle(r,n)},r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}))}var Xvo=class{publishCommand=new gzt;async handle(t,r){await this.publishCommand.handle(t,{...r,preview:!0,force:!0})}};function Zvo(e){let t=new Xvo;XZc(e,"preview","Generate a preview of your documentation site",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Docs preview timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("instance",{type:"string",description:"Select which docs instance to preview"}).option("strict",{type:"boolean",default:!1,description:"Treat all validation warnings as errors"}).option("skip-upload",{type:"boolean",default:!1,description:"Skip uploading assets during preview generation"}),[Yvo])}function eIo(e){IT(e,"docs","Configure, edit, preview, and publish your documentation.",[wyo,dvo,Zvo,Kvo])}Tt();$t();var yzt=require("fs/promises"),Rtu=ve(require("path"),1);var yFm="# yaml-language-server: $schema=https://schema.buildwithfern.dev/fern-yml.json",b8n=class{build(t){let r={};for(let o of t.languages){let s=t.outputs.get(o);if(s==null)continue;let a={output:this.buildOutput(s),...s.group!=null?{group:[s.group]}:{}};r[o]=a}let n={org:t.organization,api:{specs:[this.buildSpec(t.specFormat,t.apiPath)]},sdks:{...t.defaultGroup!=null?{defaultGroup:t.defaultGroup}:{},targets:r}},i=Tr.dump(n,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1});return`${yFm}
2278
+ Preview URLs follow the pattern: {org}-preview-{hash}.docs.buildwithfern.com`});let n=await t.getTokenOrPrompt(),i=mR({token:n.value});t.stderr.debug(`Deleting preview site: ${r.url}`);let o=await i.docs.v2.write.deleteDocsSite({url:r.url});if(!o.ok)switch(o.error.error){case"UnauthorizedError":throw on.unauthorized("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":throw on.notFound(`Preview site not found: ${r.url}`);default:throw new on({message:`Failed to delete preview site: ${r.url}`})}t.stderr.info(Ce.green(`Successfully deleted preview site: ${r.url}`))}isPreviewUrl(t){let r=t.toLowerCase().trim();r.startsWith("https://")?r=r.slice(8):r.startsWith("http://")&&(r=r.slice(7));let n=r.indexOf("/");return n!==-1&&(r=r.slice(0,n)),AFm.test(r)}};function Yvo(e){let t=new Jvo;Wa(e,"delete <url>","Delete a preview deployment",async(r,n)=>{await t.handle(r,n)},r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}))}var Xvo=class{publishCommand=new gzt;async handle(t,r){await this.publishCommand.handle(t,{...r,preview:!0,previewId:r.id,force:!0})}};function Zvo(e){let t=new Xvo;XZc(e,"preview","Generate a preview of your documentation site",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Docs preview timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("instance",{type:"string",description:"Select which docs instance to preview"}).option("strict",{type:"boolean",default:!1,description:"Treat all validation warnings as errors"}).option("id",{type:"string",description:"A stable identifier for the preview. Reusing the same ID overwrites the previous preview, keeping the URL stable."}).option("skip-upload",{type:"boolean",default:!1,description:"Skip uploading assets during preview generation"}),[Yvo])}function eIo(e){IT(e,"docs","Configure, edit, preview, and publish your documentation.",[wyo,dvo,Zvo,Kvo])}Tt();$t();var yzt=require("fs/promises"),Rtu=ve(require("path"),1);var yFm="# yaml-language-server: $schema=https://schema.buildwithfern.dev/fern-yml.json",b8n=class{build(t){let r={};for(let o of t.languages){let s=t.outputs.get(o);if(s==null)continue;let a={output:this.buildOutput(s),...s.group!=null?{group:[s.group]}:{}};r[o]=a}let n={org:t.organization,api:{specs:[this.buildSpec(t.specFormat,t.apiPath)]},sdks:{...t.defaultGroup!=null?{defaultGroup:t.defaultGroup}:{},targets:r}},i=Tr.dump(n,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1});return`${yFm}
2279
2279
  ${i}`}buildSpec(t,r){return t==="asyncapi"?{asyncapi:r}:{openapi:r}}buildOutput(t){return t.type==="local"?t.path??"./sdks":{git:{repository:t.repository??"",...t.mode!=null?{mode:t.mode}:{}}}}};var Ptu=`openapi: 3.0.3
2280
2280
  info:
2281
2281
  title: Petstore API
@@ -3352,12 +3352,12 @@ generators:
3352
3352
  uri: your-org/your-sdk-repo
3353
3353
  token: \${GITHUB_TOKEN}
3354
3354
  mode: pull-request
3355
- `),H!=null){await m$n.rm(q,{recursive:!0,force:!0}),await m$n.mkdir(q,{recursive:!0}),I.logger.debug(`Self-hosted GitHub mode: cloning ${H.uri} to ${q}`);try{let{execSync:Se}=await import("child_process"),pe=Se("which git 2>/dev/null || echo 'not found'",{encoding:"utf-8"}).trim(),le=Se("git --version 2>/dev/null || echo 'unknown'",{encoding:"utf-8"}).trim();I.logger.debug(`Git environment: path=${pe}, version=${le}, PATH=${process.env.PATH??"unset"}`)}catch{I.logger.debug(`Git environment: unable to determine git info, PATH=${process.env.PATH??"unset"}`)}try{let Se=await enr({githubRepository:H.uri,installationToken:H.token,targetDirectory:q,timeoutMs:3e4}),pe=H.mode??"push";if((pe==="push"||pe==="pull-request")&&H.branch!=null){if(I.logger.debug(`Checking out branch ${H.branch} before generation`),pe==="pull-request"&&!await Se.remoteBranchExists(H.branch)){let Fe=Yx(H.uri);I.failAndThrow(`Branch ${H.branch} does not exist in repository ${Fe.owner}/${Fe.repo}`)}await Se.checkoutRemoteBranch(H.branch)}}catch(Se){I.failAndThrow(`Failed to clone GitHub repository ${H.uri}: ${ji(Se)}`)}}let ye;E.raw?.snippets?.path!=null&&(ye=Gt.of(Ye(r.absoluteFilePath,Be.of(E.raw.snippets.path)))),ye==null&&H!=null&&(ye=Gt.of((await f$n()).path+"/snippet.json"));let Ee=await f$n(),{shouldCommit:Z,autoVersioningCommitMessage:te,autoVersioningChangelogEntry:be,autoVersioningPrDescription:Ae,autoVersioningVersionBumpReason:Te}=await m9n({organization:t.organization,absolutePathToFernConfig:r.generatorsConfiguration?.absolutePathToConfiguration??t._absolutePath,workspace:C,generatorInvocation:E,absolutePathToLocalOutput:q,absolutePathToLocalSnippetJSON:ye,absolutePathToLocalSnippetTemplateJSON:void 0,version:i,audiences:n.audiences,workspaceTempDir:Ee,keepDocker:o,context:I,irVersionOverride:E.irVersionOverride,outputVersionOverride:i,writeUnitTests:!0,generateOauthClients:z.ok?z?.body.oauthClientEnabled??!1:!1,generatePaginatedClients:z.ok?z?.body.paginationEnabled??!1:!1,includeOptionalRequestPropertyExamples:!1,inspect:s,executionEnvironment:void 0,ir:G,whiteLabel:z.ok?z.body.isWhitelabled:!1,publishToRegistry:g,runner:u,ai:l,autoVersioningCache:b,absolutePathToSpecRepo:Bn(r.absoluteFilePath),skipFernignore:h});if(I.logger.info(Ce.green("Wrote files to "+q)),H!=null&&Z){let Se={debug:Fe=>I.logger.debug(Fe),info:Fe=>I.logger.info(Fe),warn:Fe=>I.logger.warn(Fe),error:Fe=>I.logger.error(Fe)},le=await new d$n.PostGenerationPipeline({outputDir:q,replay:{enabled:p?.enabled===!0,skipApplication:d,stageOnly:!1},github:{enabled:!0,uri:H.uri,token:H.token,mode:H.mode??"push",branch:H.branch,commitMessage:te,changelogEntry:be,prDescription:Ae,versionBumpReason:Te,previewMode:H.previewMode,generatorName:E.name},cliVersion:r.cliVersion??"unknown",generatorVersions:{[E.name]:E.version},generatorName:E.name},Se).run();le.steps.replay!=null&&(0,d$n.logReplaySummary)(le.steps.replay,{debug:Fe=>I.logger.debug(Fe),info:Fe=>I.logger.info(Ce.cyan(Fe)),warn:Fe=>I.logger.warn(Ce.yellow(Fe)),error:Fe=>I.logger.error(Ce.red(Fe))}),le.success||I.failAndThrow(`Post-generation pipeline failed: ${le.errors?.join(", ")}`)}})))).some(E=>!E)&&a.failAndThrow()}function QTh(e,t){if(e==null)return;let n=(t.name.split("/").pop()??"sdk").replace(/[^a-zA-Z0-9-_]/g,"_");return e?Ye(e,Be.of(n)):void 0}async function f$n(){return mLo.default.dir({tmpdir:dLo.default.platform()==="darwin"?lIu.default.join("/private",dLo.default.tmpdir()):void 0,prefix:"fern"})}function MTh({generatorInvocation:e,org:t,version:r,packageName:n,context:i}){if(e.raw?.github!=null&&pIu(e.raw.github)){let o=Yx(e.raw.github.uri),s=e.raw.github.mode==="pull-request"?"pull-request":void 0;return Ht.PublishingConfig.github({owner:o.owner,repo:o.repo,uri:e.raw.github.uri,token:e.raw.github.token,mode:s,branch:e.raw.github.branch,target:LTh({outputSchema:e.raw.output,version:r,packageName:n})})}if(e.raw?.output?.location==="local-file-system"){let o;if(e.language==="python")o=wv.pypi({version:r,packageName:n}),i.logger.debug(`Created PyPiPublishTarget: version ${r} package name: ${n}`);else if(e.language==="rust")o=wv.crates({version:r,packageName:n}),i.logger.debug(`Created CratesPublishTarget: version ${r} package name: ${n}`);else if(e.language==="java"){let s=e.raw?.config,a=(()=>{if(!s||typeof s!="object"||s===null)return;let u=s;if(typeof u.group=="string"&&typeof u.artifact=="string")return{groupId:u.group,artifactId:u.artifact};if(typeof u["package-prefix"]=="string"&&n)return{groupId:u["package-prefix"],artifactId:n};typeof u["package-prefix"]=="string"&&!n&&i.logger.warn("Java generator has package-prefix configured but packageName is missing")})(),c=a?`${a.groupId}:${a.artifactId}`:void 0;if(c){let u=r??"0.0.0";o=wv.maven({coordinate:c,version:u,usernameEnvironmentVariable:"MAVEN_USERNAME",passwordEnvironmentVariable:"MAVEN_PASSWORD",mavenUrlEnvironmentVariable:"MAVEN_PUBLISH_REGISTRY_URL"}),i.logger.debug(`Created MavenPublishTarget: coordinate ${c} version ${u}`)}else s&&typeof s=="object"&&i.logger.debug("Java generator config provided but could not construct Maven coordinate. Expected either 'group' and 'artifact' or 'package-prefix' with packageName.")}return Ht.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:o})}return e.outputMode._visit({downloadFiles:()=>Ht.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:void 0}),github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:()=>{},_other:()=>{}})}function LTh({outputSchema:e,version:t,packageName:r}){let n=Ht.PublishTarget.postman({apiKey:"",workspaceId:"",collectionId:void 0});if(e==null)return n;if(e.location==="npm"){let i=(e.token||"${NPM_TOKEN}").trim(),o=i==="<USE_OIDC>"||i==="OIDC";return wv.npm({packageName:e["package-name"],version:t??"0.0.0",tokenEnvironmentVariable:o?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""})}else return e.location==="maven"?wv.maven({version:t??"0.0.0",coordinate:e.coordinate,usernameEnvironmentVariable:e.username||"MAVEN_USERNAME",passwordEnvironmentVariable:e.password||"MAVEN_PASSWORD",mavenUrlEnvironmentVariable:e.url||"MAVEN_PUBLISH_REGISTRY_URL"}):e.location==="pypi"?wv.pypi({version:t,packageName:r}):n}function pIu(e){return e==null?!1:"uri"in e&&"token"in e}var UTh={defaultEndpoint:void 0,bannerLink:void 0,introduction:void 0,apiReferenceLink:void 0,apiName:void 0,disabledFeatures:void 0,whiteLabel:void 0,customSections:void 0,features:void 0,exampleStyle:void 0};function zTh(e,t){if(e.raw?.github!=null&&pIu(e.raw.github))return{...e.raw.github,previewMode:t}}var _Vt=class{executionEnvironment;constructor(t){this.executionEnvironment=t}async run({organization:t,absolutePathToFernConfig:r,workspace:n,generatorGroup:i,context:o,irVersionOverride:s,outputVersionOverride:a,shouldGenerateDynamicSnippetTests:c,skipUnstableDynamicSnippetTests:u,inspect:l,skipFernignore:p,skipAutogenerationIfManualExamplesExist:d}){let f=await Promise.all(i.generators.map(async m=>o.runInteractiveTask({name:m.name},async h=>{if(m.absolutePathToLocalOutput==null){h.failWithoutThrowing("Cannot generate because output location is not local-file-system");return}try{let{ir:g,generatorConfig:A}=await this.executeGenerator({generatorGroup:i,generatorInvocation:m,context:h,workspace:n,organization:t,irVersionOverride:s,outputVersionOverride:a,absolutePathToFernConfig:r,inspect:l,skipFernignore:p,skipAutogenerationIfManualExamplesExist:d});h.logger.info(Ce.green("Wrote files to "+m.absolutePathToLocalOutput)),c&&m.language!=null?(h.logger.info(`Generating dynamic snippet tests for ${m.language}...`),await Ylu({context:h,ir:g,config:A,language:m.language,outputDir:m.absolutePathToLocalOutput,skipUnstable:u})):h.logger.info(`Skipping dynamic snippet tests; shouldGenerateDynamicSnippetTests: ${c}, language: ${m.language}`)}catch(g){g instanceof Jm||(g instanceof SG?h.failWithoutThrowing(`Generation failed: ${g.log}`,g):h.failWithoutThrowing(`Generation failed: ${g instanceof Error?g.message:"Unknown error"}`,g))}})))}async executeGenerator({generatorGroup:t,generatorInvocation:r,context:n,workspace:i,organization:o,irVersionOverride:s,outputVersionOverride:a,absolutePathToFernConfig:c,inspect:u,skipFernignore:l,skipAutogenerationIfManualExamplesExist:p}){if(n.logger.info(`Starting generation for ${r.name}`),r.absolutePathToLocalOutput==null)throw new Error("Output path is required for generation");let d=cg({workspace:i,audiences:t.audiences,generationLanguage:r.language,keywords:r.keywords,smartCasing:r.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:!0,disabled:r.disableExamples,skipAutogenerationIfManualExamplesExist:p??!1},readme:r.readme,version:a,packageName:Dn.getPackageName({generatorInvocation:r}),context:n,sourceResolver:new nh(n,i),generationMetadata:{cliVersion:i.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:bH()}}),f=await f$n();return m9n({organization:o,absolutePathToFernConfig:c,workspace:i,generatorInvocation:r,absolutePathToLocalOutput:r.absolutePathToLocalOutput,absolutePathToLocalSnippetJSON:r.absolutePathToLocalOutput?Gt.of(Ye(r.absolutePathToLocalOutput,Be.of(qnr))):void 0,absolutePathToLocalSnippetTemplateJSON:void 0,audiences:t.audiences,workspaceTempDir:f,version:a,keepDocker:!1,context:n,irVersionOverride:s,outputVersionOverride:a,writeUnitTests:!0,generateOauthClients:!0,generatePaginatedClients:!0,includeOptionalRequestPropertyExamples:!0,inspect:u,executionEnvironment:this.executionEnvironment,ir:d,runner:void 0,ai:i.generatorsConfiguration?.ai,absolutePathToSpecRepo:void 0,skipFernignore:l})}};var dIu=require("fs/promises");Tt();$t();yH();var yb=ve(tZ(),1),fIu=require("fs/promises"),gyt=class{context;constructor(t){this.context=t.context}async adapt(t){return{raw:this.buildRaw(t),name:t.image,containerImage:t.registry?`${t.registry}/${rNe(t.image)}`:void 0,version:t.version,config:t.config,language:this.mapLanguage(t.lang),outputMode:await this.buildOutputMode(t),absolutePathToLocalOutput:this.context.resolveOutputFilePath(t.output.path),smartCasing:t.smartCasing??!0,readme:this.buildReadme(t),absolutePathToLocalSnippets:void 0,disableExamples:!1,irVersionOverride:void 0,keywords:void 0,publishMetadata:void 0,settings:void 0}}buildRaw(t){let r=t.output.git;if(!(r==null||!Xv.isGitOutputSelfHosted(r)))return{name:t.image,version:t.version,github:{uri:r.uri,token:r.token,mode:this.mapSelfHostedMode(r.mode),branch:r.branch}}}mapSelfHostedMode(t){if(t==null)return Dn.GithubSelfhostedMode.PullRequest;switch(t){case"pr":return Dn.GithubSelfhostedMode.PullRequest;case"push":return Dn.GithubSelfhostedMode.Push;default:we(t)}}async buildOutputMode(t){if(t.output.git!=null){let r=t.output.git;return Xv.isGitOutputSelfHosted(r)?await this.buildGitSelfHostedOutputMode({target:t,git:r}):await this.buildGitHubRepositoryOutputMode({target:t,git:r})}return yb.FernFiddle.remoteGen.OutputMode.downloadFiles({})}async buildGitHubRepositoryOutputMode({target:t,git:r}){let n=Yx(r.repository),i=r.license!=null?await this.convertLicense(r.license):void 0,o=t.publish!=null?this.buildPublishInfo(t.publish):void 0,s=this.buildReviewers(r.reviewers),a=r.mode??"pr";switch(a){case"pr":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.pullRequest({owner:n.owner,repo:n.repo,license:i,publishInfo:o,reviewers:s,downloadSnippets:void 0}));case"release":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.commitAndRelease({owner:n.owner,repo:n.repo,license:i,publishInfo:o,downloadSnippets:void 0}));case"push":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.push({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o,downloadSnippets:void 0}));default:we(a)}}async buildGitSelfHostedOutputMode({target:t,git:r}){let n=Yx(r.uri),i=r.license!=null?await this.convertLicense(r.license):void 0,o=t.publish!=null?this.buildPublishInfo(t.publish):void 0,s=r.mode??"pr";switch(s){case"pr":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.pullRequest({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o}));case"push":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.push({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o}));default:we(s)}}buildPublishInfo(t){if(t.npm!=null)return this.buildNpmPublishInfo(t.npm);if(t.pypi!=null)return this.buildPypiPublishInfo(t.pypi);if(t.maven!=null)return this.buildMavenPublishInfo(t.maven);if(t.nuget!=null)return this.buildNugetPublishInfo(t.nuget);if(t.rubygems!=null)return this.buildRubygemsPublishInfo(t.rubygems);if(t.crates!=null)return this.buildCratesPublishInfo(t.crates)}buildNpmPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.npm({registryUrl:t.url??"https://registry.npmjs.org",packageName:t.packageName,token:t.token})}buildPypiPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.pypi({registryUrl:t.url??"https://upload.pypi.org/legacy/",packageName:t.packageName,credentials:t.token!=null?{username:"__token__",password:t.token}:t.username!=null&&t.password!=null?{username:t.username,password:t.password}:void 0,pypiMetadata:t.metadata!=null?{keywords:t.metadata.keywords,documentationLink:t.metadata.documentationLink,homepageLink:t.metadata.homepageLink}:void 0})}buildMavenPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.maven({registryUrl:t.url??"https://s01.oss.sonatype.org/content/repositories/releases/",coordinate:t.coordinate,credentials:t.username!=null&&t.password!=null?{username:t.username,password:t.password}:void 0,signature:t.signature!=null?{keyId:t.signature.keyId,password:t.signature.password,secretKey:t.signature.secretKey}:void 0})}buildNugetPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.nuget({registryUrl:t.url??"https://nuget.org/",packageName:t.packageName,apiKey:t.apiKey})}buildRubygemsPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.rubygems({registryUrl:t.url??"https://rubygems.org/",packageName:t.packageName,apiKey:t.apiKey})}buildCratesPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.crates({registryUrl:t.url??"https://crates.io/api/v1/crates",packageName:t.packageName,token:t.token})}buildReviewers(t){if(t==null)return;let r=[];if(t.teams!=null)for(let n of t.teams)r.push(yb.FernFiddle.GithubPullRequestReviewer.team({name:n}));if(t.users!=null)for(let n of t.users)r.push(yb.FernFiddle.GithubPullRequestReviewer.user({name:n}));return r.length>0?r:void 0}async convertLicense(t){if(t==="MIT")return yb.FernFiddle.GithubLicense.basic({id:yb.FernFiddle.GithubLicenseId.Mit});if(t==="Apache-2.0")return yb.FernFiddle.GithubLicense.basic({id:yb.FernFiddle.GithubLicenseId.Apache});let r=Ye(this.context.cwd,Be.of(t));if(!await sr(r,"file"))throw new Error(`Custom license file "${r}" does not exist; did you mean to use either MIT or Apache-2.0?`);let n=await(0,fIu.readFile)(r,"utf-8");return yb.FernFiddle.GithubLicense.custom({contents:n})}buildReadme(t){let r=t.readme;if(r==null)return;let n={};return r.bannerLink!=null&&(n.bannerLink=r.bannerLink),r.introduction!=null&&(n.introduction=r.introduction),r.apiReferenceLink!=null&&(n.apiReferenceLink=r.apiReferenceLink),r.apiName!=null&&(n.apiName=r.apiName),r.disabledSections!=null&&(n.disabledSections=r.disabledSections),r.defaultEndpoint!=null&&(n.defaultEndpoint=r.defaultEndpoint),r.features!=null&&(n.features=r.features),r.customSections!=null&&(n.customSections=r.customSections.map(i=>({title:i.title,language:i.language??t.lang,content:i.content}))),r.exampleStyle!=null&&(n.exampleStyle=r.exampleStyle),n}mapLanguage(t){return{typescript:Dn.GenerationLanguage.TYPESCRIPT,python:Dn.GenerationLanguage.PYTHON,java:Dn.GenerationLanguage.JAVA,go:Dn.GenerationLanguage.GO,ruby:Dn.GenerationLanguage.RUBY,csharp:Dn.GenerationLanguage.CSHARP,swift:Dn.GenerationLanguage.SWIFT,php:Dn.GenerationLanguage.PHP,rust:Dn.GenerationLanguage.RUST}[t.toLowerCase()]}};$t();var h$n=require("path");function g$n({context:e,task:t,target:r,preview:n,outputPath:i}){if(n)return[(i!=null?(0,h$n.resolve)(e.cwd,i):(0,h$n.join)(e.cwd,Be.of(".fern/preview"))).toString()];let o=VTh(t);if(o!=null){if(o.pullRequestUrl!=null)return[o.pullRequestUrl];if(o.releaseUrl!=null)return[o.releaseUrl];if(o.branchUrl!=null)return[o.branchUrl]}return e.resolveTargetOutputs(r)}function VTh(e){let t={};for(let r of e.logs??[]){let n=r.message.match(/Created pull request: (.+)/);n!=null&&(t.pullRequestUrl=n[1]);let i=r.message.match(/Created commit (\w+)/);i!=null&&(t.commitHash=i[1]);let o=r.message.match(/Pushed branch: (.+)/);o!=null&&(t.branchUrl=o[1]);let s=r.message.match(/Release tagged\. View here: (.+)/);s!=null&&(t.releaseUrl=s[1])}return Object.keys(t).length>0?t:void 0}var A$n=class{context;cliVersion;invocationAdapter;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion,this.invocationAdapter=new gyt({context:this.context})}async run(t){let r=new dg({context:this.context,task:t.task,logLevel:ei.Info});try{let n=await this.invocationAdapter.adapt(t.target),i={groupName:t.target.name,audiences:t.audiences??{type:"all"},generators:[n],reviewers:void 0},s=await new x1e({context:this.context,cliVersion:this.cliVersion,task:t.task}).adapt(t.apiDefinition);return t.target.output.git!=null&&Xv.isGitOutputSelfHosted(t.target.output.git)?await this.runSelfHostedGeneration({args:t,taskContext:r,fernWorkspace:s,generatorGroup:i}):await this.runLocalGeneration({args:t,taskContext:r,fernWorkspace:s,generatorGroup:i,generatorInvocation:n})}catch(n){return r.getResult()===If.Failure?{success:!1}:{success:!1,error:ji(n)}}}async runSelfHostedGeneration({args:t,taskContext:r,fernWorkspace:n,generatorGroup:i}){let o={_absolutePath:Ye(this.context.cwd,Be.of("fern.config.json")),rawConfig:{organization:t.organization,version:this.cliVersion},organization:t.organization,version:this.cliVersion};return await hyt({token:t.token,projectConfig:o,workspace:n,generatorGroup:i,version:t.version,keepDocker:t.keepContainer??!1,context:r,runner:t.containerEngine,absolutePathToPreview:void 0,inspect:!1,ai:void 0,skipFernignore:t.skipFernignore}),r.getResult()===If.Failure?{success:!1}:{success:!0,output:g$n({context:this.context,task:t.task,target:t.target,preview:t.preview,outputPath:t.outputPath})}}async runLocalGeneration({args:t,taskContext:r,fernWorkspace:n,generatorGroup:i,generatorInvocation:o}){let a=`${t.target.registry?`${t.target.registry}/${rNe(t.target.image)}`:t.target.image}:${t.target.version}`,c=new iUe({containerImage:a,keepContainer:t.keepContainer??!1,runner:t.containerEngine});if(await new _Vt(c).run({organization:t.organization,workspace:n,generatorGroup:i,context:r,outputVersionOverride:t.version,ai:t.ai,absolutePathToFernConfig:void 0,irVersionOverride:void 0,shouldGenerateDynamicSnippetTests:!1,skipUnstableDynamicSnippetTests:!0,inspect:!1,skipFernignore:t.skipFernignore}),t.target.output.path!=null&&o.absolutePathToLocalOutput!=null){let l=Ye(o.absolutePathToLocalOutput,Be.of(qnr));await(0,dIu.rm)(l,{force:!0})}return r.getResult()===If.Failure?{success:!1}:{success:!0,output:this.context.resolveTargetOutputs(t.target)}}};Tt();$t();var yze=require("fs/promises"),mIu=require("os");var y$n=class{context;cliVersion;invocationAdapter;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion,this.invocationAdapter=new gyt({context:this.context})}async run(t){let r=new dg({context:this.context,task:t.task,logLevel:ei.Info});try{let n=await this.invocationAdapter.adapt(t.target),i={groupName:t.target.name,audiences:t.audiences??{type:"all"},generators:[n],reviewers:void 0},s=await new x1e({context:this.context,cliVersion:this.cliVersion,task:t.task}).adapt(t.apiDefinition),a=await this.getAbsolutePathToPreview(t);if(await pzt({projectConfig:this.getProjectConfig(t),organization:t.organization,workspace:s,context:r,generatorGroup:i,version:t.version,shouldLogS3Url:t.shouldLogS3Url??!1,token:t.token,mode:this.mapMode(t.target),fernignorePath:t.fernignorePath,skipFernignore:t.skipFernignore,absolutePathToPreview:a,whitelabel:void 0,dynamicIrOnly:!1,retryRateLimited:!1,requireEnvVars:!0}),this.isLocalGitCombo(t)&&a!=null){let c=TT(n.name),u=Ye(a,Be.of(c)),l=n.absolutePathToLocalOutput;l!=null&&(await(0,yze.cp)(u,l,{recursive:!0}),await(0,yze.rm)(Ye(l,Be.of(".git")),{recursive:!0,force:!0})),await(0,yze.rm)(a,{recursive:!0,force:!0})}return r.getResult()===If.Failure?{success:!1}:{success:!0,output:g$n({context:this.context,task:t.task,target:t.target,preview:t.preview,outputPath:t.outputPath})}}catch(n){return r.getResult()===If.Failure?{success:!1}:{success:!1,error:ji(n)}}}async getAbsolutePathToPreview(t){if(this.isLocalGitCombo(t)){let r=await(0,yze.mkdtemp)(Ye(Gt.of((0,mIu.tmpdir)()),Be.of("fern-preview-")));return Gt.of(r)}if(t.preview)return t.outputPath!=null?fo(this.context.cwd,t.outputPath):Ye(this.context.cwd,Be.of(".fern/preview"))}getProjectConfig(t){return{_absolutePath:Ye(this.context.cwd,Be.of("fern.config.json")),rawConfig:{organization:t.organization,version:this.cliVersion},organization:t.organization,version:this.cliVersion}}mapMode(t){if(t.output.git!=null)return t.output.git.mode==="pr"?"pull-request":void 0}isLocalGitCombo(t){return t.target.output.path!=null&&t.target.output.git!=null&&!t.preview}};var b$n=class{context;cliVersion;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion}async run(t){try{if(this.isLocalGeneration(t))return await this.runLocalGeneration(t);if(t.target.registry!=null)throw new on({message:`Custom image configurations are only supported with local generation (--local). Target "${t.target.name}" uses a custom image registry.`});return await this.runRemoteGeneration(t)}catch(r){let n=ji(r);return{success:!1,target:t.target,error:n}}}async runLocalGeneration(t){let n=await new A$n({context:this.context,cliVersion:this.cliVersion}).run({task:t.task,target:t.target,apiDefinition:t.apiDefinition,organization:t.organization,ai:t.ai,audiences:t.audiences,version:t.version,keepContainer:t.keepContainer,preview:t.preview,outputPath:t.outputPath,containerEngine:t.containerEngine,token:t.token,skipFernignore:t.skipFernignore});return n.success?{success:!0,target:t.target,output:n.output}:{success:!1,target:t.target,error:n.error}}async runRemoteGeneration(t){if(t.token==null)throw on.authRequired();let n=await new y$n({context:this.context,cliVersion:this.cliVersion}).run({target:t.target,apiDefinition:t.apiDefinition,organization:t.organization,token:t.token,task:t.task,ai:t.ai,audiences:t.audiences,version:t.version,shouldLogS3Url:t.shouldLogS3Url,preview:t.preview,outputPath:t.outputPath,fernignorePath:t.fernignorePath,skipFernignore:t.skipFernignore});return n.success?{success:!0,target:t.target,output:n.output}:{success:!1,target:t.target,error:n.error}}isLocalGeneration(t){return t.runtime==="local"||t.target.output.git!=null&&Xv.isGitOutputSelfHosted(t.target.output.git)}};var E$n=class{id;taskGroup;stage;constructor({id:t,taskGroup:r}){this.id=t,this.taskGroup=r,this.stage={validation:new Bde({taskId:t,taskGroup:r,stageId:"validation"}),generator:new Bde({taskId:t,taskGroup:r,stageId:"generator"}),output:new Bde({taskId:t,taskGroup:r,stageId:"output"})}}getTask(){let t=this.taskGroup.getTask(this.id);if(t==null)throw new Error(`Internal error; task '${this.id}' does not exist`);return t}start(t){this.taskGroup.updateTask({id:this.id,update:{status:"running",currentStep:t}})}complete(t){this.taskGroup.updateTask({id:this.id,update:{status:"success",output:t}})}fail(t){this.taskGroup.updateTask({id:this.id,update:{status:"error",error:t}})}};var v$n=class{taskGroup;tasks={};defaultStages=[{id:"validation",labels:{pending:"Validate API",running:"Validating API...",success:"Validated API"}},{id:"generator",labels:{pending:"Run generator",running:"Running generator...",success:"Generator completed"}},{id:"output",labels:{pending:"Write output",running:"Writing output...",success:"Wrote output"}}];constructor({context:t}){this.tasks={},this.taskGroup=new fht({context:t})}addTask({id:t,name:r,stageOverrides:n}){let i=r??t;this.taskGroup.addTask({id:t,name:i});let o=this.buildStages(n);this.taskGroup.setStages(t,o);let s=new E$n({taskGroup:this.taskGroup,id:t});return this.tasks[t]=s,s}getTask(t){return this.tasks[t]}async start(t){await this.taskGroup.start(t)}finish({successMessage:t,errorMessage:r}){return this.taskGroup.complete({successMessage:t,errorMessage:r})}buildStages(t){return t==null?this.defaultStages:this.defaultStages.map(r=>{let n=t[r.id];return n==null?r:{...r,labels:{...r.labels,...n}}})}};$t();var I$n=class{context;constructor({context:t}){this.context=t}async build({org:t,lang:r,resolvedSpec:n,output:i,targetVersion:o}){let s=aLr({lang:r,version:o}),a=Be.of(Ea(this.context.cwd,n.absoluteFilePath)),c=new X5({absoluteFilePath:n.absoluteFilePath,relativeFilePath:a,line:1,column:1}),u={name:r,api:Uet,image:s.image,registry:void 0,lang:r,version:s.tag,sourceLocation:c,output:Xv.resolveOutputObjectSchema(i)};return{apis:{[Uet]:{specs:[n.spec]}},cliVersion:"*",org:t,sdks:{org:t,targets:[u]}}}};var SVt=class{async handle(t,r){let n=await t.loadWorkspace();if(n==null)return this.handleWithFlags(t,r);if(!n.success)throw new aL(n.issues);return this.handleWithWorkspace(t,n.workspace,r)}async handleWithWorkspace(t,r,n){let i=r;if(n.api!=null){let a=await new bzt({context:t}).resolve({reference:n.api}),c={};for(let u of Object.keys(i.apis))c[u]={specs:[a.spec]};i={...i,apis:c}}n.org!=null&&(i={...i,org:n.org});let o=this.getTargets({workspace:i,args:n,groupName:n.target!=null?void 0:n.group??i.sdks?.defaultGroup});this.validateArgs({workspace:i,args:n,targets:o}),await this.runGeneration({context:t,workspace:i,targets:o,args:n,forceLocal:!1})}async handleWithFlags(t,r){let n=[];if(r.api==null&&n.push("--api <path|url> Path or URL to an API spec file (e.g. ./openapi.yaml)"),r.target==null&&n.push("--target <language> The SDK language to generate (e.g. typescript)"),r.org==null&&n.push("--org <name> Your organization name (e.g. acme)"),r.output==null&&n.push("--output <path|url> Output path or git URL (e.g. ./my-sdk)"),r.group!=null&&n.push("remove --group Groups are not supported without a fern.yml"),n.length>0)throw new on({message:`No fern.yml found, either run 'fern init' or specify all of the required flags:
3355
+ `),H!=null){await m$n.rm(q,{recursive:!0,force:!0}),await m$n.mkdir(q,{recursive:!0}),I.logger.debug(`Self-hosted GitHub mode: cloning ${H.uri} to ${q}`);try{let{execSync:Se}=await import("child_process"),pe=Se("which git 2>/dev/null || echo 'not found'",{encoding:"utf-8"}).trim(),le=Se("git --version 2>/dev/null || echo 'unknown'",{encoding:"utf-8"}).trim();I.logger.debug(`Git environment: path=${pe}, version=${le}, PATH=${process.env.PATH??"unset"}`)}catch{I.logger.debug(`Git environment: unable to determine git info, PATH=${process.env.PATH??"unset"}`)}try{let Se=await enr({githubRepository:H.uri,installationToken:H.token,targetDirectory:q,timeoutMs:3e4}),pe=H.mode??"push";if((pe==="push"||pe==="pull-request")&&H.branch!=null){if(I.logger.debug(`Checking out branch ${H.branch} before generation`),pe==="pull-request"&&!await Se.remoteBranchExists(H.branch)){let Fe=Yx(H.uri);I.failAndThrow(`Branch ${H.branch} does not exist in repository ${Fe.owner}/${Fe.repo}`)}await Se.checkoutRemoteBranch(H.branch)}}catch(Se){I.failAndThrow(`Failed to clone GitHub repository ${H.uri}: ${ji(Se)}`)}}let ye;E.raw?.snippets?.path!=null&&(ye=Gt.of(Ye(r.absoluteFilePath,Be.of(E.raw.snippets.path)))),ye==null&&H!=null&&(ye=Gt.of((await f$n()).path+"/snippet.json"));let Ee=await f$n(),{shouldCommit:Z,autoVersioningCommitMessage:te,autoVersioningChangelogEntry:be,autoVersioningPrDescription:Ae,autoVersioningVersionBumpReason:Te}=await m9n({organization:t.organization,absolutePathToFernConfig:r.generatorsConfiguration?.absolutePathToConfiguration??t._absolutePath,workspace:C,generatorInvocation:E,absolutePathToLocalOutput:q,absolutePathToLocalSnippetJSON:ye,absolutePathToLocalSnippetTemplateJSON:void 0,version:i,audiences:n.audiences,workspaceTempDir:Ee,keepDocker:o,context:I,irVersionOverride:E.irVersionOverride,outputVersionOverride:i,writeUnitTests:!0,generateOauthClients:z.ok?z?.body.oauthClientEnabled??!1:!1,generatePaginatedClients:z.ok?z?.body.paginationEnabled??!1:!1,includeOptionalRequestPropertyExamples:!1,inspect:s,executionEnvironment:void 0,ir:G,whiteLabel:z.ok?z.body.isWhitelabled:!1,publishToRegistry:g,runner:u,ai:l,autoVersioningCache:b,absolutePathToSpecRepo:Bn(r.absoluteFilePath),skipFernignore:h});if(I.logger.info(Ce.green("Wrote files to "+q)),H!=null&&Z){let Se={debug:Fe=>I.logger.debug(Fe),info:Fe=>I.logger.info(Fe),warn:Fe=>I.logger.warn(Fe),error:Fe=>I.logger.error(Fe)},le=await new d$n.PostGenerationPipeline({outputDir:q,replay:{enabled:p?.enabled===!0,skipApplication:d,stageOnly:!1},github:{enabled:!0,uri:H.uri,token:H.token,mode:H.mode??"push",branch:H.branch,commitMessage:te,changelogEntry:be,prDescription:Ae,versionBumpReason:Te,previewMode:H.previewMode,generatorName:E.name},cliVersion:r.cliVersion??"unknown",generatorVersions:{[E.name]:E.version},generatorName:E.name},Se).run();le.steps.replay!=null&&(0,d$n.logReplaySummary)(le.steps.replay,{debug:Fe=>I.logger.debug(Fe),info:Fe=>I.logger.info(Ce.cyan(Fe)),warn:Fe=>I.logger.warn(Ce.yellow(Fe)),error:Fe=>I.logger.error(Ce.red(Fe))}),le.success||I.failAndThrow(`Post-generation pipeline failed: ${le.errors?.join(", ")}`)}})))).some(E=>!E)&&a.failAndThrow()}function QTh(e,t){if(e==null)return;let n=(t.name.split("/").pop()??"sdk").replace(/[^a-zA-Z0-9-_]/g,"_");return e?Ye(e,Be.of(n)):void 0}async function f$n(){return mLo.default.dir({tmpdir:dLo.default.platform()==="darwin"?lIu.default.join("/private",dLo.default.tmpdir()):void 0,prefix:"fern"})}function MTh({generatorInvocation:e,org:t,version:r,packageName:n,context:i}){if(e.raw?.github!=null&&pIu(e.raw.github)){let o=Yx(e.raw.github.uri),s=e.raw.github.mode==="pull-request"?"pull-request":void 0;return Ht.PublishingConfig.github({owner:o.owner,repo:o.repo,uri:e.raw.github.uri,token:e.raw.github.token,mode:s,branch:e.raw.github.branch,target:LTh({outputSchema:e.raw.output,version:r,packageName:n})})}if(e.raw?.output?.location==="local-file-system"){let o;if(e.language==="python")o=wv.pypi({version:r,packageName:n}),i.logger.debug(`Created PyPiPublishTarget: version ${r} package name: ${n}`);else if(e.language==="rust")o=wv.crates({version:r,packageName:n}),i.logger.debug(`Created CratesPublishTarget: version ${r} package name: ${n}`);else if(e.language==="java"){let s=e.raw?.config,a=(()=>{if(!s||typeof s!="object"||s===null)return;let u=s;if(typeof u.group=="string"&&typeof u.artifact=="string")return{groupId:u.group,artifactId:u.artifact};if(typeof u["package-prefix"]=="string"&&n)return{groupId:u["package-prefix"],artifactId:n};typeof u["package-prefix"]=="string"&&!n&&i.logger.warn("Java generator has package-prefix configured but packageName is missing")})(),c=a?`${a.groupId}:${a.artifactId}`:void 0;if(c){let u=r??"0.0.0";o=wv.maven({coordinate:c,version:u,usernameEnvironmentVariable:"MAVEN_USERNAME",passwordEnvironmentVariable:"MAVEN_PASSWORD",mavenUrlEnvironmentVariable:"MAVEN_PUBLISH_REGISTRY_URL"}),i.logger.debug(`Created MavenPublishTarget: coordinate ${c} version ${u}`)}else s&&typeof s=="object"&&i.logger.debug("Java generator config provided but could not construct Maven coordinate. Expected either 'group' and 'artifact' or 'package-prefix' with packageName.")}return Ht.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:o})}return e.outputMode._visit({downloadFiles:()=>Ht.PublishingConfig.filesystem({generateFullProject:t?.selfHostedSdKs??!1,publishTarget:void 0}),github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:()=>{},_other:()=>{}})}function LTh({outputSchema:e,version:t,packageName:r}){let n=Ht.PublishTarget.postman({apiKey:"",workspaceId:"",collectionId:void 0});if(e==null)return n;if(e.location==="npm"){let i=(e.token||"${NPM_TOKEN}").trim(),o=i==="<USE_OIDC>"||i==="OIDC";return wv.npm({packageName:e["package-name"],version:t??"0.0.0",tokenEnvironmentVariable:o?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""})}else return e.location==="maven"?wv.maven({version:t??"0.0.0",coordinate:e.coordinate,usernameEnvironmentVariable:e.username||"MAVEN_USERNAME",passwordEnvironmentVariable:e.password||"MAVEN_PASSWORD",mavenUrlEnvironmentVariable:e.url||"MAVEN_PUBLISH_REGISTRY_URL"}):e.location==="pypi"?wv.pypi({version:t,packageName:r}):n}function pIu(e){return e==null?!1:"uri"in e&&"token"in e}var UTh={defaultEndpoint:void 0,bannerLink:void 0,introduction:void 0,apiReferenceLink:void 0,apiName:void 0,disabledFeatures:void 0,whiteLabel:void 0,customSections:void 0,features:void 0,exampleStyle:void 0};function zTh(e,t){if(e.raw?.github!=null&&pIu(e.raw.github))return{...e.raw.github,previewMode:t}}var _Vt=class{executionEnvironment;constructor(t){this.executionEnvironment=t}async run({organization:t,absolutePathToFernConfig:r,workspace:n,generatorGroup:i,context:o,irVersionOverride:s,outputVersionOverride:a,shouldGenerateDynamicSnippetTests:c,skipUnstableDynamicSnippetTests:u,inspect:l,skipFernignore:p,skipAutogenerationIfManualExamplesExist:d}){let f=await Promise.all(i.generators.map(async m=>o.runInteractiveTask({name:m.name},async h=>{if(m.absolutePathToLocalOutput==null){h.failWithoutThrowing("Cannot generate because output location is not local-file-system");return}try{let{ir:g,generatorConfig:A}=await this.executeGenerator({generatorGroup:i,generatorInvocation:m,context:h,workspace:n,organization:t,irVersionOverride:s,outputVersionOverride:a,absolutePathToFernConfig:r,inspect:l,skipFernignore:p,skipAutogenerationIfManualExamplesExist:d});h.logger.info(Ce.green("Wrote files to "+m.absolutePathToLocalOutput)),c&&m.language!=null?(h.logger.info(`Generating dynamic snippet tests for ${m.language}...`),await Ylu({context:h,ir:g,config:A,language:m.language,outputDir:m.absolutePathToLocalOutput,skipUnstable:u})):h.logger.info(`Skipping dynamic snippet tests; shouldGenerateDynamicSnippetTests: ${c}, language: ${m.language}`)}catch(g){g instanceof Jm||(g instanceof SG?h.failWithoutThrowing(`Generation failed: ${g.log}`,g):h.failWithoutThrowing(`Generation failed: ${g instanceof Error?g.message:"Unknown error"}`,g))}})))}async executeGenerator({generatorGroup:t,generatorInvocation:r,context:n,workspace:i,organization:o,irVersionOverride:s,outputVersionOverride:a,absolutePathToFernConfig:c,inspect:u,skipFernignore:l,skipAutogenerationIfManualExamplesExist:p}){if(n.logger.info(`Starting generation for ${r.name}`),r.absolutePathToLocalOutput==null)throw new Error("Output path is required for generation");let d=cg({workspace:i,audiences:t.audiences,generationLanguage:r.language,keywords:r.keywords,smartCasing:r.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:!0,disabled:r.disableExamples,skipAutogenerationIfManualExamplesExist:p??!1},readme:r.readme,version:a,packageName:Dn.getPackageName({generatorInvocation:r}),context:n,sourceResolver:new nh(n,i),generationMetadata:{cliVersion:i.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:bH()}}),f=await f$n();return m9n({organization:o,absolutePathToFernConfig:c,workspace:i,generatorInvocation:r,absolutePathToLocalOutput:r.absolutePathToLocalOutput,absolutePathToLocalSnippetJSON:r.absolutePathToLocalOutput?Gt.of(Ye(r.absolutePathToLocalOutput,Be.of(qnr))):void 0,absolutePathToLocalSnippetTemplateJSON:void 0,audiences:t.audiences,workspaceTempDir:f,version:a,keepDocker:!1,context:n,irVersionOverride:s,outputVersionOverride:a,writeUnitTests:!0,generateOauthClients:!0,generatePaginatedClients:!0,includeOptionalRequestPropertyExamples:!0,inspect:u,executionEnvironment:this.executionEnvironment,ir:d,runner:void 0,ai:i.generatorsConfiguration?.ai,absolutePathToSpecRepo:void 0,skipFernignore:l})}};var dIu=require("fs/promises");Tt();$t();yH();var yb=ve(tZ(),1),fIu=require("fs/promises"),gyt=class{context;constructor(t){this.context=t.context}async adapt(t){return{raw:this.buildRaw(t),name:t.image,containerImage:t.registry?`${t.registry}/${rNe(t.image)}`:void 0,version:t.version,config:t.config,language:this.mapLanguage(t.lang),outputMode:await this.buildOutputMode(t),absolutePathToLocalOutput:this.context.resolveOutputFilePath(t.output.path),smartCasing:t.smartCasing??!0,readme:this.buildReadme(t),absolutePathToLocalSnippets:void 0,disableExamples:!1,irVersionOverride:void 0,keywords:void 0,publishMetadata:void 0,settings:void 0}}buildRaw(t){let r=t.output.git;if(!(r==null||!Xv.isGitOutputSelfHosted(r)))return{name:t.image,version:t.version,github:{uri:r.uri,token:r.token,mode:this.mapSelfHostedMode(r.mode),branch:r.branch}}}mapSelfHostedMode(t){if(t==null)return Dn.GithubSelfhostedMode.PullRequest;switch(t){case"pr":return Dn.GithubSelfhostedMode.PullRequest;case"push":return Dn.GithubSelfhostedMode.Push;default:we(t)}}async buildOutputMode(t){if(t.output.git!=null){let r=t.output.git;return Xv.isGitOutputSelfHosted(r)?await this.buildGitSelfHostedOutputMode({target:t,git:r}):await this.buildGitHubRepositoryOutputMode({target:t,git:r})}return yb.FernFiddle.remoteGen.OutputMode.downloadFiles({})}async buildGitHubRepositoryOutputMode({target:t,git:r}){let n=Yx(r.repository),i=r.license!=null?await this.convertLicense(r.license):void 0,o=t.publish!=null?this.buildPublishInfo(t.publish):void 0,s=this.buildReviewers(r.reviewers),a=r.mode??"pr";switch(a){case"pr":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.pullRequest({owner:n.owner,repo:n.repo,license:i,publishInfo:o,reviewers:s,downloadSnippets:void 0}));case"release":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.commitAndRelease({owner:n.owner,repo:n.repo,license:i,publishInfo:o,downloadSnippets:void 0}));case"push":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.push({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o,downloadSnippets:void 0}));default:we(a)}}async buildGitSelfHostedOutputMode({target:t,git:r}){let n=Yx(r.uri),i=r.license!=null?await this.convertLicense(r.license):void 0,o=t.publish!=null?this.buildPublishInfo(t.publish):void 0,s=r.mode??"pr";switch(s){case"pr":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.pullRequest({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o}));case"push":return yb.FernFiddle.remoteGen.OutputMode.githubV2(yb.FernFiddle.GithubOutputModeV2.push({owner:n.owner,repo:n.repo,branch:r.branch,license:i,publishInfo:o}));default:we(s)}}buildPublishInfo(t){if(t.npm!=null)return this.buildNpmPublishInfo(t.npm);if(t.pypi!=null)return this.buildPypiPublishInfo(t.pypi);if(t.maven!=null)return this.buildMavenPublishInfo(t.maven);if(t.nuget!=null)return this.buildNugetPublishInfo(t.nuget);if(t.rubygems!=null)return this.buildRubygemsPublishInfo(t.rubygems);if(t.crates!=null)return this.buildCratesPublishInfo(t.crates)}buildNpmPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.npm({registryUrl:t.url??"https://registry.npmjs.org",packageName:t.packageName,token:t.token})}buildPypiPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.pypi({registryUrl:t.url??"https://upload.pypi.org/legacy/",packageName:t.packageName,credentials:t.token!=null?{username:"__token__",password:t.token}:t.username!=null&&t.password!=null?{username:t.username,password:t.password}:void 0,pypiMetadata:t.metadata!=null?{keywords:t.metadata.keywords,documentationLink:t.metadata.documentationLink,homepageLink:t.metadata.homepageLink}:void 0})}buildMavenPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.maven({registryUrl:t.url??"https://s01.oss.sonatype.org/content/repositories/releases/",coordinate:t.coordinate,credentials:t.username!=null&&t.password!=null?{username:t.username,password:t.password}:void 0,signature:t.signature!=null?{keyId:t.signature.keyId,password:t.signature.password,secretKey:t.signature.secretKey}:void 0})}buildNugetPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.nuget({registryUrl:t.url??"https://nuget.org/",packageName:t.packageName,apiKey:t.apiKey})}buildRubygemsPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.rubygems({registryUrl:t.url??"https://rubygems.org/",packageName:t.packageName,apiKey:t.apiKey})}buildCratesPublishInfo(t){return yb.FernFiddle.GithubPublishInfo.crates({registryUrl:t.url??"https://crates.io/api/v1/crates",packageName:t.packageName,token:t.token})}buildReviewers(t){if(t==null)return;let r=[];if(t.teams!=null)for(let n of t.teams)r.push(yb.FernFiddle.GithubPullRequestReviewer.team({name:n}));if(t.users!=null)for(let n of t.users)r.push(yb.FernFiddle.GithubPullRequestReviewer.user({name:n}));return r.length>0?r:void 0}async convertLicense(t){if(t==="MIT")return yb.FernFiddle.GithubLicense.basic({id:yb.FernFiddle.GithubLicenseId.Mit});if(t==="Apache-2.0")return yb.FernFiddle.GithubLicense.basic({id:yb.FernFiddle.GithubLicenseId.Apache});let r=Ye(this.context.cwd,Be.of(t));if(!await sr(r,"file"))throw new Error(`Custom license file "${r}" does not exist; did you mean to use either MIT or Apache-2.0?`);let n=await(0,fIu.readFile)(r,"utf-8");return yb.FernFiddle.GithubLicense.custom({contents:n})}buildReadme(t){let r=t.readme;if(r==null)return;let n={};return r.bannerLink!=null&&(n.bannerLink=r.bannerLink),r.introduction!=null&&(n.introduction=r.introduction),r.apiReferenceLink!=null&&(n.apiReferenceLink=r.apiReferenceLink),r.apiName!=null&&(n.apiName=r.apiName),r.disabledSections!=null&&(n.disabledSections=r.disabledSections),r.defaultEndpoint!=null&&(n.defaultEndpoint=r.defaultEndpoint),r.features!=null&&(n.features=r.features),r.customSections!=null&&(n.customSections=r.customSections.map(i=>({title:i.title,language:i.language??t.lang,content:i.content}))),r.exampleStyle!=null&&(n.exampleStyle=r.exampleStyle),n}mapLanguage(t){return{typescript:Dn.GenerationLanguage.TYPESCRIPT,python:Dn.GenerationLanguage.PYTHON,java:Dn.GenerationLanguage.JAVA,go:Dn.GenerationLanguage.GO,ruby:Dn.GenerationLanguage.RUBY,csharp:Dn.GenerationLanguage.CSHARP,swift:Dn.GenerationLanguage.SWIFT,php:Dn.GenerationLanguage.PHP,rust:Dn.GenerationLanguage.RUST}[t.toLowerCase()]}};$t();var h$n=require("path");function g$n({context:e,task:t,target:r,preview:n,outputPath:i}){if(n)return[(i!=null?(0,h$n.resolve)(e.cwd,i):(0,h$n.join)(e.cwd,Be.of(".fern/preview"))).toString()];let o=VTh(t);if(o!=null){if(o.pullRequestUrl!=null)return[o.pullRequestUrl];if(o.releaseUrl!=null)return[o.releaseUrl];if(o.branchUrl!=null)return[o.branchUrl]}return e.resolveTargetOutputs(r)}function VTh(e){let t={};for(let r of e.logs??[]){let n=r.message.match(/Created pull request: (.+)/);n!=null&&(t.pullRequestUrl=n[1]);let i=r.message.match(/Created commit (\w+)/);i!=null&&(t.commitHash=i[1]);let o=r.message.match(/Pushed branch: (.+)/);o!=null&&(t.branchUrl=o[1]);let s=r.message.match(/Release tagged\. View here: (.+)/);s!=null&&(t.releaseUrl=s[1])}return Object.keys(t).length>0?t:void 0}var A$n=class{context;cliVersion;invocationAdapter;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion,this.invocationAdapter=new gyt({context:this.context})}async run(t){let r=new dg({context:this.context,task:t.task,logLevel:ei.Info});try{let n=await this.invocationAdapter.adapt(t.target),i={groupName:t.target.name,audiences:t.audiences??{type:"all"},generators:[n],reviewers:void 0},s=await new x1e({context:this.context,cliVersion:this.cliVersion,task:t.task}).adapt(t.apiDefinition);return t.target.output.git!=null&&Xv.isGitOutputSelfHosted(t.target.output.git)?await this.runSelfHostedGeneration({args:t,taskContext:r,fernWorkspace:s,generatorGroup:i}):await this.runLocalGeneration({args:t,taskContext:r,fernWorkspace:s,generatorGroup:i,generatorInvocation:n})}catch(n){return r.getResult()===If.Failure?{success:!1}:{success:!1,error:ji(n)}}}async runSelfHostedGeneration({args:t,taskContext:r,fernWorkspace:n,generatorGroup:i}){let o={_absolutePath:Ye(this.context.cwd,Be.of("fern.config.json")),rawConfig:{organization:t.organization,version:this.cliVersion},organization:t.organization,version:this.cliVersion};return await hyt({token:t.token,projectConfig:o,workspace:n,generatorGroup:i,version:t.version,keepDocker:t.keepContainer??!1,context:r,runner:t.containerEngine,absolutePathToPreview:void 0,inspect:!1,ai:void 0,skipFernignore:t.skipFernignore,requireEnvVars:t.requireEnvVars}),r.getResult()===If.Failure?{success:!1}:{success:!0,output:g$n({context:this.context,task:t.task,target:t.target,preview:t.preview,outputPath:t.outputPath})}}async runLocalGeneration({args:t,taskContext:r,fernWorkspace:n,generatorGroup:i,generatorInvocation:o}){let a=`${t.target.registry?`${t.target.registry}/${rNe(t.target.image)}`:t.target.image}:${t.target.version}`,c=new iUe({containerImage:a,keepContainer:t.keepContainer??!1,runner:t.containerEngine});if(await new _Vt(c).run({organization:t.organization,workspace:n,generatorGroup:i,context:r,outputVersionOverride:t.version,ai:t.ai,absolutePathToFernConfig:void 0,irVersionOverride:void 0,shouldGenerateDynamicSnippetTests:!1,skipUnstableDynamicSnippetTests:!0,inspect:!1,skipFernignore:t.skipFernignore}),t.target.output.path!=null&&o.absolutePathToLocalOutput!=null){let l=Ye(o.absolutePathToLocalOutput,Be.of(qnr));await(0,dIu.rm)(l,{force:!0})}return r.getResult()===If.Failure?{success:!1}:{success:!0,output:this.context.resolveTargetOutputs(t.target)}}};Tt();$t();var yze=require("fs/promises"),mIu=require("os");var y$n=class{context;cliVersion;invocationAdapter;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion,this.invocationAdapter=new gyt({context:this.context})}async run(t){let r=new dg({context:this.context,task:t.task,logLevel:ei.Info});try{let n=await this.invocationAdapter.adapt(t.target),i={groupName:t.target.name,audiences:t.audiences??{type:"all"},generators:[n],reviewers:void 0},s=await new x1e({context:this.context,cliVersion:this.cliVersion,task:t.task}).adapt(t.apiDefinition),a=await this.getAbsolutePathToPreview(t);if(await pzt({projectConfig:this.getProjectConfig(t),organization:t.organization,workspace:s,context:r,generatorGroup:i,version:t.version,shouldLogS3Url:t.shouldLogS3Url??!1,token:t.token,mode:this.mapMode(t.target),fernignorePath:t.fernignorePath,skipFernignore:t.skipFernignore,absolutePathToPreview:a,whitelabel:void 0,dynamicIrOnly:!1,retryRateLimited:!1,requireEnvVars:t.requireEnvVars??!0}),this.isLocalGitCombo(t)&&a!=null){let c=TT(n.name),u=Ye(a,Be.of(c)),l=n.absolutePathToLocalOutput;l!=null&&(await(0,yze.cp)(u,l,{recursive:!0}),await(0,yze.rm)(Ye(l,Be.of(".git")),{recursive:!0,force:!0})),await(0,yze.rm)(a,{recursive:!0,force:!0})}return r.getResult()===If.Failure?{success:!1}:{success:!0,output:g$n({context:this.context,task:t.task,target:t.target,preview:t.preview,outputPath:t.outputPath})}}catch(n){return r.getResult()===If.Failure?{success:!1}:{success:!1,error:ji(n)}}}async getAbsolutePathToPreview(t){if(this.isLocalGitCombo(t)){let r=await(0,yze.mkdtemp)(Ye(Gt.of((0,mIu.tmpdir)()),Be.of("fern-preview-")));return Gt.of(r)}if(t.preview)return t.outputPath!=null?fo(this.context.cwd,t.outputPath):Ye(this.context.cwd,Be.of(".fern/preview"))}getProjectConfig(t){return{_absolutePath:Ye(this.context.cwd,Be.of("fern.config.json")),rawConfig:{organization:t.organization,version:this.cliVersion},organization:t.organization,version:this.cliVersion}}mapMode(t){if(t.output.git!=null)return t.output.git.mode==="pr"?"pull-request":void 0}isLocalGitCombo(t){return t.target.output.path!=null&&t.target.output.git!=null&&!t.preview}};var b$n=class{context;cliVersion;constructor(t){this.context=t.context,this.cliVersion=t.cliVersion}async run(t){try{if(this.isLocalGeneration(t))return await this.runLocalGeneration(t);if(t.target.registry!=null)throw new on({message:`Custom image configurations are only supported with local generation (--local). Target "${t.target.name}" uses a custom image registry.`});return await this.runRemoteGeneration(t)}catch(r){let n=ji(r);return{success:!1,target:t.target,error:n}}}async runLocalGeneration(t){let n=await new A$n({context:this.context,cliVersion:this.cliVersion}).run({task:t.task,target:t.target,apiDefinition:t.apiDefinition,organization:t.organization,ai:t.ai,audiences:t.audiences,version:t.version,keepContainer:t.keepContainer,preview:t.preview,outputPath:t.outputPath,containerEngine:t.containerEngine,token:t.token,skipFernignore:t.skipFernignore,requireEnvVars:t.requireEnvVars});return n.success?{success:!0,target:t.target,output:n.output}:{success:!1,target:t.target,error:n.error}}async runRemoteGeneration(t){if(t.token==null)throw on.authRequired();let n=await new y$n({context:this.context,cliVersion:this.cliVersion}).run({target:t.target,apiDefinition:t.apiDefinition,organization:t.organization,token:t.token,task:t.task,ai:t.ai,audiences:t.audiences,version:t.version,shouldLogS3Url:t.shouldLogS3Url,preview:t.preview,outputPath:t.outputPath,fernignorePath:t.fernignorePath,skipFernignore:t.skipFernignore,requireEnvVars:t.requireEnvVars});return n.success?{success:!0,target:t.target,output:n.output}:{success:!1,target:t.target,error:n.error}}isLocalGeneration(t){return t.runtime==="local"||t.target.output.git!=null&&Xv.isGitOutputSelfHosted(t.target.output.git)}};var E$n=class{id;taskGroup;stage;constructor({id:t,taskGroup:r}){this.id=t,this.taskGroup=r,this.stage={validation:new Bde({taskId:t,taskGroup:r,stageId:"validation"}),generator:new Bde({taskId:t,taskGroup:r,stageId:"generator"}),output:new Bde({taskId:t,taskGroup:r,stageId:"output"})}}getTask(){let t=this.taskGroup.getTask(this.id);if(t==null)throw new Error(`Internal error; task '${this.id}' does not exist`);return t}start(t){this.taskGroup.updateTask({id:this.id,update:{status:"running",currentStep:t}})}complete(t){this.taskGroup.updateTask({id:this.id,update:{status:"success",output:t}})}fail(t){this.taskGroup.updateTask({id:this.id,update:{status:"error",error:t}})}};var v$n=class{taskGroup;tasks={};defaultStages=[{id:"validation",labels:{pending:"Validate API",running:"Validating API...",success:"Validated API"}},{id:"generator",labels:{pending:"Run generator",running:"Running generator...",success:"Generator completed"}},{id:"output",labels:{pending:"Write output",running:"Writing output...",success:"Wrote output"}}];constructor({context:t}){this.tasks={},this.taskGroup=new fht({context:t})}addTask({id:t,name:r,stageOverrides:n}){let i=r??t;this.taskGroup.addTask({id:t,name:i});let o=this.buildStages(n);this.taskGroup.setStages(t,o);let s=new E$n({taskGroup:this.taskGroup,id:t});return this.tasks[t]=s,s}getTask(t){return this.tasks[t]}async start(t){await this.taskGroup.start(t)}finish({successMessage:t,errorMessage:r}){return this.taskGroup.complete({successMessage:t,errorMessage:r})}buildStages(t){return t==null?this.defaultStages:this.defaultStages.map(r=>{let n=t[r.id];return n==null?r:{...r,labels:{...r.labels,...n}}})}};$t();var I$n=class{context;constructor({context:t}){this.context=t}async build({org:t,lang:r,resolvedSpec:n,output:i,targetVersion:o}){let s=aLr({lang:r,version:o}),a=Be.of(Ea(this.context.cwd,n.absoluteFilePath)),c=new X5({absoluteFilePath:n.absoluteFilePath,relativeFilePath:a,line:1,column:1}),u={name:r,api:Uet,image:s.image,registry:void 0,lang:r,version:s.tag,sourceLocation:c,output:Xv.resolveOutputObjectSchema(i)};return{apis:{[Uet]:{specs:[n.spec]}},cliVersion:"*",org:t,sdks:{org:t,targets:[u]}}}};var SVt=class{async handle(t,r){let n=await t.loadWorkspace();if(n==null)return this.handleWithFlags(t,r);if(!n.success)throw new aL(n.issues);return this.handleWithWorkspace(t,n.workspace,r)}async handleWithWorkspace(t,r,n){let i=r;if(n.api!=null){let a=await new bzt({context:t}).resolve({reference:n.api}),c={};for(let u of Object.keys(i.apis))c[u]={specs:[a.spec]};i={...i,apis:c}}n.org!=null&&(i={...i,org:n.org});let o=this.getTargets({workspace:i,args:n,groupName:n.target!=null?void 0:n.group??i.sdks?.defaultGroup});this.validateArgs({workspace:i,args:n,targets:o}),await this.runGeneration({context:t,workspace:i,targets:o,args:n,forceLocal:!1})}async handleWithFlags(t,r){let n=[];if(r.api==null&&n.push("--api <path|url> Path or URL to an API spec file (e.g. ./openapi.yaml)"),r.target==null&&n.push("--target <language> The SDK language to generate (e.g. typescript)"),r.org==null&&n.push("--org <name> Your organization name (e.g. acme)"),r.output==null&&n.push("--output <path|url> Output path or git URL (e.g. ./my-sdk)"),r.group!=null&&n.push("remove --group Groups are not supported without a fern.yml"),n.length>0)throw new on({message:`No fern.yml found, either run 'fern init' or specify all of the required flags:
3356
3356
 
3357
3357
  `+n.map(f=>` ${f}`).join(`
3358
3358
  `)});let i=r.api,o=r.target,s=r.org,a=r.output,u=await new bzt({context:t}).resolve({reference:i}),p=await new I$n({context:t}).build({org:s,lang:this.resolveLanguage(o),resolvedSpec:u,output:this.parseTargetOutput({...r,output:a}),targetVersion:r["target-version"]}),d=p.sdks?.targets??[];await this.runGeneration({context:t,workspace:p,targets:d,args:r,forceLocal:!0})}async runGeneration({context:t,workspace:r,targets:n,args:i,forceLocal:o}){if(r.sdks==null)throw new Error("No SDKs configured");let s=[...new Set(n.map(A=>A.api))],c=await new _Z({context:t,cliVersion:r.cliVersion}).check({workspace:r,apiNames:s});if(c.violations.length>0)for(let A of c.violations)process.stderr.write(`${Ce.red(`${A.displayRelativeFilepath}:${A.line}:${A.column}: ${A.message}`)}
3359
3359
  `);if(r.fernYml!=null){let b=await new J8({context:t}).check({workspace:r});if(b.violations.length>0)for(let v of b.violations)process.stderr.write(`${Ce.red(`${v.displayRelativeFilepath}:${v.line}:${v.column}: ${v.message}`)}
3360
- `);if(b.errorCount>0)throw on.exit()}if(n.filter(A=>c.validApis.has(A.api)).length===0)throw on.exit();let l=new b$n({context:t,cliVersion:r.cliVersion}),p=o||i.local,d=this.isTokenRequired({targets:n,args:{...i,local:p}})?await t.getTokenOrPrompt():void 0;d!=null&&await t.verifyOrgAccess({organization:r.sdks.org,token:d});let f=p?"local":"remote",m=new v$n({context:t});for(let A of n){let b=A.output.git!=null&&A.output.path==null?{output:this.getGitOutputStageLabels(A.output.git.mode??"pr")}:void 0;m.addTask({id:A.name,name:A.name,stageOverrides:b})}for(let A of n){let b=i.output!=null?fo(t.cwd,i.output):t.resolveOutputFilePath(A.output.path);if(b!=null){let{shouldProceed:v}=await this.checkOutputDirectory({context:t,args:i,outputPath:b});if(!v)throw new on({message:"Generation cancelled."})}}let h=this.maybePluralSdks(n);if(await m.start({title:`Generating ${h}`,subtitle:`org: ${r.sdks.org}`}),t.onShutdown(()=>{m.finish({successMessage:`Successfully generated ${h}`,errorMessage:"Generation interrupted"})}),await Promise.all(n.map(async A=>{let b=m.getTask(A.name);if(b==null)throw new on({message:`Internal error; task '${A.name}' not found`});b.start(),b.stage.validation.start();let v=r.apis[A.api];if(v==null){b.stage.validation.fail("API not found in workspace");return}if(c.invalidApis.has(A.api)){b.stage.validation.fail("API is invalid");return}b.stage.validation.complete(),b.stage.generator.start();let E=await l.run({organization:r.org,ai:r.ai,target:A,apiDefinition:v,task:b.getTask(),audiences:this.parseAudiences(i.audience),runtime:f,containerEngine:i["container-engine"]??"docker",keepContainer:i["keep-container"],preview:i.preview,outputPath:i.output!=null?fo(t.cwd,i.output):void 0,token:d,version:i["output-version"],fernignorePath:i.fernignore,skipFernignore:i["skip-fernignore"]});if(!E.success){b.stage.generator.fail(E.error);return}b.stage.generator.complete(),b.stage.output.complete(),b.complete(E.output)})),m.finish({successMessage:`Successfully generated ${h}`,errorMessage:`Failed to generate ${h}`}).failedCount>0)throw on.exit()}validateArgs({workspace:t,args:r,targets:n}){if(r["container-engine"]!=null&&!r.local)throw new on({message:"The --container-engine flag can only be used with --local"});if(r.group!=null&&r.target!=null)throw new on({message:"The --group and --target flags cannot be used together"});if(n.length>1&&r.output!=null)throw new on({message:"The --output flag can only be used when generating a single target"});if(r["skip-fernignore"]&&r.fernignore!=null)throw new on({message:"The --skip-fernignore and --fernignore flags cannot be used together."});let i=[];if(r.local)for(let o of n){let s=o.output.git;s!=null&&!Xv.isGitOutputSelfHosted(s)&&o.output.path==null&&i.push(this.suggestGitHubRepositoryOutput({target:o,git:s}))}if(i.length>0)throw new aL(i)}suggestGitHubRepositoryOutput({target:t,git:r}){let{repository:n,reviewers:i,...o}=r,s=n.startsWith("https://")||n.startsWith("http://")?n:`https://github.com/${n}`,a={[t.name]:{output:{git:{...o,uri:s,token:"${GIT_TOKEN}"}}}};return new vA({message:`Target '${t.name}' is incompatible with --local mode.`,suggestion:`Use remote generation (without --local) or configure the target with 'uri' and 'token' instead of 'repository'.
3360
+ `);if(b.errorCount>0)throw on.exit()}if(n.filter(A=>c.validApis.has(A.api)).length===0)throw on.exit();let l=new b$n({context:t,cliVersion:r.cliVersion}),p=o||i.local,d=this.isTokenRequired({targets:n,args:{...i,local:p}})?await t.getTokenOrPrompt():void 0;d!=null&&await t.verifyOrgAccess({organization:r.sdks.org,token:d});let f=p?"local":"remote",m=new v$n({context:t});for(let A of n){let b=A.output.git!=null&&A.output.path==null?{output:this.getGitOutputStageLabels(A.output.git.mode??"pr")}:void 0;m.addTask({id:A.name,name:A.name,stageOverrides:b})}for(let A of n){let b=i.output!=null?fo(t.cwd,i.output):t.resolveOutputFilePath(A.output.path);if(b!=null){let{shouldProceed:v}=await this.checkOutputDirectory({context:t,args:i,outputPath:b});if(!v)throw new on({message:"Generation cancelled."})}}let h=this.maybePluralSdks(n);if(await m.start({title:`Generating ${h}`,subtitle:`org: ${r.sdks.org}`}),t.onShutdown(()=>{m.finish({successMessage:`Successfully generated ${h}`,errorMessage:"Generation interrupted"})}),await Promise.all(n.map(async A=>{let b=m.getTask(A.name);if(b==null)throw new on({message:`Internal error; task '${A.name}' not found`});b.start(),b.stage.validation.start();let v=r.apis[A.api];if(v==null){b.stage.validation.fail("API not found in workspace");return}if(c.invalidApis.has(A.api)){b.stage.validation.fail("API is invalid");return}b.stage.validation.complete(),b.stage.generator.start();let E=await l.run({organization:r.org,ai:r.ai,target:A,apiDefinition:v,task:b.getTask(),audiences:this.parseAudiences(i.audience),runtime:f,containerEngine:i["container-engine"]??"docker",keepContainer:i["keep-container"],preview:i.preview,outputPath:i.output!=null?fo(t.cwd,i.output):void 0,token:d,version:i["output-version"],fernignorePath:i.fernignore,skipFernignore:i["skip-fernignore"],requireEnvVars:i["require-env-vars"]});if(!E.success){b.stage.generator.fail(E.error);return}b.stage.generator.complete(),b.stage.output.complete(),b.complete(E.output)})),m.finish({successMessage:`Successfully generated ${h}`,errorMessage:`Failed to generate ${h}`}).failedCount>0)throw on.exit()}validateArgs({workspace:t,args:r,targets:n}){if(r["container-engine"]!=null&&!r.local)throw new on({message:"The --container-engine flag can only be used with --local"});if(r.group!=null&&r.target!=null)throw new on({message:"The --group and --target flags cannot be used together"});if(n.length>1&&r.output!=null)throw new on({message:"The --output flag can only be used when generating a single target"});if(r["skip-fernignore"]&&r.fernignore!=null)throw new on({message:"The --skip-fernignore and --fernignore flags cannot be used together."});let i=[];if(r.local)for(let o of n){let s=o.output.git;s!=null&&!Xv.isGitOutputSelfHosted(s)&&o.output.path==null&&i.push(this.suggestGitHubRepositoryOutput({target:o,git:s}))}if(i.length>0)throw new aL(i)}suggestGitHubRepositoryOutput({target:t,git:r}){let{repository:n,reviewers:i,...o}=r,s=n.startsWith("https://")||n.startsWith("http://")?n:`https://github.com/${n}`,a={[t.name]:{output:{git:{...o,uri:s,token:"${GIT_TOKEN}"}}}};return new vA({message:`Target '${t.name}' is incompatible with --local mode.`,suggestion:`Use remote generation (without --local) or configure the target with 'uri' and 'token' instead of 'repository'.
3361
3361
 
3362
3362
  Example:
3363
3363
  `+this.indentBlock(Tr.dump(a,{lineWidth:-1})),location:t.sourceLocation})}parseTargetOutput(t){if(t.output!=null&&I8n(t.output)){if(!t.local)throw new on({message:`Remote generation is not supported with a git URL for --output
@@ -3370,7 +3370,7 @@ Example:
3370
3370
  Or use a local path:
3371
3371
  --output ./my-sdk`});return{git:{uri:t.output,token:r,mode:"pr"}}}return{path:t.output}}getTargets({workspace:t,args:r,groupName:n}){let i=t.sdks!=null?this.filterTargetsByGroup(t.sdks.targets,n):[];if(r.target!=null&&(i=i.filter(o=>o.name===r.target),i.length===0))throw new Error(`Target '${r.target}' not found`);if(i.length===0)throw n!=null?new Error(`No targets found for group '${n}'`):new Error("No targets configured in fern.yml");return i.map(o=>({...o,version:r["target-version"]??o.version,output:r.output!=null?this.parseTargetOutput(r):o.output}))}async checkOutputDirectory({context:t,args:r,outputPath:n}){if(r.force||!t.isTTY)return{shouldProceed:!0};if(!await sr(n))return{shouldProceed:!0};if((await(0,hIu.readdir)(n)).length===0)return{shouldProceed:!0};let{confirm:s}=await Zp.prompt([{type:"confirm",name:"confirm",message:`Directory ${n} contains existing files that may be overwritten. Continue?`,default:!1}]);return{shouldProceed:s}}filterTargetsByGroup(t,r){return r==null?t:t.filter(n=>n.groups?.includes(r))}resolveLanguage(t){let r=t;if(fee.includes(r))return r;throw new Error(`"${t}" is not a supported language. Supported: ${fee.join(", ")}`)}parseAudiences(t){if(!(t==null||t.length===0))return{type:"select",audiences:t}}getGitOutputStageLabels(t){switch(t){case"push":return{pending:"Push to repository",running:"Pushing to repository...",success:"Pushed to repository"};case"release":return{pending:"Create release",running:"Creating release...",success:"Created release"};case"pr":return{pending:"Create pull request",running:"Creating pull request...",success:"Created pull request"};default:we(t)}}isTokenRequired({targets:t,args:r}){return!r.local||t.some(n=>n.output.git!=null&&Xv.isGitOutputSelfHosted(n.output.git))}maybePluralSdks(t){return t.length===1?"SDK":"SDKs"}indentBlock(t){return t.trimEnd().split(`
3372
3372
  `).map(r=>r.length>0?` ${r}`:r).join(`
3373
- `)}};function hLo(e){let t=new SVt;Wa(e,"generate","Generate SDKs from fern.yml or directly from an API spec",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Generation timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("api",{type:"string",description:"Path or URL to an API spec file (enables no-config mode)"}).option("audience",{type:"array",string:!0,description:"Filter the target API(s) with the given audience(s)"}).option("container-engine",{choices:["docker","podman"],description:"Choose the container engine to use for local generation"}).option("force",{type:"boolean",default:!1,description:"Ignore prompts to confirm generation"}).option("group",{type:"string",description:"The SDK group to generate"}).option("keep-container",{type:"boolean",default:!1,description:"Prevent auto-deletion of any containers used for local generation"}).option("local",{type:"boolean",default:!1,description:"Run the generator locally in a container"}).option("org",{type:"string",description:"Organization name (required with --api)"}).option("output",{type:"string",description:"Output path or git URL (required with --api; requires --preview in workspace mode)"}).option("output-version",{type:"string",description:"The version to use for the generated packages (e.g. 1.0.0)"}).option("target",{type:"string",description:"The SDK target to generate"}).option("target-version",{type:"string",description:"The generator version for the target"}).option("preview",{type:"boolean",default:!1,description:"Generate a preview of the generated SDK in a local preview directory",hidden:!0}).option("fernignore",{type:"string",description:"Path to .fernignore file",hidden:!0}).option("skip-fernignore",{type:"boolean",default:!1,description:"Skip the .fernignore file and generate all files. For remote generation, uploads an empty .fernignore. For local generation, skips reading .fernignore from the output directory."}))}var gLo=class{generateCommand=new SVt;async handle(t,r){await this.generateCommand.handle(t,{...r,preview:!0})}};function ALo(e){let t=new gLo;Wa(e,"preview","Generate a preview of an SDK",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Preview generation timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("api",{type:"string",description:"Path or URL to an API spec file (enables no-config mode)"}).option("audience",{type:"array",string:!0,description:"Filter the target API(s) with the given audience(s)"}).option("container-engine",{choices:["docker","podman"],description:"Choose the container engine to use for local generation"}).option("force",{type:"boolean",default:!1,description:"Ignore prompts to confirm generation"}).option("group",{type:"string",description:"The SDK group to generate"}).option("keep-container",{type:"boolean",default:!1,description:"Prevent auto-deletion of any containers used for local generation"}).option("local",{type:"boolean",default:!1,description:"Run the generator locally in a container"}).option("org",{type:"string",description:"Organization name (required with --api)"}).option("output",{type:"string",description:"Output path or git URL (required with --api)"}).option("output-version",{type:"string",description:"The version to use for the generated packages (e.g. 1.0.0)"}).option("target",{type:"string",description:"The SDK target to generate"}).option("target-version",{type:"string",description:"The generator version for the target"}).option("fernignore",{type:"string",description:"Path to .fernignore file",hidden:!0}))}Tt();Tt();var C$n=require("fs"),dU=require("fs/promises"),Ayt=require("path"),yme=ve(b1(),1),gIu=require("url"),yLo="@fern-api/generator-migrations",w$n=class e{logger;cachePath;migrationsInstallPromise;static LOCK_FILENAME=".install.lock";static LOCK_POLL_MS=200;static LOCK_STALE_MS=300*1e3;constructor(t){this.logger=t.logger,this.cachePath=t.cachePath}async migrate({target:t,editor:r,from:n,to:i}){let o=this.toGeneratorInvocationSchema(t),s=await this.loadAndRunMigrations({generatorName:t.image,from:n,to:i,config:o});if(s!=null)return await this.applyConfigChanges({target:t,editor:r,migratedConfig:s.config.config}),{migrationsApplied:s.migrationsApplied,appliedVersions:s.appliedVersions}}toGeneratorInvocationSchema(t){return{name:t.image,version:t.version,config:t.config}}async applyConfigChanges({target:t,editor:r,migratedConfig:n}){if(n!=null&&typeof n=="object"){await r.setTargetConfig(t.name,n);return}t.config!=null&&n==null&&await r.deleteTargetConfig(t.name)}async loadAndRunMigrations({generatorName:t,from:r,to:n,config:i}){let o=await this.loadMigrationModule(t);if(o==null)return;let s=this.filterMigrations({migrations:o.migrations,from:r,to:n});if(s.length!==0)return this.runMigrations({migrations:s,config:i})}async ensureMigrationsInstalled(){return this.migrationsInstallPromise!=null?this.migrationsInstallPromise.catch(t=>{throw this.migrationsInstallPromise=void 0,t}):(this.migrationsInstallPromise=(async()=>{let t=this.cachePath;await(0,dU.mkdir)(t,{recursive:!0});let r=(0,Ayt.join)(t,".npm-cache"),n=(0,Ayt.join)(t,"node_modules",yLo),i=(0,Ayt.join)(n,"package.json"),o=await e.acquireLock(this.logger,t);try{await Bu(this.logger,"npm",["install",`${yLo}@latest`,"--prefix",t,"--cache",r,"--ignore-scripts","--no-audit","--no-fund"],{doNotPipeOutput:!0});let s=await(0,dU.readFile)(i,"utf-8"),a=JSON.parse(s);if(a.main==null)throw new Error(`No main field found in package.json for ${yLo}`);let c=(0,Ayt.join)(n,a.main),{migrations:u}=await import((0,gIu.pathToFileURL)(c).href);return u}finally{await o()}})(),this.migrationsInstallPromise.catch(()=>{this.migrationsInstallPromise=void 0}),this.migrationsInstallPromise)}static isProcessAlive(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}static async acquireLock(t,r){let n=(0,Ayt.join)(r,e.LOCK_FILENAME),i=String(process.pid);for(;;)try{let o=await(0,dU.open)(n,"wx");await o.writeFile(i),await o.close();let s=()=>{try{(0,C$n.readFileSync)(n,"utf-8").trim()===i&&(0,C$n.unlinkSync)(n)}catch(a){}};return process.on("exit",s),async()=>{process.removeListener("exit",s);try{let a=await(0,dU.readFile)(n,"utf-8");a.trim()===i?await(0,dU.unlink)(n):t.debug(`Lock file owned by another process (expected pid=${i}, found=${a.trim()}); skipping release`)}catch(a){t.debug(`Failed to release migration lock: ${a}`)}}}catch(o){if(o.code!=="EEXIST")throw o;try{let a=await(0,dU.readFile)(n,"utf-8"),c=Number(a.trim()),u=await(0,dU.stat)(n),l=Date.now()-u.mtimeMs;if(l>e.LOCK_STALE_MS||Number.isFinite(c)&&c>0&&!e.isProcessAlive(c)){t.debug(`Removing stale migration lock (pid=${a.trim()}, age=${l}ms)`);try{await(0,dU.unlink)(n)}catch(p){t.debug(`Failed to remove stale lock: ${p}`)}continue}}catch(a){t.debug(`Lock file vanished during stale check: ${a}`);continue}await new Promise(a=>setTimeout(a,e.LOCK_POLL_MS))}}async loadMigrationModule(t){try{let r=await this.ensureMigrationsInstalled();if(r==null)return;let n=r[t];if(n==null){this.logger.debug(`No migrations registered for generator: ${t}.`);return}return n}catch(r){let n=ji(r);if(n.includes("404")||n.includes("E404")){this.logger.debug(`No migration package found for ${t}.`);return}throw new Error(`Failed to load generator migrations for ${t}.
3373
+ `)}};function hLo(e){let t=new SVt;Wa(e,"generate","Generate SDKs from fern.yml or directly from an API spec",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Generation timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("api",{type:"string",description:"Path or URL to an API spec file (enables no-config mode)"}).option("audience",{type:"array",string:!0,description:"Filter the target API(s) with the given audience(s)"}).option("container-engine",{choices:["docker","podman"],description:"Choose the container engine to use for local generation"}).option("force",{type:"boolean",default:!1,description:"Ignore prompts to confirm generation"}).option("group",{type:"string",description:"The SDK group to generate"}).option("keep-container",{type:"boolean",default:!1,description:"Prevent auto-deletion of any containers used for local generation"}).option("local",{type:"boolean",default:!1,description:"Run the generator locally in a container"}).option("org",{type:"string",description:"Organization name (required with --api)"}).option("output",{type:"string",description:"Output path or git URL (required with --api; requires --preview in workspace mode)"}).option("output-version",{type:"string",description:"The version to use for the generated packages (e.g. 1.0.0)"}).option("target",{type:"string",description:"The SDK target to generate"}).option("target-version",{type:"string",description:"The generator version for the target"}).option("preview",{type:"boolean",default:!1,description:"Generate a preview of the generated SDK in a local preview directory",hidden:!0}).option("fernignore",{type:"string",description:"Path to .fernignore file",hidden:!0}).option("skip-fernignore",{type:"boolean",default:!1,description:"Skip the .fernignore file and generate all files. For remote generation, uploads an empty .fernignore. For local generation, skips reading .fernignore from the output directory."}).option("require-env-vars",{type:"boolean",default:!0,description:"Require all referenced environment variables to be defined (use --no-require-env-vars to substitute empty strings for missing variables)"}))}var gLo=class{generateCommand=new SVt;async handle(t,r){await this.generateCommand.handle(t,{...r,preview:!0})}};function ALo(e){let t=new gLo;Wa(e,"preview","Generate a preview of an SDK",async(r,n)=>{let i=new Promise((o,s)=>{setTimeout(()=>s(new on({message:"Preview generation timed out after 10 minutes."})),6e5).unref()});await Promise.race([t.handle(r,n),i])},r=>r.option("api",{type:"string",description:"Path or URL to an API spec file (enables no-config mode)"}).option("audience",{type:"array",string:!0,description:"Filter the target API(s) with the given audience(s)"}).option("container-engine",{choices:["docker","podman"],description:"Choose the container engine to use for local generation"}).option("force",{type:"boolean",default:!1,description:"Ignore prompts to confirm generation"}).option("group",{type:"string",description:"The SDK group to generate"}).option("keep-container",{type:"boolean",default:!1,description:"Prevent auto-deletion of any containers used for local generation"}).option("local",{type:"boolean",default:!1,description:"Run the generator locally in a container"}).option("org",{type:"string",description:"Organization name (required with --api)"}).option("output",{type:"string",description:"Output path or git URL (required with --api)"}).option("output-version",{type:"string",description:"The version to use for the generated packages (e.g. 1.0.0)"}).option("target",{type:"string",description:"The SDK target to generate"}).option("target-version",{type:"string",description:"The generator version for the target"}).option("fernignore",{type:"string",description:"Path to .fernignore file",hidden:!0}).option("require-env-vars",{type:"boolean",default:!0,description:"Require all referenced environment variables to be defined (use --no-require-env-vars to substitute empty strings for missing variables)"}))}Tt();Tt();var C$n=require("fs"),dU=require("fs/promises"),Ayt=require("path"),yme=ve(b1(),1),gIu=require("url"),yLo="@fern-api/generator-migrations",w$n=class e{logger;cachePath;migrationsInstallPromise;static LOCK_FILENAME=".install.lock";static LOCK_POLL_MS=200;static LOCK_STALE_MS=300*1e3;constructor(t){this.logger=t.logger,this.cachePath=t.cachePath}async migrate({target:t,editor:r,from:n,to:i}){let o=this.toGeneratorInvocationSchema(t),s=await this.loadAndRunMigrations({generatorName:t.image,from:n,to:i,config:o});if(s!=null)return await this.applyConfigChanges({target:t,editor:r,migratedConfig:s.config.config}),{migrationsApplied:s.migrationsApplied,appliedVersions:s.appliedVersions}}toGeneratorInvocationSchema(t){return{name:t.image,version:t.version,config:t.config}}async applyConfigChanges({target:t,editor:r,migratedConfig:n}){if(n!=null&&typeof n=="object"){await r.setTargetConfig(t.name,n);return}t.config!=null&&n==null&&await r.deleteTargetConfig(t.name)}async loadAndRunMigrations({generatorName:t,from:r,to:n,config:i}){let o=await this.loadMigrationModule(t);if(o==null)return;let s=this.filterMigrations({migrations:o.migrations,from:r,to:n});if(s.length!==0)return this.runMigrations({migrations:s,config:i})}async ensureMigrationsInstalled(){return this.migrationsInstallPromise!=null?this.migrationsInstallPromise.catch(t=>{throw this.migrationsInstallPromise=void 0,t}):(this.migrationsInstallPromise=(async()=>{let t=this.cachePath;await(0,dU.mkdir)(t,{recursive:!0});let r=(0,Ayt.join)(t,".npm-cache"),n=(0,Ayt.join)(t,"node_modules",yLo),i=(0,Ayt.join)(n,"package.json"),o=await e.acquireLock(this.logger,t);try{await Bu(this.logger,"npm",["install",`${yLo}@latest`,"--prefix",t,"--cache",r,"--ignore-scripts","--no-audit","--no-fund"],{doNotPipeOutput:!0});let s=await(0,dU.readFile)(i,"utf-8"),a=JSON.parse(s);if(a.main==null)throw new Error(`No main field found in package.json for ${yLo}`);let c=(0,Ayt.join)(n,a.main),{migrations:u}=await import((0,gIu.pathToFileURL)(c).href);return u}finally{await o()}})(),this.migrationsInstallPromise.catch(()=>{this.migrationsInstallPromise=void 0}),this.migrationsInstallPromise)}static isProcessAlive(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}static async acquireLock(t,r){let n=(0,Ayt.join)(r,e.LOCK_FILENAME),i=String(process.pid);for(;;)try{let o=await(0,dU.open)(n,"wx");await o.writeFile(i),await o.close();let s=()=>{try{(0,C$n.readFileSync)(n,"utf-8").trim()===i&&(0,C$n.unlinkSync)(n)}catch(a){}};return process.on("exit",s),async()=>{process.removeListener("exit",s);try{let a=await(0,dU.readFile)(n,"utf-8");a.trim()===i?await(0,dU.unlink)(n):t.debug(`Lock file owned by another process (expected pid=${i}, found=${a.trim()}); skipping release`)}catch(a){t.debug(`Failed to release migration lock: ${a}`)}}}catch(o){if(o.code!=="EEXIST")throw o;try{let a=await(0,dU.readFile)(n,"utf-8"),c=Number(a.trim()),u=await(0,dU.stat)(n),l=Date.now()-u.mtimeMs;if(l>e.LOCK_STALE_MS||Number.isFinite(c)&&c>0&&!e.isProcessAlive(c)){t.debug(`Removing stale migration lock (pid=${a.trim()}, age=${l}ms)`);try{await(0,dU.unlink)(n)}catch(p){t.debug(`Failed to remove stale lock: ${p}`)}continue}}catch(a){t.debug(`Lock file vanished during stale check: ${a}`);continue}await new Promise(a=>setTimeout(a,e.LOCK_POLL_MS))}}async loadMigrationModule(t){try{let r=await this.ensureMigrationsInstalled();if(r==null)return;let n=r[t];if(n==null){this.logger.debug(`No migrations registered for generator: ${t}.`);return}return n}catch(r){let n=ji(r);if(n.includes("404")||n.includes("E404")){this.logger.debug(`No migration package found for ${t}.`);return}throw new Error(`Failed to load generator migrations for ${t}.
3374
3374
 
3375
3375
  Reason: ${n}
3376
3376
 
@@ -3640,7 +3640,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
3640
3640
  Run ${Ce.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
3641
3641
  Run ${Ce.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),UXe(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function hGo({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!rQu(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
3642
3642
  ${await m9h(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+Ce.dim(a.currentVersion)+Ce.reset(" \u2192 ")+Ce.green(a.latestVersion);return i+=`
3643
- `,n?UXe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function m9h(e){let r=await new tQu.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 h9h({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await iQu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=nNe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await yB({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await iQu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=nNe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await yB({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function iQu({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 LM({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?D0(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function oQu(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=nj(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function bei({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await h9h({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...oQu(u,c,t.logger));else s.push(...oQu(a.versions,void 0,t.logger))}return s}async function Zme({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"||e.packageVersion==="0.0.0"?e.packageVersion:PCt(e.packageName,{version:t?"prerelease":"latest"})}var sQu=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Eei=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ei.Info;isLocal;stdoutRedirector=new yei;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new ije(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},this.sentryClient=new Aei({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.62.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ce.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Jm}failWithoutThrowing(t,r){this.didSucceed=!1,SPt({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)+`
3643
+ `,n?UXe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function m9h(e){let r=await new tQu.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 h9h({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await iQu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=nNe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await yB({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await iQu({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=nNe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await yB({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function iQu({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 LM({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?D0(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function oQu(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=nj(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function bei({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await h9h({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...oQu(u,c,t.logger));else s.push(...oQu(a.versions,void 0,t.logger))}return s}async function Zme({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"||e.packageVersion==="0.0.0"?e.packageVersion:PCt(e.packageName,{version:t?"prerelease":"latest"})}var sQu=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Eei=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ei.Info;isLocal;stdoutRedirector=new yei;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new ije(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},this.sentryClient=new Aei({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.62.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ce.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Jm}failWithoutThrowing(t,r){this.didSucceed=!1,SPt({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)+`
3644
3644
  `),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await LXe()).flush(),await this.sentryClient.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await nQu({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
3645
3645
  `)||(r+=`
3646
3646
  `),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=sai(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 oqt(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 Jm}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await LXe()).sendEvent(t)}async captureException(t){await this.sentryClient.captureException(t)}logger=H1((t,...r)=>this.log(t,...r));stderr=H1((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=aQu(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?aQu(this.longestWorkspaceName):r).length,i=r.padEnd(n),o=sQu[this.numTasks++%sQu.length],s=Ce.hex(o)(i);return{...this.constructTaskInit(),logPrefix:s}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===If.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=>$1.indexOf(i.level)>=$1.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===ei.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 Zme({cliEnvironment:this.environment,includePreReleases:t}),n=nj(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await bei({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await dGo({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ce.yellow("?"),style:{answer:i=>Ce.cyan(i),message:i=>Ce.bold(i),highlight:i=>Ce.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
@@ -3836,7 +3836,7 @@ ${Ce.dim(o.summary)}`}));r.push("Do you wish to continue?");let{[t]:n}=await Zp.
3836
3836
  \u2713 All ${t} MDX files are valid`));return}for(let n of e)r.logger.error(n.toString())}$t();function R6u({apiResults:e,docsResult:t,hasErrors:r,showApiNames:n}){let i=[];for(let a of e)for(let c of a.violations){let u={severity:c.severity,message:c.message};n&&(u.api=a.apiName),c.name!=null&&(u.rule=c.name),i.push(u)}let o=[];if(t!=null)for(let a of t.violations){let c={severity:a.severity,message:a.message};a.name!=null&&(c.rule=a.name),o.push(c)}let s={};return i.length>0&&(s.apis=i),o.length>0&&(s.docs=o),{success:!r,results:s}}Tt();function N6u({apiResults:e,docsResult:t,logWarnings:r,context:n}){let i=performance.now(),o=!1;if(e.filter(l=>{let p=Rqt(l.violations);return p.numErrors>0||r&&p.numWarnings>0}).length>0){let l=xZh(e.map(d=>d.violations).flat());if(e.length>1){n.logger.info(Ce.cyan(Ce.bold("[sdk]")));for(let d of e){let f=Rqt(d.violations);(f.numErrors>0||r&&f.numWarnings>0)&&(o=o||f.numErrors>0,vZh({apiName:d.apiName,violations:d.violations,stats:f,logWarnings:r,context:n,indent:" "}))}}else o=o||l.numErrors>0,EZh({violations:e[0]?.violations??[],stats:l,logWarnings:r,context:n})}if(t!=null){let l=Rqt(t.violations);(l.numErrors>0||r&&l.numWarnings>0)&&(o=o||l.numErrors>0,IZh({violations:t.violations,stats:l,logWarnings:r,context:n}))}let a=performance.now()-i,c=[...e.map(l=>l.violations).flat(),...t?.violations??[]],u=Rqt(c);return _Zh({stats:u,logWarnings:r,elapsedMillis:a,context:n}),{hasErrors:o}}function EZh({violations:e,stats:t,logWarnings:r,context:n}){let i=R7o(t,r);n.logger.info(Ce.cyan(Ce.bold("[sdk]"))+` ${i}`),D7o({violations:e,logWarnings:r,context:n,indent:" "})}function vZh({apiName:e,violations:t,stats:r,logWarnings:n,context:i,indent:o}){let s=R7o(r,n);i.logger.info(`${o}${Ce.bold(`[${e}]`)} ${s}`),D7o({violations:t,logWarnings:n,context:i,indent:o+" "})}function IZh({violations:e,stats:t,logWarnings:r,context:n}){let i=R7o(t,r);n.logger.info(Ce.magenta(Ce.bold("[docs]"))+` ${i}`),D7o({violations:e,logWarnings:r,context:n,indent:" "})}function D7o({violations:e,logWarnings:t,context:r,indent:n}){let i=e.filter(s=>s.severity==="fatal"||s.severity==="error"),o=e.filter(s=>s.severity==="warning");if(t)for(let s of o.sort(k6u))F6u({violation:s,context:r,indent:n});for(let s of i.sort(k6u))F6u({violation:s,context:r,indent:n})}function F6u({violation:e,context:t,indent:r}){let n=CZh(e.severity),i=wZh(e);i===""?t.logger.info(`${r}${n} ${e.message}`):(t.logger.info(`${r}${n}`),t.logger.info(`${r} path: ${Ce.blue(i)}`),t.logger.info(`${r} issue: ${e.message}`)),t.logger.info("")}function wZh(e){let t=[];e.relativeFilepath!==""&&t.push(e.relativeFilepath);for(let r of e.nodePath){let n=typeof r=="string"?r:r.key;typeof r!="string"&&r.arrayIndex!=null&&(n+=`[${r.arrayIndex}]`),t.push(n)}return t.join(" -> ")}function CZh(e){switch(e){case"fatal":return Ce.red("[error]");case"error":return Ce.red("[error]");case"warning":return Ce.yellow("[warning]");default:we(e)}}function R7o(e,t){let r=[];return e.numErrors>0&&r.push(`${e.numErrors} error${e.numErrors!==1?"s":""}`),t&&e.numWarnings>0&&r.push(`${e.numWarnings} warning${e.numWarnings!==1?"s":""}`),r.join(", ")}function Rqt(e){let t=0,r=0;for(let n of e)switch(n.severity){case"fatal":case"error":t+=1;break;case"warning":r+=1;break;default:we(n.severity)}return{numErrors:t,numWarnings:r}}function xZh(e){return Rqt(e)}function k6u(e,t){let r=e.relativeFilepath.localeCompare(t.relativeFilepath);return r!==0?r:JSON.stringify(e.nodePath).localeCompare(JSON.stringify(t.nodePath))}function _Zh({stats:e,logWarnings:t,elapsedMillis:r,context:n}){let i=r>0?` in ${(r/1e3).toFixed(3)} seconds.`:".",o=`Found ${e.numErrors} error${e.numErrors!==1?"s":""} and ${e.numWarnings} warning${e.numWarnings!==1?"s":""}`+i;!t&&e.numWarnings>0&&(o+=" Run fern check --warnings to print out the warnings not shown."),e.numErrors>0?n.logger.error(o):e.numWarnings>0?n.logger.warn(o):n.logger.info(Ce.green("All checks passed"))}async function j6u({project:e,cliContext:t,logWarnings:r,brokenLinks:n,errorOnBrokenLinks:i,isLocal:o,directFromOpenapi:s}){let a=[],c,u=!1,l=e.docsWorkspaces;if(l!=null){let d=n||i?[]:["valid-markdown-links"],f=await iv(e),m;await t.runTaskForWorkspace(l,async h=>{m=await RQu({workspace:l,context:h,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:f,errorOnBrokenLinks:i,excludeRules:d})}),m!=null&&(c={violations:m.violations,elapsedMillis:m.elapsedMillis},m.hasErrors&&(u=!0))}await Promise.all(e.apiWorkspaces.map(async d=>{if(d.generatorsConfiguration?.groups.length===0&&d.type!=="fern")return;if(d instanceof Of&&s){await t.runTaskForWorkspace(d,async m=>{await d.getIntermediateRepresentation({context:m,audiences:{type:"all"},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,logWarnings:r})});return}if(d instanceof CB){let m=Ye(d.absoluteFilePath,Be.of(uA),Be.of(TE));if(!await sr(m)){await t.runTask(async g=>(g.logger.error(`Missing file: ${TE}`),g.failAndThrow()));return}}let f;await t.runTaskForWorkspace(d,async m=>{let h=await d.toFernWorkspace({context:m});f=await Avo({workspace:h,context:m,ossWorkspace:d instanceof Of?d:void 0})}),f!=null&&(a.push({apiName:f.apiName,violations:f.violations,elapsedMillis:f.elapsedMillis}),f.hasErrors&&(u=!0))}));let{hasErrors:p}=await t.runTask(d=>N6u({apiResults:a,docsResult:c,logWarnings:r,context:d}));if(t.isJsonMode){let d=a.length>1;t.writeJsonToStdout(R6u({apiResults:a,docsResult:c,hasErrors:p||u,showApiNames:d}))}(p||u)&&t.failAndThrow()}$t();var fae=require("fs/promises");var F7o=ve(require("path"),1);async function Q6u({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async o=>{i instanceof Gk?await SZh({workspace:i,context:o}):await OZh({workspace:await i.toFernWorkspace({context:o},{preserveSchemaIds:n}),context:o})})}))}async function SZh({workspace:e,context:t}){for(let[r,n]of Object.entries(e.definition.importedDefinitions)){let i=Ye(e.absoluteFilePath,Be.of(uA),Be.of(r),Be.of(`.${uA}`));await M6u({definition:n.definition,absolutePathToOutputDirectory:i}),t.logger.info(Ce.green(`Wrote imported definition at ${F7o.default.relative(process.cwd(),i)}`))}}async function OZh({workspace:e,context:t}){let r=Ye(e.absoluteFilePath,Be.of(`.${uA}`));await M6u({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(Ce.green(`Wrote definition to ${F7o.default.relative(process.cwd(),r)}`))}async function M6u({definition:e,absolutePathToOutputDirectory:t}){let r=(n,i)=>{let o={imports:0,types:1,services:2},s=n in o?o[n]:Object.keys(o).length,a=i in o?o[i]:Object.keys(o).length;return s==null?-1:a==null?1:s!==a?s-a:n.localeCompare(i)};await sr(t)&&await(0,fae.rm)(t,{recursive:!0}),await(0,fae.mkdir)(t,{recursive:!0}),await(0,fae.writeFile)(Ye(t,Be.of(TE)),Tr.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[n,i]of Object.entries(e.packageMarkers)){let o=Ye(t,Be.of(n));await(0,fae.mkdir)(Bn(o),{recursive:!0}),await(0,fae.writeFile)(o,Tr.dump(i.contents,{sortKeys:r}))}for(let[n,i]of Object.entries(e.namedDefinitionFiles)){let o=Ye(t,Be.of(n));await(0,fae.mkdir)(Bn(o),{recursive:!0}),await(0,fae.writeFile)(o,Tr.dump(i.contents,{sortKeys:r}))}}$t();var L6u=require("fs/promises");async function U6u({project:e,outputPath:t,cliContext:r}){let n=e.docsWorkspaces;n!=null&&await r.runTaskForWorkspace(n,async i=>{let o=await iv(e),s=await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:i},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),c=await new HL({domain:n.config.instances[0]?.url??"http://localhost:8080",docsWorkspace:n,ossWorkspaces:o,apiWorkspaces:s,taskContext:i,editThisPage:void 0,uploadFiles:void 0,registerApi:void 0,targetAudiences:n.config.instances[0]?.audiences?Array.isArray(n.config.instances[0].audiences)?n.config.instances[0].audiences:[n.config.instances[0].audiences]:void 0}).resolve();await(0,L6u.writeFile)(Gt.of(t),JSON.stringify(c,null,2)),i.logger.info(Ce.green(`Docs definition written to ${t}`))})}$t();var iqu=ve(F0o(),1),qEt=require("fs"),wq=require("fs/promises"),oqu=ve(gxr(),1),L7o=ve(require("path"),1);Tt();var TZh="https://r88yjrnw5k.execute-api.us-east-1.amazonaws.com/dev2/translate",BZh=3,PZh=1e3,DZh=3e4,RZh=3e4;function z6u(e,t){if(e.name==="AbortError"||e.code==="ECONNRESET"||e.code==="ENOTFOUND"||e.code==="ECONNREFUSED"||e.code==="ETIMEDOUT")return!0;if(e.cause instanceof Error){let r=e.cause;if(r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ETIMEDOUT")return!0}if(t){let r=t.status;if(r>=500&&r<600||r===429||r===408)return!0}return!1}function V6u(e,t,r){let n=t*Math.pow(2,e-1),i=Math.random()*.1*n;return Math.min(n+i,r)}function FZh(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);return fetch(e,{...t,signal:n.signal}).finally(()=>{clearTimeout(i)})}async function Fqt({text:e,language:t,sourceLanguage:r,fileType:n,cliContext:i,retryConfig:o={}}){if(t===r)return e;let s=await s7();if(s==null)throw i.logger.error("Authentication required. Please run 'fern login' or set the FERN_TOKEN environment variable."),new Error("Authentication required for translation service");let a={maxRetries:o.maxRetries??BZh,baseDelay:o.baseDelay??PZh,maxDelay:o.maxDelay??DZh,timeout:o.timeout??RZh},c;for(let l=1;l<=a.maxRetries+1;l++)try{let p=await FZh(TZh,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.value}`},body:JSON.stringify({text:e,source_language:r,target_language:t,...n!==void 0&&{file_type:n}})},a.timeout);if(!p.ok){let f="";try{let h=await p.json();f=h.detail||JSON.stringify(h)}catch{f=await p.text()}if(p.status===403)throw new Error(`403: ${f}`);let m=new Error(`HTTP ${p.status}: ${f}`);if(!z6u(m,p))return i.logger.debug(`[TRANSLATE] Non-retriable error ${p.status}: ${f}`),e;if(c=m,l<=a.maxRetries){i.logger.debug(`[TRANSLATE] Attempt ${l} failed with status ${p.status}: ${f}. Retrying...`);let h=V6u(l,a.baseDelay,a.maxDelay);await new Promise(g=>setTimeout(g,h));continue}else return i.logger.debug(`[TRANSLATE] All ${a.maxRetries+1} attempts failed. Final error: ${f}`),e}let d=await p.json();return l>1&&i.logger.debug(`[TRANSLATE] Succeeded on attempt ${l} after ${l-1} retries`),await new Promise(f=>setTimeout(f,500)),d.translated_text??e}catch(p){if(c=p,p instanceof Error&&p.message.includes("403"))throw p;if(p instanceof Error&&!z6u(p)){let m=ji(p);return i.logger.debug(`[TRANSLATE] Non-retriable error: ${m}`),e}if(l>a.maxRetries){let m=ji(p);return i.logger.debug(`[TRANSLATE] All ${a.maxRetries+1} attempts failed. Final error: ${m}`),e}let d=ji(p);i.logger.debug(`[TRANSLATE] Attempt ${l} failed: ${d}. Retrying...`);let f=V6u(l,a.baseDelay,a.maxDelay);await new Promise(m=>setTimeout(m,f))}let u=c instanceof Error?c.message:c?String(c):"Unknown error";return i.logger.debug(`[TRANSLATE] Unexpected end of retry loop. Last error: ${u}`),e}Ni();var kZh=new Set(["title","display-name","page","section","text","link","message","subtitle","search-text","system-prompt","summary","description","docs","tags","api"]);function q6u(e,t){return typeof t!="string"||t==="string"||t.startsWith("./")?!1:!!kZh.has(e)}function u3e({name:e}){let t=e.replace(/\.(md|mdx)$/i,"");return $m(t)}function NZh(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.page=="string"&&typeof t.path=="string"}function jZh(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.section=="string"&&Array.isArray(t.contents)}function QZh(e){return typeof e!="object"||e===null?!1:typeof e.api=="string"}function MZh(e){return typeof e!="object"||e===null?!1:typeof e.changelog=="string"}function LZh(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t["display-name"]=="string"||typeof t.displayName=="string"}function UZh(e){if(typeof e!="object"||e===null)return!1;let t=e;return(typeof t["display-name"]=="string"||typeof t.displayName=="string")&&typeof t.path=="string"}function zZh(e){if(typeof e!="object"||e===null)return;let t=e;if(typeof t.slug=="string")return t.slug;if(t["skip-slug"]!==!0){if(NZh(e))return u3e({name:e.page});if(jZh(e))return u3e({name:e.section});if(QZh(e)){let r=e["api-name"],n=e.api;return u3e({name:typeof r=="string"?r:n})}if(MZh(e)){let r=e.title;if(typeof r=="string")return u3e({name:r});let n=e.changelog;if(typeof n=="string"){let i=n.split("/").pop()||n;return u3e({name:i})}}if(LZh(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return u3e({name:r})}if(UZh(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return u3e({name:r})}}}async function k7o({obj:e,language:t,sourceLanguage:r,filePath:n,cliContext:i,stub:o,sourceObj:s}){if(e==null||typeof e=="string")return e;if(Array.isArray(e)){let a=Array.isArray(s)?s:void 0;return await Promise.all(e.map((c,u)=>k7o({obj:c,language:t,sourceLanguage:r,filePath:n,cliContext:i,stub:o,sourceObj:a?.[u]})))}if(typeof e=="object"){let a={},c=typeof s=="object"&&s!==null?s:void 0,u;u=zZh(e);for(let[l,p]of Object.entries(e))if(l!=="slug")if(q6u(l,p)){if(o){a[l]=p;continue}a[l]=await Fqt({text:p,language:t,sourceLanguage:r,cliContext:i})}else a[l]=await k7o({obj:p,language:t,sourceLanguage:r,filePath:n,cliContext:i,stub:o,sourceObj:c?.[l]});return u!==void 0&&(a.slug=u),a}return e}async function G6u({yamlContent:e,language:t,sourceLanguage:r,filePath:n,cliContext:i,stub:o=!1}){if(t===r)return e;try{let s=vce(e);if(!s)return e;let a=await k7o({obj:s,language:t,sourceLanguage:r,filePath:n,cliContext:i,stub:o,sourceObj:s});return bAe(a,{indent:2,lineWidth:-1,quotingType:'"',forceQuotes:!1})}catch(s){if(s instanceof Error&&s.message.includes("403"))throw s;return i.logger.error(` [ERROR] Failed to process YAML file ${n}: ${s}`),e}}async function Fri({transformation:e,cliContext:t,stub:r=!1}){let{filePath:n,language:i,sourceLanguage:o,originalContent:s}=e;if(r&&!n.endsWith(".yml")&&!n.endsWith(".yaml"))return t.logger.debug(`[STUB] Returning content as-is for ${n} (stub mode enabled)`),s;t.logger.debug(`[PROCESSING] ${n} for language: ${i} (source: ${o})`);try{return(n.endsWith(".yml")||n.endsWith(".yaml"))&&!n.includes("generators.yml")?await G6u({yamlContent:s,language:i,sourceLanguage:o,filePath:n,cliContext:t,stub:r}):n.endsWith(".md")||n.endsWith(".mdx")?Fqt({text:s,language:i,sourceLanguage:o,fileType:"MDX",cliContext:t}):n.endsWith(".json")&&!n.includes("fern.config.json")?Fqt({text:s,language:i,sourceLanguage:o,cliContext:t}):(t.logger.debug(`[SKIP] Skipping file "${n}" - unsupported file type for translation.`),s)}catch(a){if(a instanceof Error&&a.message.includes("403"))throw a;return s}}function W6u(e){let t=[".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".bmp",".tiff",".tif",".woff",".woff2",".ttf",".otf",".eot",".pdf",".doc",".docx",".mp4",".webm",".ogg",".mp3",".wav",".zip",".tar",".gz",".bin"],r=e.toLowerCase();return t.some(n=>r.endsWith(n))}function $6u(e,t){return e.endsWith(".yaml")||e.endsWith(".yml")?!0:e.endsWith(".md")||e.endsWith(".mdx")||e.endsWith(".json")&&!e.includes("fern.config.json")?!t:!1}$t();var Nri=require("fs/promises");function kri(e,t){try{let r=new URL(e),n=r.hostname,i=e.endsWith("/");if(n.includes(".docs.buildwithfern.com")){let s=n.split(".")[0];r.hostname=`${s}-${t}.docs.buildwithfern.com`,r.pathname=`/${t}${r.pathname}`}else r.hostname=`${t}.${n}`,r.pathname=`/${t}${r.pathname}`;let o=r.toString();return!i&&o.endsWith("/")&&r.pathname===`/${t}/`&&(o=o.slice(0,-1)),o}catch{let r=e.endsWith("/");if(e.includes("://")){let[n,i]=e.split("://"),[o,...s]=i?.split("#")??[],[a,...c]=o?.split("?")??[],[u,...l]=a?.split("/")??[];if(!u)return e;let p;u.includes(".docs.buildwithfern.com")?p=`${u.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:p=`${t}.${u}/${t}`;let d=`${n}://${p}`;return l.length>0?d+="/"+l.join("/"):r&&(d+="/"),c.length>0&&(d+="?"+c.join("?")),s.length>0&&(d+="#"+s.join("#")),d}else if(e.includes("/")){let n=e.split("/"),i=n[0],o=n.slice(1),s;return i?.includes(".docs.buildwithfern.com")?s=`${i.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:s=`${t}.${i}/${t}`,o.length>0||o.some(a=>a!=="")?`${s}/${o.join("/")}`:r?`${s}/`:s}else return e.includes(".docs.buildwithfern.com")?`${e.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:`${t}.${e}/${t}`}}function VZh(e,t){let r=qZh({docsConfig:e,language:t});return GZh({docsConfig:r,language:t})}function qZh({docsConfig:e,language:t}){let r=structuredClone(e);return r.settings?(r.settings.language=t,r.settings["search-text"]=H6u[t]):r.settings={language:t,"search-text":H6u[t]},r}var H6u={en:"Search",es:"Buscar",fr:"Rechercher",de:"Suchen",it:"Cerca",pt:"Pesquisar",ja:"\u691C\u7D22",zh:"\u641C\u7D22",ko:"\uAC80\uC0C9",el:"\u0391\u03BD\u03B1\u03B6\u03AE\u03C4\u03B7\u03C3\u03B7",no:"S\xF8k",pl:"Szukaj",ru:"\u041F\u043E\u0438\u0441\u043A",sv:"S\xF6k",tr:"Ara"};function GZh({docsConfig:e,language:t}){let r=structuredClone(e);return r.instances&&Array.isArray(r.instances)&&(r.instances=r.instances.map(n=>{let i={...n};if(i.url&&(i.url=kri(i.url,t)),i["custom-domain"]){let o=i["custom-domain"];typeof o=="string"?i["custom-domain"]=kri(o,t):Array.isArray(o)&&(i["custom-domain"]=o.map(s=>kri(s,t)))}return i})),r}async function K6u({originalDocsConfigPath:e,targetDirectory:t,language:r,sourceLanguage:n,context:i,stub:o=!1}){try{let s=await(0,Nri.readFile)(e,"utf-8"),c=await Fri({transformation:{filePath:Bg,language:r,sourceLanguage:n,originalContent:s},cliContext:i,stub:o}),u=Tr.load(c),l=VZh(u,r),p=Ye(t,Be.of(Bg)),d=Tr.dump(l,{sortKeys:!1});await(0,Nri.writeFile)(p,d,"utf-8"),i.logger.debug(`Created language-specific docs config: ${p}`)}catch(s){if(s instanceof Error&&s.message.includes("403"))throw s;i.logger.warn(`Failed to create language-specific docs config for ${r}: ${s}`)}}$t();var J6u=require("fs"),Y6u=require("fs/promises"),X6u=ve(require("path"),1);async function N7o(e,t){let r={},n=await(0,Y6u.readdir)(e);for(let i of n){if(i==="translations")continue;let o=X6u.default.join(e,i),s=t?Ye(t,Be.of(i)):Be.of(i),a=(0,J6u.statSync)(o);if(a.isDirectory()){let c=await N7o(o,s);for(let[u,l]of Object.entries(c))r[u]=l}else a.isFile()&&(r[o]=s)}return r}var Z6u=require("crypto"),equ=require("fs"),kqt=require("fs/promises"),j7o=ve(require("path"),1);function tqu(e){return(0,Z6u.createHash)("sha256").update(e,"utf-8").digest("hex")}async function rqu(e){let t=j7o.default.join(e,"hashes");if(!(0,equ.existsSync)(t))return{};try{let r=await(0,kqt.readFile)(t,"utf-8"),n=JSON.parse(r),{_comment:i,...o}=n;return o}catch{return{}}}async function Q7o(e,t){let r=j7o.default.join(e,"hashes"),n={};Object.keys(t).sort().forEach(o=>{let s=t[o];s!==void 0&&(n[o]=s)});let i={_comment:"This file is auto-generated by Fern to track source file changes for translation purposes. Do not edit manually - it will be overwritten on the next translation update.",...n};await(0,kqt.writeFile)(r,JSON.stringify(i,null,2),"utf-8")}async function jri(e,t,r){try{let n=await(0,kqt.readFile)(e,"utf-8"),i=tqu(n),o=r[t];return i!==o}catch{return!0}}function WZh(e,t,r){let n=tqu(r);e[t]=n}async function M7o(e,t,r,n){WZh(t,r,n),await Q7o(e,t)}function nqu(e,t){let r={};for(let[n,i]of Object.entries(e))t.has(n)&&(r[n]=i);return r}async function squ({project:e,cliContext:t,stub:r=!1}){let n=e.docsWorkspaces;if(n==null){t.logger.error("No docs workspace found. Please ensure you have a docs.yml file configured.");return}let i=n.config.languages;if(i==null||i.length===0){t.logger.error("No languages found in docs.yml configuration. Please add a 'languages' field with the desired languages.");return}await t.runTaskForWorkspace(n,async o=>{let s=n.absoluteFilePath,a=Ye(s,Be.of("translations")),c=i[0];if(!c)throw new Error("Unexpected error - first element of languages array is invalid");(0,qEt.existsSync)(a)||(o.logger.debug(`Creating translations directory at: ${a}`),await(0,wq.mkdir)(a,{recursive:!0}));let u={},l=i.filter(h=>h!==c),p=Ye(s,Be.of(Bg)),d=(0,qEt.existsSync)(p);for(let h of l){let g=Ye(a,Be.of(h),Be.of("fern"));(0,qEt.existsSync)(g)||await(0,wq.mkdir)(g,{recursive:!0}),u[h]={filesProcessed:0,filesSkipped:0}}u[c]={filesProcessed:0,filesSkipped:0};let f={filesProcessed:0,filesSkipped:0};try{let h=await rqu(a),g=await N7o(s,""),A=Object.entries(g),b=new Set(Object.values(g)),v=nqu(h,b);Object.keys(v).length!==Object.keys(h).length&&await Q7o(a,v),h=v;let E=[];for(let[z,K]of A)d&&K===Bg||$6u(z,r)&&await jri(z,K,h)&&E.push([z,K]);let I=!1;d&&(I=await jri(p,Be.of(Bg),h));let w=E.length+(I?1:0),x=w*l.length,C=process.stdout.isTTY&&!oqu.default&&x>0,_;C&&(_=new iqu.default.SingleBar({format:"Processing files [{bar}] {percentage}% | {value}/{total} files",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1,stopOnComplete:!0}),_.start(x,0));let R=0,G=0;try{if(d)if(I){for(let ie of l){R++,G++,C||o.logger.info(Ce.gray(`[${G}/${w+1}] Processing: ${Bg} (docs config) for language: ${ie}`)),t.logger.debug(`[PROCESSING] ${Bg} (docs config) for language: ${ie}`);let q=Ye(a,Be.of(ie),Be.of("fern"));await K6u({originalDocsConfigPath:p,targetDirectory:q,language:ie,sourceLanguage:c,context:t,stub:r});let H=u[ie];_&&_.update(R),H&&H.filesProcessed++,t.logger.debug(`[COMPLETED] ${Bg} -> ${ie}/${Bg}`)}let z=await(0,wq.readFile)(p,"utf-8");await M7o(a,h,Be.of(Bg),z);let K=u[c];K&&K.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${Bg} -> ${c} (source language - hash updated)`)}else{for(let z of i){let K=u[z];K&&K.filesSkipped++}t.logger.debug(`[SKIPPED] ${Bg} (no changes since last translation)`)}for(let[z,K]of A){if(d&&K===Bg){t.logger.debug(`[SKIPPED] ${K} (already handled by docs config processing)`);continue}if(!await jri(z,K,h)){for(let ye of i){let Ee=u[ye];Ee&&Ee.filesSkipped++}t.logger.debug(`[SKIPPED] ${K} (no changes since last translation)`);continue}t.logger.debug(`[PROCESSING] ${K} (detected changes)`);let q=await(0,wq.readFile)(z,"utf-8");await M7o(a,h,K,q);let H=u[c];H&&H.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${K} -> ${c} (source language - hash only)`);for(let ye of l){G++,R++,C||o.logger.info(Ce.gray(`[${G}/${w}] Processing: ${K}`));let Ee=Ye(a,Be.of(ye),Be.of("fern")),Z=Ye(Ee,K),te=L7o.default.dirname(Z);(0,qEt.existsSync)(te)||await(0,wq.mkdir)(te,{recursive:!0});let Ae=await Fri({transformation:{filePath:K,language:ye,sourceLanguage:c,originalContent:q},cliContext:t,stub:r});await(0,wq.writeFile)(Z,Ae,"utf-8");let Te=u[ye];Te&&Te.filesProcessed++,t.logger.debug(`[COMPLETED] ${K} -> ${ye}/${K}`),_&&_.update(R)}}}finally{_&&(_.update(x),_.stop(),t.logger.info())}o.logger.info(Ce.cyan("Copying asset files..."));let V=0;for(let[z,K]of A)if(W6u(z))for(let ie of l){let q=Ye(a,Be.of(ie),Be.of("fern")),H=Ye(q,K),ye=L7o.default.dirname(H);(0,qEt.existsSync)(ye)||await(0,wq.mkdir)(ye,{recursive:!0}),await(0,wq.copyFile)(z,H),V++,t.logger.debug(`[ASSET COPIED] ${K} -> ${ie}/${K}`)}V>0&&o.logger.info(Ce.green(`\u2713 Copied ${V} asset files to translation directories`));for(let z of i){let K=u[z];if(!K)continue;f.filesProcessed+=K.filesProcessed,f.filesSkipped+=K.filesSkipped;let ie=K.filesProcessed+K.filesSkipped;z===c?(o.logger.info(Ce.blue(`${z} (source) hash tracking summary: ${K.filesProcessed} processed, ${K.filesSkipped} skipped (${ie} total)`)),o.logger.info(Ce.green(`\u2713 Successfully tracked ${z} source language hashes (no directory created)`))):(o.logger.info(Ce.blue(`${z} translation summary: ${K.filesProcessed} processed, ${K.filesSkipped} skipped (${ie} total)`)),o.logger.info(Ce.green(`\u2713 Successfully created ${z} translation with content processing`)))}}catch(h){throw h instanceof Error&&h.message.includes("403")||o.logger.error(`Failed to create translations: ${h}`),h}let m=f.filesProcessed+f.filesSkipped;if(o.logger.info(Ce.cyan(`Overall summary: ${f.filesProcessed} files processed, ${f.filesSkipped} files skipped across ${i.length} languages (${m} total operations)`)),o.logger.info(Ce.green(`Translations created successfully in: ${a}`)),l.length>0){o.logger.info("You can now modify the content in each language directory:");for(let h of l)o.logger.info(Ce.blue(` - ${h}: ${Ye(a,Be.of(h))}`))}if(o.logger.info(`Source language (${c}) values are tracked as hashes in translations/hashes`),d&&l.length>0){o.logger.info("Language-specific docs configurations created with modified instance URLs:");for(let h of l)o.logger.info(` - ${h}/docs.yml: URLs modified to include ${h} prefix`)}})}Tt();async function aqu(e,t,r){let i=(await lp(e,{commandLineApiWorkspace:r,defaultToAllApiWorkspaces:!1})).apiWorkspaces[0];if(i==null)return e.failAndThrow("No API workspace found.");let o=i.generatorsConfiguration;if(o==null)return e.failAndThrow("No generators.yml found in workspace.");let s=o.groups.find(l=>l.groupName===t);if(s==null){let l=o.groups.map(p=>p.groupName).join(", ");return e.failAndThrow(`Group "${t}" not found. Available groups: ${l}`)}let a=l=>_b(l,{onError:p=>e.failAndThrow(p)}),c=s.generators.find(l=>l.raw?.github!=null&&Tbe(l.raw.github));if(c?.raw?.github!=null&&Tbe(c.raw.github)){let l=a(c.raw.github);return e.logger.info(`Using github config from group "${t}" generator "${c.name}" (mode: ${l.mode??"pull-request"})`),{githubRepo:l.uri,token:l.token,mode:l.mode==="push"?"push":"pull-request",branch:l.branch}}let u=s.generators.find(l=>l.raw?.github!=null&&"repository"in l.raw.github);if(u?.raw?.github!=null&&"repository"in u.raw.github){let l=a(u.raw.github),p=process.env.GITHUB_TOKEN;return e.logger.info(`Using repository config from group "${t}" generator "${u.name}"`+(p!=null?". Using GITHUB_TOKEN from environment.":".")),{githubRepo:l.repository,token:p,mode:l.mode==="push"?"push":"pull-request",branch:"branch"in l?l.branch:void 0}}return e.failAndThrow(`No generator in group "${t}" has a github configuration.`)}var Qri=$Zh();function $Zh(){return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&globalThis?.navigator?.userAgent==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(self.constructor?.name==="DedicatedWorkerGlobalScope"||self.constructor?.name==="ServiceWorkerGlobalScope"||self.constructor?.name==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!process.versions?.node?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}odg();var idg="The Fern CLI requires Node 18+ or above.";async function odg(){let e=process.argv.includes("--local"),t=new Eei(process.stdout,process.stderr,{isLocal:e}),r=async()=>{await t.exit()};if(Qri.type==="node"&&Qri.parsedVersion!=null&&Qri.parsedVersion>=18){let{setGlobalDispatcher:n,Agent:i}=await Promise.resolve().then(()=>ve(aKo(),1));n(new i({connect:{timeout:2147483647},bodyTimeout:0,headersTimeout:2147483647}))}if(process.env.HTTP_PROXY!=null){let{setGlobalDispatcher:n,ProxyAgent:i}=await Promise.resolve().then(()=>ve(aKo(),1)),o=new i(process.env.HTTP_PROXY);n(o)}process.on("SIGINT",async()=>{t.suppressUpgradeMessage(),await r()});try{let n=process.env[Bqt];n!=null&&process.chdir(n);let i=await adg(t);t.environment.packageVersion===i?await sdg(t):await Dqt({version:i,cliContext:t})}catch(n){await t.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:n}}),n?.message.includes("globalThis")?(t.logger.error(idg),t.failWithoutThrowing()):n instanceof Jm?t.failWithoutThrowing():n instanceof SG?t.logger.error(`Failed. ${n.log}`):(await t.captureException(n),t.failWithoutThrowing("Failed.",n))}await r()}async function sdg(e){let t=W3e(process.argv);if(t[0]==="completion"){$qo(t).scriptName(e.environment.cliName).completion("completion","Generate shell completion script").parse();return}let r=$qo(t).scriptName(e.environment.cliName).version(!1).completion("completion","Generate shell completion script").fail((n,i,o)=>{i==null&&(o.showHelp(),e.logger.error(n))}).strict().exitProcess(!1).command("$0",!1,n=>n.option("version",{describe:"Print current version",alias:"v"}).version(!1),n=>{n.version!=null?e.logger.info(e.environment.packageVersion):(r.showHelp(),e.failAndThrow())}).option("log-level",{default:ei.Info,choices:$1}).demandCommand().recommendCommands();ldg(r,e),pdg(r,e),udg(r,e),fdg(r,e),ddg(r,e),mdg(r,e),hdg(r,e),ydg(r,e),gdg(r,e),Adg(r,e),vdg(r,e),bdg(r,e),Edg(r,e),Sdg(r,e),Odg(r,e),Tdg(r,e),Ndg(r,e),jdg(r,e),Pdg(r,e),Ddg(r,e),kdg(r,e),Bdg(r,e),Cdg(r,e),_dg(r,e),Idg({cli:r,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),wdg(r,e),$dg(r,e),Hdg(r,e),Kdg(r,e),Jdg(r,e),omg(r,e),emg(r,e),Xdg(r,e),_Qu(r,e),SQu(r,e),tmg(r,e),img(r,e),r.middleware(async n=>{e.setLogLevel(n["log-level"]),n.json===!0&&e.enableJsonMode(),e.logFernVersionDebug()}),await r.parse()}async function adg(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await Yy();if(t!=null){let r=await e.runTask(n=>FM({directory:t,context:n}));return r.version==="*"?e.environment.packageVersion:r.version==="latest"?Zme({cliEnvironment:e.environment}):r.version}return Zme({cliEnvironment:e.environment})}async function cdg(e){let t=await Yy();if(t!=null)return(await e.runTask(n=>FM({directory:t,context:n}))).organization}function udg(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("fern-definition",{boolean:!0,description:"Initialize with a sample Fern Definition instead of an OpenAPI spec"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null){let n=await cdg(t);n!=null?r.organization=n:r.organization=await t.getInput({message:"Please enter your organization"})}if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.");if(r.openapi!=null&&r["fern-definition"]===!0)return t.failWithoutThrowing("Cannot specify both --openapi and --fern-definition. Please choose one.");if(r.readme!=null)await t.runTask(async n=>{await cqo({readmeUrl:r.readme,organization:r.organization??"fern",taskContext:n,versionOfCli:await Zme({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async n=>{await GLo({organization:r.organization,versionOfCli:await Zme({cliEnvironment:t.environment}),taskContext:n})});else if(r.mintlify!=null)await t.runTask(async n=>{await JLo({pathToMintJson:r.mintlify,organization:r.organization??"fern",taskContext:n,versionOfCli:await Zme({cliEnvironment:t.environment})})});else{let n;if(r.openapi!=null){if(Zhe(r.openapi)){let o=await uqo({url:r.openapi,logger:t.logger});o.status===v5e.Failure&&t.failAndThrow(o.errorMessage);let s=o.filePath;n=Gt.of(s)}else n=Gt.of(fo(zl(),r.openapi));await sr(n)||t.failAndThrow(`${n} does not exist`)}await t.runTask(async i=>{await qLo({organization:r.organization,versionOfCli:await Zme({cliEnvironment:t.environment}),context:i,openApiPath:n,useFernDefinition:r["fern-definition"]===!0})})}})}function ldg(e,t){e.command("diff","Diff two versions of an API",r=>r.option("from",{string:!0,demandOption:!0,description:"The previous version of the API"}).option("to",{string:!0,demandOption:!0,description:"The next version of the API"}).option("from-version",{string:!0,description:"The previous version of the API (e.g. 1.1.0)"}).option("from-generator-version",{string:!0,description:"The previous version of the generator (e.g. 1.1.0)"}).option("to-generator-version",{string:!0,description:"The next version of the generator (e.g. 1.1.0)"}).option("quiet",{boolean:!0,default:!1,alias:"q",description:"Whether to suppress output written to stderr"}).middleware(n=>{if(!z7t(n.fromGeneratorVersion,n.toGeneratorVersion))throw new Error("Both --from-generator-version and --to-generator-version must be provided together, or neither should be provided")}),async r=>{if(process.env.__FERN_DIFF_HEAP_RESPAWNED==null){let a=await import("fs"),c=1024*1024*1024,u=fo(zl(),r.from),l=fo(zl(),r.to),p=a.statSync(u,{throwIfNoEntry:!1})?.size??0,d=a.statSync(l,{throwIfNoEntry:!1})?.size??0;if(p>c||d>c){let{spawnSync:f}=await import("child_process"),h=f(process.execPath,["--max-old-space-size=8192",...process.execArgv,...process.argv.slice(1)],{env:{...process.env,__FERN_DIFF_HEAP_RESPAWNED:"1"},stdio:"inherit"});await t.exit({code:h.status??1});return}}let n=L7t(r.fromVersion),i=U7t({from:r.fromGeneratorVersion,to:r.toGeneratorVersion}),o=await DQu({context:t,from:r.from,to:r.to,fromVersion:n,generatorVersions:i});if(n!=null){let{errors:a,...c}=o;t.logger.info(JSON.stringify(c))}!r.quiet&&o.errors.length>0&&t.stderr.info(o.errors.join(`
3837
3837
  `));let s=o.bump==="major"?1:0;await t.exit({code:s})})}function pdg(e,t){e.command("sdk-diff <from-dir> <to-dir>",!1,r=>r.positional("from-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the previous version of the SDK"}).positional("to-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the next version of the SDK"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{await t.instrumentPostHogEvent({command:"fern sdk-diff"});let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),i=await A4u({context:t,project:n,fromDir:r.fromDir,toDir:r.toDir});r.json?t.logger.info(JSON.stringify(i,null,2)):(t.logger.info(`
3838
3838
  `+i.message),t.logger.info(`
3839
- Version Bump: ${i.version_bump}`))})}function fdg(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async n=>{await T4u({orgId:r.organization??(await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:n})})})}function ddg(e,t){e.command("add <generator>",`Add a code generator to ${Kp}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{let n=cKo(r.generator,t);await TQu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:n,groupName:r.group,cliContext:t})})}function mdg(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("id",{type:"string",description:"A stable identifier for the preview. Reusing the same ID overwrites the previous preview, keeping the URL stable."}).option("group",{type:"string",description:"The group to generate"}).option("generator",{type:"string",description:"The name of a specific generator to run"}).option("mode",{choices:Object.values(CUu),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file. For generators with local file system output, the .fernignore in the output directory is used automatically if not specified"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}).option("output",{type:"string",description:"Custom output directory (currently only supported with --preview for SDK generation)"}).option("replay",{boolean:!0,default:!0,hidden:!0,description:"Run replay after generation (use --no-replay to skip)"}).option("retry-rate-limited",{boolean:!0,default:!1,description:"Automatically retry with exponential backoff when receiving 429 Too Many Requests responses"}).option("require-env-vars",{boolean:!0,default:!0,description:"Require all referenced environment variables to be defined (use --no-require-env-vars to substitute empty strings for missing variables)"}).option("skip-fernignore",{boolean:!0,default:!1,description:"Skip the .fernignore file and generate all files. For remote generation, uploads an empty .fernignore. For local generation, skips reading .fernignore from the output directory."}),async r=>{if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.id!=null&&!r.preview)return t.failWithoutThrowing("The --id flag can only be used with --preview.");if(r.id!=null&&r.docs==null)return t.failWithoutThrowing("The --id flag can only be used with --docs.");if(r.skipUpload&&!r.preview)return t.failWithoutThrowing("The --skip-upload flag can only be used with --preview.");if(r.skipUpload&&r.docs==null)return t.failWithoutThrowing("The --skip-upload flag can only be used with --docs.");if(r.fernignore!=null&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation.");if(r["skip-fernignore"]&&r.fernignore!=null)return t.failWithoutThrowing("The --skip-fernignore and --fernignore flags cannot be used together.");if(r["dynamic-ir-only"]&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation.");if(r["dynamic-ir-only"]&&r.version==null)return t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version.");if(r["dynamic-ir-only"]&&r.docs!=null)return t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation.");if(r.output!=null&&!r.preview)return t.failWithoutThrowing("The --output flag currently only works with --preview.");if(r.output!=null&&r.docs!=null)return t.failWithoutThrowing("The --output flag is not supported for docs generation.");let n=r.generator!=null?cKo(r.generator,t):void 0;return r.api!=null?await g9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:n,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"]}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.generator!=null&&t.logger.warn("--generator is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await BUu({project:await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,previewId:r.id,force:r.force,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await g9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:n,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"]})})}function hdg(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await NUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function gdg(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await MUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function Adg(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await DUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function ydg(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await y9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await y9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await FUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function bdg(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>M0(o));await d4u({project:n,cliContext:t,token:i,version:r.version})})}function Edg(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>M0(o));await m4u({project:n,cliContext:t,token:i})})}function vdg(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: warn` instead."}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: error` instead."}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("json",{boolean:!0,description:"Output results as JSON to stdout.",default:!1}),async r=>{await j6u({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function Idg({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${BE}`,n=>n.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async n=>{await _6u({cliContext:t,includePreReleases:n.rc,targetVersion:n.to??n.version,fromVersion:n.from,fromGit:n["from-git"],yes:n.yes}),r()})}function wdg(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${BE}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await tUu({cliContext:t,targetVersion:r.version})})}function Cdg(e,t){e.command("api","Commands for managing your API specs",r=>(xdg(r,t),Ydg(r,t),r))}function xdg(e,t){e.command("update",`Pulls the latest OpenAPI spec from the specified origin in ${Kp} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await N4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function _dg(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await S4u({cliContext:t,version:r.version,dryRun:r.dryRun})})}function Sdg(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}).option("email",{string:!0,description:"Log in via enterprise SSO using your email address"}),async r=>{await t.runTask(async n=>{await t.instrumentPostHogEvent({command:"fern login"}),await PNt(n,{useDeviceCodeFlow:r.deviceCode,email:r.email})})})}function Odg(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await sKi(r)})})}function Tdg(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await lUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function Bdg(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await O4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function Pdg(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await c4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function Ddg(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(Rdg(r,t),Fdg(r,t),r))}function Rdg(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let n=fo(zl(),r.original),i=fo(zl(),r.modified),o=r.output!=null?fo(zl(),r.output):void 0;await UUu({originalPath:Gt.of(n),modifiedPath:Gt.of(i),outputPath:o!=null?Gt.of(o):void 0,cliContext:t})})}function Fdg(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await E9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function kdg(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await E9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function Ndg(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let n=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await Q6u({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:n}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:n})})}function jdg(e,t){e.command("docs","Commands for managing your docs",r=>(qdg(r,t),Gdg(r,t),Udg(r,t),Ldg(r,t),Qdg(r,t),r))}function Qdg(e,t){e.command("md",!1,r=>(Mdg(r,t),Wdg(r,t),r))}function Mdg(e,t){e.command("generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs md generate"});let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await MLu({project:n,cliContext:t,library:r.library})})}function Ldg(e,t){e.command("diff <preview-url> <files..>","Generate visual diffs between preview and production docs pages",r=>r.positional("preview-url",{type:"string",description:"The preview deployment URL (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}).positional("files",{type:"string",array:!0,description:"File paths to generate diffs for (e.g. fern/pages/intro.mdx)",demandOption:!0}).option("output",{type:"string",default:".fern/diff",description:"Output directory for diff images"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs diff"});let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),i=await FMu({cliContext:t,project:n,previewUrl:r.previewUrl,files:r.files??[],outputDir:r.output});t.logger.info(JSON.stringify(i,null,2))})}function Udg(e,t){e.command("preview","Commands for managing preview deployments",r=>(zdg(r,t),Vdg(r,t),r))}function zdg(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await ULu({cliContext:t,limit:r.limit,page:r.page})})}function Vdg(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await LLu({cliContext:t,previewUrl:r.url})})}function qdg(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let n;r.port!=null?n=r.port:n=await uOe({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let i;r.backendPort!=null?i=r.backendPort:i=await uOe({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let o=r.bundlePath;await kQu({loadProject:()=>lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:n,bundlePath:o,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:i,forceDownload:r.forceDownload})})}function Gdg(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await S6u({project:n,cliContext:t,errorOnBrokenLinks:r.strict})})}function Wdg(e,t){e.command("check","Validate MDX syntax in your docs",()=>{},async()=>{await t.instrumentPostHogEvent({command:"fern docs md check"});let r=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});r.docsWorkspaces==null&&t.failAndThrow("No docs workspace found");let n=r.docsWorkspaces,i=!1;await t.runTaskForWorkspace(n,async o=>{let{errors:s,totalFiles:a}=await P6u({workspace:n,context:o});D6u({errors:s,totalFiles:a,context:o}),s.length>0&&(i=!0)}),i&&t.failWithoutThrowing()})}function $dg(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await YUu({typeLocator:r.type,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:fo(zl(),r.pathToOutput),cliContext:t})})}function Hdg(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await U6u({project:await lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:fo(zl(),r.outputPath),cliContext:t})})}function Kdg(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await squ({project:await lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function Jdg(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await uUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:fo(zl(),r.outputPath),indent:r.indent})})}function Ydg(e,t){e.command("enrich <openapi>","Merge an AI examples overrides file into an OpenAPI spec",r=>r.positional("openapi",{type:"string",description:"Path to the OpenAPI spec",demandOption:!0}).option("file",{type:"string",alias:"f",description:"Path to the overrides file (e.g. ai_examples_overrides.yml)",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the enriched output file",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern api enrich"});let n=fo(zl(),r.openapi),i=fo(zl(),r.file),o=fo(zl(),r.output);await e4u({openapiPath:Gt.of(n),overridesPath:Gt.of(i),outputPath:Gt.of(o),cliContext:t})})}function Xdg(e,t){e.command("sdk",!1,r=>(Zdg(r,t),r.demandCommand()))}function Zdg(e,t){e.command("preview",!1,r=>r.option("group",{type:"string",description:"The generator group to preview"}).option("generator",{type:"string",description:"The name of a specific generator to run"}).option("api",{type:"string",description:"Only run the command on the provided API"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{await t.instrumentPostHogEvent({command:"fern sdk preview"});let n=r.generator!=null?cKo(r.generator,t):void 0;await x4u({cliContext:t,groupName:r.group,generatorFilter:n,apiName:r.api,json:r.json})})}function emg(e,t){e.command("beta",!1,r=>r.help(!1).version(!1).strict(!1).parserConfiguration({"unknown-options-as-args":!0}),async r=>{try{let n=r._.slice(1).map(String);await TLo(n)}catch(n){t.logger.error("CLI v2 failed:",String(n)),t.failWithoutThrowing()}})}function tmg(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=pqo,n=await rmg(process.stdin),i=eIt(BJo,n),o=r.run(i);await nmg(process.stdout,Aoi(p9t,o)),process.exit(0)})}function rmg(e){return new Promise((t,r)=>{let n=[];e.on("data",i=>n.push(i)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(n)))}),e.on("error",i=>{r(i)})})}function cKo(e,t){let r=M$e(e);return r!==e&&t.logger.warn(`"${e}" is not a valid generator name. Using "${r}" instead \u2014 the Docker org is "fernapi", not "${tNe}".`),r}function nmg(e,t){return new Promise((r,n)=>{e.write(t,i=>{i?n(i):r()})})}function img(e,t){e.command("install-dependencies",!1,r=>{},async()=>{await GUu({cliContext:t})})}function omg(e,t){e.command({command:"replay",describe:!1,builder:r=>(smg(r,t),amg(r,t),r),handler:()=>{}})}function smg(e,t){e.command("init",!1,r=>r.option("group",{type:"string",description:"Generator group from generators.yml (reads github config automatically)"}).option("api",{type:"string",description:"If multiple APIs, specify which API workspace to use"}).option("github",{type:"string",description:"GitHub repository (e.g., owner/repo). Overrides --group config."}).option("token",{type:"string",description:"GitHub token. Overrides --group config."}).option("dry-run",{type:"boolean",default:!1,description:"Report what would happen without making changes"}).option("max-commits",{type:"number",description:"Max commits to scan for generation history"}).option("force",{type:"boolean",default:!1,description:"Overwrite existing lockfile if Replay is already initialized"}),async r=>{await t.instrumentPostHogEvent({command:"fern replay init"});let n=r.github,i=r.token;if(r.group!=null){let o=await aqu(t,r.group,r.api);n=n??o.githubRepo,i=i??o.token}if(n==null||i==null){let o=n!=null?"Repository found but no token. Pass --token or set GITHUB_TOKEN environment variable.":"Either use --group to read from generators.yml, or provide --github and --token directly.";return t.failAndThrow(`Missing required github config. ${o}`)}t.logger.info(`Initializing Replay for: ${n}`),r.dryRun&&t.logger.info("(dry-run mode)");try{let o=await(0,Lvt.replayInit)({githubRepo:n,token:i,dryRun:r.dryRun,maxCommitsToScan:r.maxCommits,force:r.force}),s=(0,Lvt.formatBootstrapSummary)(o);for(let f of s)f.level==="warn"?t.logger.warn(f.message):t.logger.info(f.message);if(!o.bootstrap.generationCommit)return;if(r.dryRun){t.logger.info(`
3839
+ Version Bump: ${i.version_bump}`))})}function fdg(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async n=>{await T4u({orgId:r.organization??(await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:n})})})}function ddg(e,t){e.command("add <generator>",`Add a code generator to ${Kp}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{let n=cKo(r.generator,t);await TQu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:n,groupName:r.group,cliContext:t})})}function mdg(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("id",{type:"string",description:"A stable identifier for the preview. Reusing the same ID overwrites the previous preview, keeping the URL stable."}).option("group",{type:"string",description:"The group to generate"}).option("generator",{type:"string",description:"The name of a specific generator to run"}).option("mode",{choices:Object.values(CUu),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file. For generators with local file system output, the .fernignore in the output directory is used automatically if not specified"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}).option("output",{type:"string",description:"Custom output directory (currently only supported with --preview for SDK generation)"}).option("replay",{boolean:!0,default:!0,hidden:!0,description:"Run replay after generation (use --no-replay to skip)"}).option("retry-rate-limited",{boolean:!0,default:!1,description:"Automatically retry with exponential backoff when receiving 429 Too Many Requests responses"}).option("require-env-vars",{boolean:!0,default:!0,description:"Require all referenced environment variables to be defined (use --no-require-env-vars to substitute empty strings for missing variables)"}).option("skip-fernignore",{boolean:!0,default:!1,description:"Skip the .fernignore file and generate all files. For remote generation, uploads an empty .fernignore. For local generation, skips reading .fernignore from the output directory."}),async r=>{if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.id!=null&&!r.preview)return t.failWithoutThrowing("The --id flag can only be used with --preview.");if(r.id!=null&&r.docs==null)return t.failWithoutThrowing("The --id flag can only be used with --docs.");if(r.skipUpload&&!r.preview)return t.failWithoutThrowing("The --skip-upload flag can only be used with --preview.");if(r.skipUpload&&r.docs==null)return t.failWithoutThrowing("The --skip-upload flag can only be used with --docs.");if(r.fernignore!=null&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation.");if(r["skip-fernignore"]&&r.fernignore!=null)return t.failWithoutThrowing("The --skip-fernignore and --fernignore flags cannot be used together.");if(r["dynamic-ir-only"]&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation.");if(r["dynamic-ir-only"]&&r.version==null)return t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version.");if(r["dynamic-ir-only"]&&r.docs!=null)return t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation.");if(r.output!=null&&!r.preview)return t.failWithoutThrowing("The --output flag currently only works with --preview.");if(r.output!=null&&r.docs!=null)return t.failWithoutThrowing("The --output flag is not supported for docs generation.");let n=r.generator!=null?cKo(r.generator,t):void 0;return r.api!=null?await g9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:n,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"]}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.generator!=null&&t.logger.warn("--generator is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await BUu({project:await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,previewId:r.id,force:r.force,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await g9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:n,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"]})})}function hdg(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await NUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function gdg(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await MUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function Adg(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await DUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:fo(zl(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function ydg(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await y9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await y9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await FUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:fo(zl(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function bdg(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>M0(o));await d4u({project:n,cliContext:t,token:i,version:r.version})})}function Edg(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>M0(o));await m4u({project:n,cliContext:t,token:i})})}function vdg(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: warn` instead."}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: error` instead."}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("json",{boolean:!0,description:"Output results as JSON to stdout.",default:!1}),async r=>{await j6u({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function Idg({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${BE}`,n=>n.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async n=>{await _6u({cliContext:t,includePreReleases:n.rc,targetVersion:n.to??n.version,fromVersion:n.from,fromGit:n["from-git"],yes:n.yes}),r()})}function wdg(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${BE}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await tUu({cliContext:t,targetVersion:r.version})})}function Cdg(e,t){e.command("api","Commands for managing your API specs",r=>(xdg(r,t),Ydg(r,t),r))}function xdg(e,t){e.command("update",`Pulls the latest OpenAPI spec from the specified origin in ${Kp} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await N4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function _dg(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await S4u({cliContext:t,version:r.version,dryRun:r.dryRun})})}function Sdg(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}).option("email",{string:!0,description:"Log in via enterprise SSO using your email address"}),async r=>{await t.runTask(async n=>{await t.instrumentPostHogEvent({command:"fern login"}),await PNt(n,{useDeviceCodeFlow:r.deviceCode,email:r.email})})})}function Odg(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await sKi(r)})})}function Tdg(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await lUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function Bdg(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await O4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function Pdg(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await c4u({cliContext:t,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function Ddg(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(Rdg(r,t),Fdg(r,t),r))}function Rdg(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let n=fo(zl(),r.original),i=fo(zl(),r.modified),o=r.output!=null?fo(zl(),r.output):void 0;await UUu({originalPath:Gt.of(n),modifiedPath:Gt.of(i),outputPath:o!=null?Gt.of(o):void 0,cliContext:t})})}function Fdg(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await E9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function kdg(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await E9o({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function Ndg(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Dn.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let n=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await Q6u({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:n}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:n})})}function jdg(e,t){e.command("docs","Commands for managing your docs",r=>(qdg(r,t),Gdg(r,t),Udg(r,t),Ldg(r,t),Qdg(r,t),r))}function Qdg(e,t){e.command("md",!1,r=>(Mdg(r,t),Wdg(r,t),r))}function Mdg(e,t){e.command("generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs md generate"});let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await MLu({project:n,cliContext:t,library:r.library})})}function Ldg(e,t){e.command("diff <preview-url> <files..>","Generate visual diffs between preview and production docs pages",r=>r.positional("preview-url",{type:"string",description:"The preview deployment URL (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}).positional("files",{type:"string",array:!0,description:"File paths to generate diffs for (e.g. fern/pages/intro.mdx)",demandOption:!0}).option("output",{type:"string",default:".fern/diff",description:"Output directory for diff images"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs diff"});let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),i=await FMu({cliContext:t,project:n,previewUrl:r.previewUrl,files:r.files??[],outputDir:r.output});t.logger.info(JSON.stringify(i,null,2))})}function Udg(e,t){e.command("preview","Commands for managing preview deployments",r=>(zdg(r,t),Vdg(r,t),r))}function zdg(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await ULu({cliContext:t,limit:r.limit,page:r.page})})}function Vdg(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await LLu({cliContext:t,previewUrl:r.url})})}function qdg(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let n;r.port!=null?n=r.port:n=await uOe({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let i;r.backendPort!=null?i=r.backendPort:i=await uOe({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let o=r.bundlePath;await kQu({loadProject:()=>lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:n,bundlePath:o,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:i,forceDownload:r.forceDownload})})}function Gdg(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let n=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await S6u({project:n,cliContext:t,errorOnBrokenLinks:r.strict})})}function Wdg(e,t){e.command("check","Validate MDX syntax in your docs",()=>{},async()=>{await t.instrumentPostHogEvent({command:"fern docs md check"});let r=await lp(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});r.docsWorkspaces==null&&t.failAndThrow("No docs workspace found");let n=r.docsWorkspaces,i=!1;await t.runTaskForWorkspace(n,async o=>{let{errors:s,totalFiles:a}=await P6u({workspace:n,context:o});D6u({errors:s,totalFiles:a,context:o}),s.length>0&&(i=!0)}),i&&t.failWithoutThrowing()})}function $dg(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await YUu({typeLocator:r.type,project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:fo(zl(),r.pathToOutput),cliContext:t})})}function Hdg(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await U6u({project:await lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:fo(zl(),r.outputPath),cliContext:t})})}function Kdg(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await squ({project:await lp(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function Jdg(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await uUu({project:await lp(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:fo(zl(),r.outputPath),indent:r.indent})})}function Ydg(e,t){e.command("enrich <openapi>","Merge an AI examples overrides file into an OpenAPI spec",r=>r.positional("openapi",{type:"string",description:"Path to the OpenAPI spec",demandOption:!0}).option("file",{type:"string",alias:"f",description:"Path to the overrides file (e.g. ai_examples_overrides.yml)",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the enriched output file",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern api enrich"});let n=fo(zl(),r.openapi),i=fo(zl(),r.file),o=fo(zl(),r.output);await e4u({openapiPath:Gt.of(n),overridesPath:Gt.of(i),outputPath:Gt.of(o),cliContext:t})})}function Xdg(e,t){e.command("sdk",!1,r=>(Zdg(r,t),r.demandCommand()))}function Zdg(e,t){e.command("preview",!1,r=>r.option("group",{type:"string",description:"The generator group to preview"}).option("generator",{type:"string",description:"The name of a specific generator to run"}).option("api",{type:"string",description:"Only run the command on the provided API"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{await t.instrumentPostHogEvent({command:"fern sdk preview"});let n=r.generator!=null?cKo(r.generator,t):void 0;await x4u({cliContext:t,groupName:r.group,generatorFilter:n,apiName:r.api,json:r.json})})}function emg(e,t){e.command("beta",!1,r=>r.help(!1).version(!1).strict(!1).parserConfiguration({"unknown-options-as-args":!0}),async r=>{try{let n=r._.slice(1).map(String);await TLo(n)}catch(n){t.logger.error("CLI v2 failed:",String(n)),t.failWithoutThrowing()}})}function tmg(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=pqo,n=await rmg(process.stdin),i=eIt(BJo,n),o=r.run(i);await nmg(process.stdout,Aoi(p9t,o)),process.exit(0)})}function rmg(e){return new Promise((t,r)=>{let n=[];e.on("data",i=>n.push(i)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(n)))}),e.on("error",i=>{r(i)})})}function cKo(e,t){let r=M$e(e);return r!==e&&t.logger.warn(`"${e}" is not a valid generator name. Using "${r}" instead \u2014 the Docker org is "fernapi", not "${tNe}".`),r}function nmg(e,t){return new Promise((r,n)=>{e.write(t,i=>{i?n(i):r()})})}function img(e,t){e.command("install-dependencies",!1,r=>{},async()=>{await GUu({cliContext:t})})}function omg(e,t){e.command({command:"replay",describe:!1,builder:r=>(smg(r,t),amg(r,t),r),handler:()=>{}})}function smg(e,t){e.command("init",!1,r=>r.option("group",{type:"string",description:"Generator group from generators.yml (reads github config automatically)"}).option("api",{type:"string",description:"If multiple APIs, specify which API workspace to use"}).option("github",{type:"string",description:"GitHub repository (e.g., owner/repo). Overrides --group config."}).option("token",{type:"string",description:"GitHub token. Overrides --group config."}).option("dry-run",{type:"boolean",default:!1,description:"Report what would happen without making changes"}).option("max-commits",{type:"number",description:"Max commits to scan for generation history"}).option("force",{type:"boolean",default:!1,description:"Overwrite existing lockfile if Replay is already initialized"}),async r=>{await t.instrumentPostHogEvent({command:"fern replay init"});let n=r.github,i=r.token;if(r.group!=null){let o=await aqu(t,r.group,r.api);n=n??o.githubRepo,i=i??o.token}if(n==null)return t.failAndThrow("Missing required github config. Either use --group to read from generators.yml, or provide --github directly.");i==null&&t.logger.warn("No GitHub token found. Clone may fail for private repos. Set GITHUB_TOKEN or pass --token."),t.logger.info(`Initializing Replay for: ${n}`),r.dryRun&&t.logger.info("(dry-run mode)");try{let o=await(0,Lvt.replayInit)({githubRepo:n,token:i,dryRun:r.dryRun,maxCommitsToScan:r.maxCommits,force:r.force}),s=(0,Lvt.formatBootstrapSummary)(o);for(let f of s)f.level==="warn"?t.logger.warn(f.message):t.logger.info(f.message);if(!o.bootstrap.generationCommit)return;if(r.dryRun){t.logger.info(`
3840
3840
  Dry run complete. No changes made.`);return}if(o.lockfileContent==null)return t.failAndThrow("Bootstrap succeeded but lockfile content is missing.");let a=await t.runTask(f=>M0(f)),{owner:c,repo:u}=cmg(n),l=GPt(),p=await fetch(`${l}/api/remote-gen/replay/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.value}`},body:JSON.stringify({owner:c,repo:u,lockfileContents:o.lockfileContent,fernignoreEntries:o.fernignoreEntries,prBody:o.prBody})});if(!p.ok){if(p.status===404)return t.failAndThrow("The Fern GitHub App is not installed on this repository. Install it at https://github.com/apps/fern-api to enable server-side PR creation.");let f=await p.text();return t.failAndThrow(`Failed to create PR via Fern: ${f}`)}let d=await p.json();t.logger.info(`
3841
3841
  PR created: ${d.prUrl}`),t.logger.info("Merge the PR to enable Replay for this repository.")}catch(o){t.failAndThrow(`Failed to initialize Replay: ${ji(o)}`)}})}function amg(e,t){e.command("resolve [directory]",!1,r=>r.positional("directory",{type:"string",default:".",description:"SDK directory containing .fern/replay.lock"}).option("no-check-markers",{type:"boolean",default:!1,description:"Skip checking for remaining conflict markers before committing"}),async r=>{await t.instrumentPostHogEvent({command:"fern replay resolve"});let n=fo(zl(),r.directory??".");try{let i=await(0,Lvt.replayResolve)({outputDir:n,checkMarkers:!r.noCheckMarkers});switch(i.phase){case"applied":if(t.logger.info(`Applied ${i.patchesApplied} unresolved patch(es) to your working tree.`),i.unresolvedFiles&&i.unresolvedFiles.length>0){t.logger.info(`
3842
3842
  Files with conflict markers:`);for(let o of i.unresolvedFiles)t.logger.info(` ${o}`);t.logger.info("\nResolve the conflicts in your editor, then run `fern replay resolve` again to finalize.")}break;case"committed":t.logger.info(`Resolved ${i.patchesResolved} patch(es) and committed. Push when ready.`);break;case"nothing-to-resolve":t.logger.info("No unresolved patches found.");break;default:if(!i.success)if(i.reason==="unresolved-conflicts"&&i.unresolvedFiles){t.logger.warn("Some files still have conflict markers:");for(let o of i.unresolvedFiles)t.logger.warn(` ${o}`);t.logger.warn("Resolve them first, then run `fern replay resolve` again.")}else t.failAndThrow(`Resolve failed: ${i.reason??"unknown error"}`)}}catch(i){t.failAndThrow(`Failed to resolve: ${ji(i)}`)}})}function cmg(e){let r=e.replace(/^https?:\/\//,"").replace(/\.git$/,"").replace(/^github\.com\//,"").split("/"),n=r[r.length-2],i=r[r.length-1];if(n==null||i==null)throw new Error(`Could not parse owner/repo from: ${e}`);return{owner:n,repo:i}}