fern-api 3.49.1 → 3.49.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +5 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -925,7 +925,7 @@ ${l.indent}`:""}${iQp(u)}:${c.indent?" ":""}`;return o=!1,s=!0,c.objectItem=void
|
|
|
925
925
|
`),n.showHelp(),process.exit(1)});return tRp(t),gLp(t),PLp(t),t}var uR="fern",kq="definition",KVa="openapi",jLp="changelog",X_c="asyncapi",xB="api.yml",Odn="__package__",Zb=`${Odn}.yml`,lUo="dependencies.yml",hD="generators.yml",fUo="generators.yaml",wLp="dependencies.yml",w0="docs.yml",E4="fern.config.json",Z_c="api",yHt=".fernignore";var ELp="snippet-templates.json";var rXn="default-group",SLp="spec-origin",MLp="async-api",DLp="openapi",BLp="openapi-overrides",ILp="api-settings";var oNi="apis",JVa="local";var Qt={};Yt(Qt,{BRAND:()=>v_S,DIRTY:()=>mdn,EMPTY_PATH:()=>YpS,INVALID:()=>lf,NEVER:()=>rhS,OK:()=>j8,ParseStatus:()=>S4,Schema:()=>uy,ZodAny:()=>fxi,ZodArray:()=>lNi,ZodBigInt:()=>Pdn,ZodBoolean:()=>jdn,ZodBranded:()=>YVa,ZodCatch:()=>Rdn,ZodDate:()=>wdn,ZodDefault:()=>Tdn,ZodDiscriminatedUnion:()=>_Uo,ZodEffects:()=>M0e,ZodEnum:()=>Cdn,ZodError:()=>NJ,ZodFirstPartyTypeKind:()=>wf,ZodFunction:()=>yUo,ZodIntersection:()=>Ddn,ZodIssueCode:()=>wi,ZodLazy:()=>Bdn,ZodLiteral:()=>Idn,ZodMap:()=>sXn,ZodNaN:()=>lXn,ZodNativeEnum:()=>qdn,ZodNever:()=>OVt,ZodNull:()=>Sdn,ZodNullable:()=>gHt,ZodNumber:()=>Adn,ZodObject:()=>FJ,ZodOptional:()=>E0e,ZodParsedType:()=>Vo,ZodPipeline:()=>XVa,ZodPromise:()=>dxi,ZodReadonly:()=>zdn,ZodRecord:()=>hUo,ZodSchema:()=>uy,ZodSet:()=>cXn,ZodString:()=>lxi,ZodSymbol:()=>oXn,ZodTransformer:()=>M0e,ZodTuple:()=>vHt,ZodType:()=>uy,ZodUndefined:()=>Edn,ZodUnion:()=>Mdn,ZodUnknown:()=>cNi,ZodVoid:()=>uXn,addIssueToContext:()=>Qa,any:()=>S_S,array:()=>I_S,bigint:()=>A_S,boolean:()=>VLp,coerce:()=>thS,custom:()=>QLp,date:()=>P_S,datetimeRegex:()=>NLp,defaultErrorMap:()=>uNi,discriminatedUnion:()=>R_S,effect:()=>K_S,enum:()=>G_S,function:()=>L_S,getErrorMap:()=>iXn,getParsedType:()=>bHt,instanceof:()=>O_S,intersection:()=>z_S,isAborted:()=>dUo,isAsync:()=>nXn,isDirty:()=>pUo,isValid:()=>cxi,late:()=>g_S,lazy:()=>V_S,literal:()=>W_S,makeIssue:()=>$Va,map:()=>Q_S,nan:()=>m_S,nativeEnum:()=>x_S,never:()=>D_S,null:()=>E_S,nullable:()=>$_S,number:()=>LLp,object:()=>C_S,objectUtil:()=>k_c,oboolean:()=>ehS,onumber:()=>k_S,optional:()=>J_S,ostring:()=>Z_S,pipeline:()=>X_S,preprocess:()=>Y_S,promise:()=>H_S,quotelessJson:()=>KpS,record:()=>F_S,set:()=>U_S,setErrorMap:()=>$pS,strictObject:()=>q_S,string:()=>ULp,symbol:()=>j_S,transformer:()=>K_S,tuple:()=>N_S,undefined:()=>w_S,union:()=>T_S,unknown:()=>M_S,util:()=>$v,void:()=>B_S});var $v;(function(e){e.assertEqual=n=>{};function t(n){}e.assertIs=t;function r(n){throw new Error}e.assertNever=r,e.arrayToEnum=n=>{let a={};for(let o of n)a[o]=o;return a},e.getValidEnumValues=n=>{let a=e.objectKeys(n).filter(c=>typeof n[n[c]]!="number"),o={};for(let c of a)o[c]=n[c];return e.objectValues(o)},e.objectValues=n=>e.objectKeys(n).map(function(a){return n[a]}),e.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&a.push(o);return a},e.find=(n,a)=>{for(let o of n)if(a(o))return o},e.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function i(n,a=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}e.joinValues=i,e.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})($v||($v={}));var k_c;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(k_c||(k_c={}));var Vo=$v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),bHt=e=>{switch(typeof e){case"undefined":return Vo.undefined;case"string":return Vo.string;case"number":return Number.isNaN(e)?Vo.nan:Vo.number;case"boolean":return Vo.boolean;case"function":return Vo.function;case"bigint":return Vo.bigint;case"symbol":return Vo.symbol;case"object":return Array.isArray(e)?Vo.array:e===null?Vo.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Vo.promise:typeof Map<"u"&&e instanceof Map?Vo.map:typeof Set<"u"&&e instanceof Set?Vo.set:typeof Date<"u"&&e instanceof Date?Vo.date:Vo.object;default:return Vo.unknown}};var wi=$v.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"]),KpS=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),NJ=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};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(a){return a.message},i={_errors:[]},n=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)i._errors.push(r(o));else{let c=i,d=0;for(;d<o.path.length;){let s=o.path[d];d===o.path.length-1?(c[s]=c[s]||{_errors:[]},c[s]._errors.push(r(o))):c[s]=c[s]||{_errors:[]},c=c[s],d++}}};return n(this),i}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,$v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},i=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];r[a]=r[a]||[],r[a].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}};NJ.create=e=>new NJ(e);var JpS=(e,t)=>{let r;switch(e.code){case wi.invalid_type:e.received===Vo.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case wi.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,$v.jsonStringifyReplacer)}`;break;case wi.unrecognized_keys:r=`Unrecognized key(s) in object: ${$v.joinValues(e.keys,", ")}`;break;case wi.invalid_union:r="Invalid input";break;case wi.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${$v.joinValues(e.options)}`;break;case wi.invalid_enum_value:r=`Invalid enum value. Expected ${$v.joinValues(e.options)}, received '${e.received}'`;break;case wi.invalid_arguments:r="Invalid function arguments";break;case wi.invalid_return_type:r="Invalid function return type";break;case wi.invalid_date:r="Invalid date";break;case wi.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}"`:$v.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case wi.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 wi.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 wi.custom:r="Invalid input";break;case wi.invalid_intersection_types:r="Intersection results could not be merged";break;case wi.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case wi.not_finite:r="Number must be finite";break;default:r=t.defaultError,$v.assertNever(e)}return{message:r}},uNi=JpS;var CLp=uNi;function $pS(e){CLp=e}function iXn(){return CLp}var $Va=e=>{let{data:t,path:r,errorMaps:i,issueData:n}=e,a=[...r,...n.path||[]],o={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let c="",d=i.filter(s=>!!s).slice().reverse();for(let s of d)c=s(o,{data:t,defaultError:c}).message;return{...n,path:a,message:c}},YpS=[];function Qa(e,t){let r=iXn(),i=$Va({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===uNi?void 0:uNi].filter(n=>!!n)});e.common.issues.push(i)}var S4=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 i=[];for(let n of r){if(n.status==="aborted")return lf;n.status==="dirty"&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let n of r){let a=await n.key,o=await n.value;i.push({key:a,value:o})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:a,value:o}=n;if(a.status==="aborted"||o.status==="aborted")return lf;a.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(i[a.value]=o.value)}return{status:t.value,value:i}}},lf=Object.freeze({status:"aborted"}),mdn=e=>({status:"dirty",value:e}),j8=e=>({status:"valid",value:e}),dUo=e=>e.status==="aborted",pUo=e=>e.status==="dirty",cxi=e=>e.status==="valid",nXn=e=>typeof Promise<"u"&&e instanceof Promise;var Gs;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Gs||(Gs={}));var S0e=class{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}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}},qLp=(e,t)=>{if(cxi(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 NJ(e.common.issues);return this._error=r,this._error}}};function W_(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:n}=e;if(t&&(r||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(o,c)=>{let{message:d}=e;return o.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:d??i??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:d??r??c.defaultError}},description:n}}var uy=class{get description(){return this._def.description}_getType(t){return bHt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:bHt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new S4,ctx:{common:t.parent.common,data:t.data,parsedType:bHt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(nXn(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 i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:bHt(t)},n=this._parseSync({data:t,path:i.path,parent:i});return qLp(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:bHt(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return cxi(i)?{value:i.value}:{issues:r.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>cxi(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:bHt(t)},n=this._parse({data:t,path:i.path,parent:i}),a=await(nXn(n)?n:Promise.resolve(n));return qLp(i,a)}refine(t,r){let i=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,a)=>{let o=t(n),c=()=>a.addIssue({code:wi.custom,...i(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(t,r){return this._refinement((i,n)=>t(i)?!0:(n.addIssue(typeof r=="function"?r(i,n):r),!1))}_refinement(t){return new M0e({schema:this,typeName:wf.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 E0e.create(this,this._def)}nullable(){return gHt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lNi.create(this)}promise(){return dxi.create(this,this._def)}or(t){return Mdn.create([this,t],this._def)}and(t){return Ddn.create(this,t,this._def)}transform(t){return new M0e({...W_(this._def),schema:this,typeName:wf.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Tdn({...W_(this._def),innerType:this,defaultValue:r,typeName:wf.ZodDefault})}brand(){return new YVa({typeName:wf.ZodBranded,type:this,...W_(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Rdn({...W_(this._def),innerType:this,catchValue:r,typeName:wf.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return XVa.create(this,t)}readonly(){return zdn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},XpS=/^c[^\s-]{8,}$/i,ZpS=/^[0-9a-z]+$/,kpS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,e_S=/^[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,t_S=/^[a-z0-9_-]{21}$/i,r_S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,i_S=/^[-+]?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)?)??$/,n_S=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,a_S="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ehc,o_S=/^(?:(?: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])$/,u_S=/^(?:(?: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])$/,s_S=/^(([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]))$/,c_S=/^(([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])$/,l_S=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,f_S=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,RLp="((\\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])))",d_S=new RegExp(`^${RLp}$`);function zLp(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 p_S(e){return new RegExp(`^${zLp(e)}$`)}function NLp(e){let t=`${RLp}T${zLp(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 __S(e,t){return!!((t==="v4"||!t)&&o_S.test(e)||(t==="v6"||!t)&&s_S.test(e))}function h_S(e,t){if(!r_S.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(i));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function y_S(e,t){return!!((t==="v4"||!t)&&u_S.test(e)||(t==="v6"||!t)&&c_S.test(e))}var lxi=class e extends uy{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Vo.string){let a=this._getOrReturnCtx(t);return Qa(a,{code:wi.invalid_type,expected:Vo.string,received:a.parsedType}),lf}let i=new S4,n;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")t.data.length>a.value&&(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){let o=t.data.length>a.value,c=t.data.length<a.value;(o||c)&&(n=this._getOrReturnCtx(t,n),o?Qa(n,{code:wi.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):c&&Qa(n,{code:wi.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")n_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"email",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")ehc||(ehc=new RegExp(a_S,"u")),ehc.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"emoji",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")e_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"uuid",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")t_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"nanoid",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")XpS.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"cuid",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")ZpS.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"cuid2",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")kpS.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"ulid",code:wi.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),Qa(n,{validation:"url",code:wi.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"regex",code:wi.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?NLp(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?d_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?p_S(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?i_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"duration",code:wi.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?__S(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"ip",code:wi.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?h_S(t.data,a.alg)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"jwt",code:wi.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?y_S(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"cidr",code:wi.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?l_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"base64",code:wi.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?f_S.test(t.data)||(n=this._getOrReturnCtx(t,n),Qa(n,{validation:"base64url",code:wi.invalid_string,message:a.message}),i.dirty()):$v.assertNever(a);return{status:i.value,value:t.data}}_regex(t,r,i){return this.refinement(n=>t.test(n),{validation:r,code:wi.invalid_string,...Gs.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Gs.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Gs.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Gs.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Gs.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Gs.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Gs.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Gs.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Gs.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Gs.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Gs.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Gs.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Gs.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Gs.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,...Gs.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,...Gs.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Gs.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Gs.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Gs.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Gs.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Gs.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Gs.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Gs.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Gs.errToObj(r)})}nonempty(t){return this.min(1,Gs.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}};lxi.create=e=>new lxi({checks:[],typeName:wf.ZodString,coerce:e?.coerce??!1,...W_(e)});function b_S(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,n=r>i?r:i,a=Number.parseInt(e.toFixed(n).replace(".","")),o=Number.parseInt(t.toFixed(n).replace(".",""));return a%o/10**n}var Adn=class e extends uy{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)!==Vo.number){let a=this._getOrReturnCtx(t);return Qa(a,{code:wi.invalid_type,expected:Vo.number,received:a.parsedType}),lf}let i,n=new S4;for(let a of this._def.checks)a.kind==="int"?$v.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?b_S(t.data,a.value)!==0&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.not_finite,message:a.message}),n.dirty()):$v.assertNever(a);return{status:n.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Gs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Gs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Gs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Gs.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:Gs.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Gs.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Gs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Gs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Gs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Gs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Gs.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Gs.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Gs.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Gs.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"&&$v.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(r===null||i.value>r)&&(r=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Adn.create=e=>new Adn({checks:[],typeName:wf.ZodNumber,coerce:e?.coerce||!1,...W_(e)});var Pdn=class e extends uy{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)!==Vo.bigint)return this._getInvalidInput(t);let i,n=new S4;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),Qa(i,{code:wi.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):$v.assertNever(a);return{status:n.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Qa(r,{code:wi.invalid_type,expected:Vo.bigint,received:r.parsedType}),lf}gte(t,r){return this.setLimit("min",t,!0,Gs.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Gs.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Gs.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Gs.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:Gs.toString(n)}]})}_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:Gs.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Gs.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Gs.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Gs.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Gs.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}};Pdn.create=e=>new Pdn({checks:[],typeName:wf.ZodBigInt,coerce:e?.coerce??!1,...W_(e)});var jdn=class extends uy{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Vo.boolean){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.boolean,received:i.parsedType}),lf}return j8(t.data)}};jdn.create=e=>new jdn({typeName:wf.ZodBoolean,coerce:e?.coerce||!1,...W_(e)});var wdn=class e extends uy{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Vo.date){let a=this._getOrReturnCtx(t);return Qa(a,{code:wi.invalid_type,expected:Vo.date,received:a.parsedType}),lf}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return Qa(a,{code:wi.invalid_date}),lf}let i=new S4,n;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(n=this._getOrReturnCtx(t,n),Qa(n,{code:wi.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):$v.assertNever(a);return{status:i.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:Gs.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Gs.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}};wdn.create=e=>new wdn({checks:[],coerce:e?.coerce||!1,typeName:wf.ZodDate,...W_(e)});var oXn=class extends uy{_parse(t){if(this._getType(t)!==Vo.symbol){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.symbol,received:i.parsedType}),lf}return j8(t.data)}};oXn.create=e=>new oXn({typeName:wf.ZodSymbol,...W_(e)});var Edn=class extends uy{_parse(t){if(this._getType(t)!==Vo.undefined){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.undefined,received:i.parsedType}),lf}return j8(t.data)}};Edn.create=e=>new Edn({typeName:wf.ZodUndefined,...W_(e)});var Sdn=class extends uy{_parse(t){if(this._getType(t)!==Vo.null){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.null,received:i.parsedType}),lf}return j8(t.data)}};Sdn.create=e=>new Sdn({typeName:wf.ZodNull,...W_(e)});var fxi=class extends uy{constructor(){super(...arguments),this._any=!0}_parse(t){return j8(t.data)}};fxi.create=e=>new fxi({typeName:wf.ZodAny,...W_(e)});var cNi=class extends uy{constructor(){super(...arguments),this._unknown=!0}_parse(t){return j8(t.data)}};cNi.create=e=>new cNi({typeName:wf.ZodUnknown,...W_(e)});var OVt=class extends uy{_parse(t){let r=this._getOrReturnCtx(t);return Qa(r,{code:wi.invalid_type,expected:Vo.never,received:r.parsedType}),lf}};OVt.create=e=>new OVt({typeName:wf.ZodNever,...W_(e)});var uXn=class extends uy{_parse(t){if(this._getType(t)!==Vo.undefined){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.void,received:i.parsedType}),lf}return j8(t.data)}};uXn.create=e=>new uXn({typeName:wf.ZodVoid,...W_(e)});var lNi=class e extends uy{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==Vo.array)return Qa(r,{code:wi.invalid_type,expected:Vo.array,received:r.parsedType}),lf;if(n.exactLength!==null){let o=r.data.length>n.exactLength.value,c=r.data.length<n.exactLength.value;(o||c)&&(Qa(r,{code:o?wi.too_big:wi.too_small,minimum:c?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(Qa(r,{code:wi.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(Qa(r,{code:wi.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((o,c)=>n.type._parseAsync(new S0e(r,o,r.path,c)))).then(o=>S4.mergeArray(i,o));let a=[...r.data].map((o,c)=>n.type._parseSync(new S0e(r,o,r.path,c)));return S4.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Gs.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Gs.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Gs.toString(r)}})}nonempty(t){return this.min(1,t)}};lNi.create=(e,t)=>new lNi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wf.ZodArray,...W_(t)});function aXn(e){if(e instanceof FJ){let t={};for(let r in e.shape){let i=e.shape[r];t[r]=E0e.create(aXn(i))}return new FJ({...e._def,shape:()=>t})}else return e instanceof lNi?new lNi({...e._def,type:aXn(e.element)}):e instanceof E0e?E0e.create(aXn(e.unwrap())):e instanceof gHt?gHt.create(aXn(e.unwrap())):e instanceof vHt?vHt.create(e.items.map(t=>aXn(t))):e}var FJ=class e extends uy{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=$v.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Vo.object){let s=this._getOrReturnCtx(t);return Qa(s,{code:wi.invalid_type,expected:Vo.object,received:s.parsedType}),lf}let{status:i,ctx:n}=this._processInputParams(t),{shape:a,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof OVt&&this._def.unknownKeys==="strip"))for(let s in n.data)o.includes(s)||c.push(s);let d=[];for(let s of o){let u=a[s],l=n.data[s];d.push({key:{status:"valid",value:s},value:u._parse(new S0e(n,l,n.path,s)),alwaysSet:s in n.data})}if(this._def.catchall instanceof OVt){let s=this._def.unknownKeys;if(s==="passthrough")for(let u of c)d.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(s==="strict")c.length>0&&(Qa(n,{code:wi.unrecognized_keys,keys:c}),i.dirty());else if(s!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let s=this._def.catchall;for(let u of c){let l=n.data[u];d.push({key:{status:"valid",value:u},value:s._parse(new S0e(n,l,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let s=[];for(let u of d){let l=await u.key,p=await u.value;s.push({key:l,value:p,alwaysSet:u.alwaysSet})}return s}).then(s=>S4.mergeObjectSync(i,s)):S4.mergeObjectSync(i,d)}get shape(){return this._def.shape()}strict(t){return Gs.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return r.code==="unrecognized_keys"?{message:Gs.errToObj(t).message??n}:{message:n}}}:{}})}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:wf.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let i of $v.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let i of $v.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}deepPartial(){return aXn(this)}partial(t){let r={};for(let i of $v.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let i of $v.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof E0e;)a=a._def.innerType;r[i]=a}return new e({...this._def,shape:()=>r})}keyof(){return FLp($v.objectKeys(this.shape))}};FJ.create=(e,t)=>new FJ({shape:()=>e,unknownKeys:"strip",catchall:OVt.create(),typeName:wf.ZodObject,...W_(t)});FJ.strictCreate=(e,t)=>new FJ({shape:()=>e,unknownKeys:"strict",catchall:OVt.create(),typeName:wf.ZodObject,...W_(t)});FJ.lazycreate=(e,t)=>new FJ({shape:e,unknownKeys:"strip",catchall:OVt.create(),typeName:wf.ZodObject,...W_(t)});var Mdn=class extends uy{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;function n(a){for(let c of a)if(c.result.status==="valid")return c.result;for(let c of a)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let o=a.map(c=>new NJ(c.ctx.common.issues));return Qa(r,{code:wi.invalid_union,unionErrors:o}),lf}if(r.common.async)return Promise.all(i.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let a,o=[];for(let d of i){let s={...r,common:{...r.common,issues:[]},parent:null},u=d._parseSync({data:r.data,path:r.path,parent:s});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:s}),s.common.issues.length&&o.push(s.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let c=o.map(d=>new NJ(d));return Qa(r,{code:wi.invalid_union,unionErrors:c}),lf}}get options(){return this._def.options}};Mdn.create=(e,t)=>new Mdn({options:e,typeName:wf.ZodUnion,...W_(t)});var sNi=e=>e instanceof Bdn?sNi(e.schema):e instanceof M0e?sNi(e.innerType()):e instanceof Idn?[e.value]:e instanceof Cdn?e.options:e instanceof qdn?$v.objectValues(e.enum):e instanceof Tdn?sNi(e._def.innerType):e instanceof Edn?[void 0]:e instanceof Sdn?[null]:e instanceof E0e?[void 0,...sNi(e.unwrap())]:e instanceof gHt?[null,...sNi(e.unwrap())]:e instanceof YVa||e instanceof zdn?sNi(e.unwrap()):e instanceof Rdn?sNi(e._def.innerType):[],_Uo=class e extends uy{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Vo.object)return Qa(r,{code:wi.invalid_type,expected:Vo.object,received:r.parsedType}),lf;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(Qa(r,{code:wi.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),lf)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let a of r){let o=sNi(a.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of o){if(n.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);n.set(c,a)}}return new e({typeName:wf.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...W_(i)})}};function thc(e,t){let r=bHt(e),i=bHt(t);if(e===t)return{valid:!0,data:e};if(r===Vo.object&&i===Vo.object){let n=$v.objectKeys(t),a=$v.objectKeys(e).filter(c=>n.indexOf(c)!==-1),o={...e,...t};for(let c of a){let d=thc(e[c],t[c]);if(!d.valid)return{valid:!1};o[c]=d.data}return{valid:!0,data:o}}else if(r===Vo.array&&i===Vo.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let a=0;a<e.length;a++){let o=e[a],c=t[a],d=thc(o,c);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return r===Vo.date&&i===Vo.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ddn=class extends uy{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(a,o)=>{if(dUo(a)||dUo(o))return lf;let c=thc(a.value,o.value);return c.valid?((pUo(a)||pUo(o))&&r.dirty(),{status:r.value,value:c.data}):(Qa(i,{code:wi.invalid_intersection_types}),lf)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,o])=>n(a,o)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};Ddn.create=(e,t,r)=>new Ddn({left:e,right:t,typeName:wf.ZodIntersection,...W_(r)});var vHt=class e extends uy{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==Vo.array)return Qa(i,{code:wi.invalid_type,expected:Vo.array,received:i.parsedType}),lf;if(i.data.length<this._def.items.length)return Qa(i,{code:wi.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),lf;!this._def.rest&&i.data.length>this._def.items.length&&(Qa(i,{code:wi.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...i.data].map((o,c)=>{let d=this._def.items[c]||this._def.rest;return d?d._parse(new S0e(i,o,i.path,c)):null}).filter(o=>!!o);return i.common.async?Promise.all(a).then(o=>S4.mergeArray(r,o)):S4.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};vHt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vHt({items:e,typeName:wf.ZodTuple,rest:null,...W_(t)})};var hUo=class e extends uy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==Vo.object)return Qa(i,{code:wi.invalid_type,expected:Vo.object,received:i.parsedType}),lf;let n=[],a=this._def.keyType,o=this._def.valueType;for(let c in i.data)n.push({key:a._parse(new S0e(i,c,i.path,c)),value:o._parse(new S0e(i,i.data[c],i.path,c)),alwaysSet:c in i.data});return i.common.async?S4.mergeObjectAsync(r,n):S4.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return r instanceof uy?new e({keyType:t,valueType:r,typeName:wf.ZodRecord,...W_(i)}):new e({keyType:lxi.create(),valueType:t,typeName:wf.ZodRecord,...W_(r)})}},sXn=class extends uy{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==Vo.map)return Qa(i,{code:wi.invalid_type,expected:Vo.map,received:i.parsedType}),lf;let n=this._def.keyType,a=this._def.valueType,o=[...i.data.entries()].map(([c,d],s)=>({key:n._parse(new S0e(i,c,i.path,[s,"key"])),value:a._parse(new S0e(i,d,i.path,[s,"value"]))}));if(i.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let d of o){let s=await d.key,u=await d.value;if(s.status==="aborted"||u.status==="aborted")return lf;(s.status==="dirty"||u.status==="dirty")&&r.dirty(),c.set(s.value,u.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let d of o){let s=d.key,u=d.value;if(s.status==="aborted"||u.status==="aborted")return lf;(s.status==="dirty"||u.status==="dirty")&&r.dirty(),c.set(s.value,u.value)}return{status:r.value,value:c}}}};sXn.create=(e,t,r)=>new sXn({valueType:t,keyType:e,typeName:wf.ZodMap,...W_(r)});var cXn=class e extends uy{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==Vo.set)return Qa(i,{code:wi.invalid_type,expected:Vo.set,received:i.parsedType}),lf;let n=this._def;n.minSize!==null&&i.data.size<n.minSize.value&&(Qa(i,{code:wi.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&i.data.size>n.maxSize.value&&(Qa(i,{code:wi.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function o(d){let s=new Set;for(let u of d){if(u.status==="aborted")return lf;u.status==="dirty"&&r.dirty(),s.add(u.value)}return{status:r.value,value:s}}let c=[...i.data.values()].map((d,s)=>a._parse(new S0e(i,d,i.path,s)));return i.common.async?Promise.all(c).then(d=>o(d)):o(c)}min(t,r){return new e({...this._def,minSize:{value:t,message:Gs.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Gs.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};cXn.create=(e,t)=>new cXn({valueType:e,minSize:null,maxSize:null,typeName:wf.ZodSet,...W_(t)});var yUo=class e extends uy{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Vo.function)return Qa(r,{code:wi.invalid_type,expected:Vo.function,received:r.parsedType}),lf;function i(c,d){return $Va({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,iXn(),uNi].filter(s=>!!s),issueData:{code:wi.invalid_arguments,argumentsError:d}})}function n(c,d){return $Va({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,iXn(),uNi].filter(s=>!!s),issueData:{code:wi.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof dxi){let c=this;return j8(async function(...d){let s=new NJ([]),u=await c._def.args.parseAsync(d,a).catch(_=>{throw s.addIssue(i(d,_)),s}),l=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(l,a).catch(_=>{throw s.addIssue(n(l,_)),s})})}else{let c=this;return j8(function(...d){let s=c._def.args.safeParse(d,a);if(!s.success)throw new NJ([i(d,s.error)]);let u=Reflect.apply(o,this,s.data),l=c._def.returns.safeParse(u,a);if(!l.success)throw new NJ([n(u,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:vHt.create(t).rest(cNi.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,i){return new e({args:t||vHt.create([]).rest(cNi.create()),returns:r||cNi.create(),typeName:wf.ZodFunction,...W_(i)})}},Bdn=class extends uy{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})}};Bdn.create=(e,t)=>new Bdn({getter:e,typeName:wf.ZodLazy,...W_(t)});var Idn=class extends uy{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Qa(r,{received:r.data,code:wi.invalid_literal,expected:this._def.value}),lf}return{status:"valid",value:t.data}}get value(){return this._def.value}};Idn.create=(e,t)=>new Idn({value:e,typeName:wf.ZodLiteral,...W_(t)});function FLp(e,t){return new Cdn({values:e,typeName:wf.ZodEnum,...W_(t)})}var Cdn=class e extends uy{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),i=this._def.values;return Qa(r,{expected:$v.joinValues(i),received:r.parsedType,code:wi.invalid_type}),lf}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return Qa(r,{received:r.data,code:wi.invalid_enum_value,options:i}),lf}return j8(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(i=>!t.includes(i)),{...this._def,...r})}};Cdn.create=FLp;var qdn=class extends uy{_parse(t){let r=$v.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==Vo.string&&i.parsedType!==Vo.number){let n=$v.objectValues(r);return Qa(i,{expected:$v.joinValues(n),received:i.parsedType,code:wi.invalid_type}),lf}if(this._cache||(this._cache=new Set($v.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let n=$v.objectValues(r);return Qa(i,{received:i.data,code:wi.invalid_enum_value,options:n}),lf}return j8(t.data)}get enum(){return this._def.values}};qdn.create=(e,t)=>new qdn({values:e,typeName:wf.ZodNativeEnum,...W_(t)});var dxi=class extends uy{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Vo.promise&&r.common.async===!1)return Qa(r,{code:wi.invalid_type,expected:Vo.promise,received:r.parsedType}),lf;let i=r.parsedType===Vo.promise?r.data:Promise.resolve(r.data);return j8(i.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};dxi.create=(e,t)=>new dxi({type:e,typeName:wf.ZodPromise,...W_(t)});var M0e=class extends uy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wf.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:o=>{Qa(i,o),o.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let o=n.transform(i.data,a);if(i.common.async)return Promise.resolve(o).then(async c=>{if(r.value==="aborted")return lf;let d=await this._def.schema._parseAsync({data:c,path:i.path,parent:i});return d.status==="aborted"?lf:d.status==="dirty"?mdn(d.value):r.value==="dirty"?mdn(d.value):d});{if(r.value==="aborted")return lf;let c=this._def.schema._parseSync({data:o,path:i.path,parent:i});return c.status==="aborted"?lf:c.status==="dirty"?mdn(c.value):r.value==="dirty"?mdn(c.value):c}}if(n.type==="refinement"){let o=c=>{let d=n.refinement(c,a);if(i.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(i.common.async===!1){let c=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return c.status==="aborted"?lf:(c.status==="dirty"&&r.dirty(),o(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(c=>c.status==="aborted"?lf:(c.status==="dirty"&&r.dirty(),o(c.value).then(()=>({status:r.value,value:c.value}))))}if(n.type==="transform")if(i.common.async===!1){let o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!cxi(o))return lf;let c=n.transform(o.value,a);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>cxi(o)?Promise.resolve(n.transform(o.value,a)).then(c=>({status:r.value,value:c})):lf);$v.assertNever(n)}};M0e.create=(e,t,r)=>new M0e({schema:e,typeName:wf.ZodEffects,effect:t,...W_(r)});M0e.createWithPreprocess=(e,t,r)=>new M0e({schema:t,effect:{type:"preprocess",transform:e},typeName:wf.ZodEffects,...W_(r)});var E0e=class extends uy{_parse(t){return this._getType(t)===Vo.undefined?j8(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};E0e.create=(e,t)=>new E0e({innerType:e,typeName:wf.ZodOptional,...W_(t)});var gHt=class extends uy{_parse(t){return this._getType(t)===Vo.null?j8(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};gHt.create=(e,t)=>new gHt({innerType:e,typeName:wf.ZodNullable,...W_(t)});var Tdn=class extends uy{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===Vo.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Tdn.create=(e,t)=>new Tdn({innerType:e,typeName:wf.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...W_(t)});var Rdn=class extends uy{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return nXn(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new NJ(i.common.issues)},input:i.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new NJ(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};Rdn.create=(e,t)=>new Rdn({innerType:e,typeName:wf.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...W_(t)});var lXn=class extends uy{_parse(t){if(this._getType(t)!==Vo.nan){let i=this._getOrReturnCtx(t);return Qa(i,{code:wi.invalid_type,expected:Vo.nan,received:i.parsedType}),lf}return{status:"valid",value:t.data}}};lXn.create=e=>new lXn({typeName:wf.ZodNaN,...W_(e)});var v_S=Symbol("zod_brand"),YVa=class extends uy{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}},XVa=class e extends uy{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?lf:a.status==="dirty"?(r.dirty(),mdn(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{let n=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?lf:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:i.path,parent:i})}}static create(t,r){return new e({in:t,out:r,typeName:wf.ZodPipeline})}},zdn=class extends uy{_parse(t){let r=this._def.innerType._parse(t),i=n=>(cxi(n)&&(n.value=Object.freeze(n.value)),n);return nXn(r)?r.then(n=>i(n)):i(r)}unwrap(){return this._def.innerType}};zdn.create=(e,t)=>new zdn({innerType:e,typeName:wf.ZodReadonly,...W_(t)});function TLp(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function QLp(e,t={},r){return e?fxi.create().superRefine((i,n)=>{let a=e(i);if(a instanceof Promise)return a.then(o=>{if(!o){let c=TLp(t,i),d=c.fatal??r??!0;n.addIssue({code:"custom",...c,fatal:d})}});if(!a){let o=TLp(t,i),c=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:c})}}):fxi.create()}var g_S={object:FJ.lazycreate},wf;(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"})(wf||(wf={}));var O_S=(e,t={message:`Input not instance of ${e.name}`})=>QLp(r=>r instanceof e,t),ULp=lxi.create,LLp=Adn.create,m_S=lXn.create,A_S=Pdn.create,VLp=jdn.create,P_S=wdn.create,j_S=oXn.create,w_S=Edn.create,E_S=Sdn.create,S_S=fxi.create,M_S=cNi.create,D_S=OVt.create,B_S=uXn.create,I_S=lNi.create,C_S=FJ.create,q_S=FJ.strictCreate,T_S=Mdn.create,R_S=_Uo.create,z_S=Ddn.create,N_S=vHt.create,F_S=hUo.create,Q_S=sXn.create,U_S=cXn.create,L_S=yUo.create,V_S=Bdn.create,W_S=Idn.create,G_S=Cdn.create,x_S=qdn.create,H_S=dxi.create,K_S=M0e.create,J_S=E0e.create,$_S=gHt.create,Y_S=M0e.createWithPreprocess,X_S=XVa.create,Z_S=()=>ULp().optional(),k_S=()=>LLp().optional(),ehS=()=>VLp().optional(),thS={string:(e=>lxi.create({...e,coerce:!0})),number:(e=>Adn.create({...e,coerce:!0})),boolean:(e=>jdn.create({...e,coerce:!0})),bigint:(e=>Pdn.create({...e,coerce:!0})),date:(e=>wdn.create({...e,coerce:!0}))};var rhS=lf;var UJ={};Yt(UJ,{RawSchemas:()=>lyc});var lyc={};Yt(lyc,{AiChatLocation:()=>ahc,AiChatModel:()=>ohc,Availability:()=>shc,BodyThemeConfig:()=>_hc,ContentAlignment:()=>Ohc,EditThisPageLaunch:()=>uhc,FernDocsConfig:()=>Shc,FernDocsConfigError:()=>ZVa,FernDocsConfigTimeoutError:()=>kVa,FontDisplay:()=>Phc,FontStyle:()=>Ahc,FooterNavThemeConfig:()=>dhc,HeaderPosition:()=>mhc,HttpSnippetLanguage:()=>bhc,JsScriptStrategy:()=>jhc,Language:()=>ihc,LanguageSwitcherThemeConfig:()=>fhc,PageActionOption:()=>nhc,PageActionsThemeConfig:()=>yhc,ProductSwitcherThemeConfig:()=>lhc,ProgrammingLanguage:()=>rhc,SearchbarPlacement:()=>vhc,Serializer:()=>QJ,SidebarThemeConfig:()=>hhc,TabsPlacement:()=>ghc,TabsThemeConfig:()=>phc,Target:()=>Ehc,TwitterCardSetting:()=>whc,VersionAvailability:()=>chc,docs:()=>bUo,serialization:()=>QJ});var Shc={};Yt(Shc,{AiChatLocation:()=>ahc,AiChatModel:()=>ohc,Availability:()=>shc,BodyThemeConfig:()=>_hc,ContentAlignment:()=>Ohc,EditThisPageLaunch:()=>uhc,FontDisplay:()=>Phc,FontStyle:()=>Ahc,FooterNavThemeConfig:()=>dhc,HeaderPosition:()=>mhc,HttpSnippetLanguage:()=>bhc,JsScriptStrategy:()=>jhc,Language:()=>ihc,LanguageSwitcherThemeConfig:()=>fhc,PageActionOption:()=>nhc,PageActionsThemeConfig:()=>yhc,ProductSwitcherThemeConfig:()=>lhc,ProgrammingLanguage:()=>rhc,SearchbarPlacement:()=>vhc,SidebarThemeConfig:()=>hhc,TabsPlacement:()=>ghc,TabsThemeConfig:()=>phc,Target:()=>Ehc,TwitterCardSetting:()=>whc,VersionAvailability:()=>chc,docs:()=>bUo});var bUo={};Yt(bUo,{AiChatLocation:()=>ahc,AiChatModel:()=>ohc,Availability:()=>shc,BodyThemeConfig:()=>_hc,ContentAlignment:()=>Ohc,EditThisPageLaunch:()=>uhc,FontDisplay:()=>Phc,FontStyle:()=>Ahc,FooterNavThemeConfig:()=>dhc,HeaderPosition:()=>mhc,HttpSnippetLanguage:()=>bhc,JsScriptStrategy:()=>jhc,Language:()=>ihc,LanguageSwitcherThemeConfig:()=>fhc,PageActionOption:()=>nhc,PageActionsThemeConfig:()=>yhc,ProductSwitcherThemeConfig:()=>lhc,ProgrammingLanguage:()=>rhc,SearchbarPlacement:()=>vhc,SidebarThemeConfig:()=>hhc,TabsPlacement:()=>ghc,TabsThemeConfig:()=>phc,Target:()=>Ehc,TwitterCardSetting:()=>whc,VersionAvailability:()=>chc});var rhc={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var ihc={En:"en",Es:"es",Fr:"fr",De:"de",It:"it",Pt:"pt",Ja:"ja",Zh:"zh",Ko:"ko",El:"el",No:"no",Pl:"pl",Ru:"ru",Sv:"sv",Tr:"tr"};var nhc={CopyPage:"copy-page",ViewAsMarkdown:"view-as-markdown",AskAi:"ask-ai",Chatgpt:"chatgpt",Claude:"claude",Cursor:"cursor",Vscode:"vscode"};var ahc={Docs:"docs",Slack:"slack",Discord:"discord"};var ohc={Claude37:"claude-3.7",Claude4:"claude-4",CommandA:"command-a"};var uhc={Github:"github",Dashboard:"dashboard"};var shc={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Deprecated:"deprecated",Beta:"beta"};var chc={Deprecated:"deprecated",Ga:"ga",Stable:"stable",Beta:"beta"};var lhc={Default:"default",Toggle:"toggle"};var fhc={Default:"default",Minimal:"minimal"};var dhc={Default:"default",Minimal:"minimal"};var phc={Default:"default",Bubble:"bubble"};var _hc={Default:"default",Canvas:"canvas"};var hhc={Default:"default",Minimal:"minimal"};var yhc={Default:"default",Toolbar:"toolbar"};var bhc={Curl:"curl",Csharp:"csharp",Go:"go",Java:"java",Javascript:"javascript",Php:"php",Python:"python",Ruby:"ruby",Swift:"swift",Typescript:"typescript"};var vhc={Header:"header",HeaderTabs:"header-tabs",Sidebar:"sidebar"};var ghc={Header:"header",Sidebar:"sidebar"};var Ohc={Center:"center",Left:"left"};var mhc={Fixed:"fixed",Static:"static"};var Ahc={Normal:"normal",Italic:"italic"};var Phc={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var jhc={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var whc={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Ehc={Blank:"_blank",Self:"_self",Parent:"_parent",Top:"_top"};var WLp=(e,t,r)=>JSON.stringify(e,t,r);var ZVa=class e extends Error{statusCode;body;rawResponse;constructor({message:t,statusCode:r,body:i,rawResponse:n}){super(ihS({message:t,statusCode:r,body:i})),Object.setPrototypeOf(this,e.prototype),this.statusCode=r,this.body=i,this.rawResponse=n}};function ihS({message:e,statusCode:t,body:r}){let i=[];return e!=null&&i.push(e),t!=null&&i.push(`Status code: ${t.toString()}`),r!=null&&i.push(`Body: ${WLp(r,void 0,2)}`),i.join(`
|
|
926
926
|
`)}var kVa=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};var QJ={};Yt(QJ,{AbsoluteProductPath:()=>gLo,AiChatConfig:()=>b3a,AiChatDatasource:()=>w4o,AiChatLocation:()=>P4o,AiChatModel:()=>A4o,AiChatWebsiteDatasource:()=>j4o,AiExamplesConfig:()=>$Uo,AnalyticsConfig:()=>JUo,AnnouncementConfig:()=>vxi,ApiReferenceConfiguration:()=>cLo,ApiReferenceEndpointConfiguration:()=>_Lo,ApiReferenceLayoutItem:()=>MHt,ApiReferencePackageConfiguration:()=>yLo,ApiReferencePackageConfigurationWithOptions:()=>bLo,ApiReferenceSectionConfiguration:()=>hLo,Audience:()=>PHt,AudienceId:()=>h3a,Availability:()=>S8,BackgroundImageConfiguration:()=>I4o,BackgroundImageThemedConfig:()=>B4o,BodyThemeConfig:()=>K4o,ChangelogConfiguration:()=>fLo,ChangelogFolderRelativePath:()=>jXn,ColorConfig:()=>EHt,ColorThemedConfig:()=>C4o,ColorsConfiguration:()=>q4o,ContentAlignment:()=>U4o,CssConfig:()=>tLo,CustomDomain:()=>YUo,CustomPageAction:()=>v4o,DocsConfiguration:()=>A8p,DocsInstance:()=>e4o,DocsSettingsConfig:()=>x4o,DocsTypographyConfig:()=>N4o,EditThisPageConfig:()=>kUo,EditThisPageLaunch:()=>ZUo,ExperimentalConfig:()=>m4o,ExternalProduct:()=>n4o,FeatureFlag:()=>y3a,FeatureFlagConfiguration:()=>t4o,FolderConfiguration:()=>dLo,FontConfig:()=>BXn,FontConfigPath:()=>R4o,FontConfigVariant:()=>T4o,FontDisplay:()=>z4o,FontStyle:()=>DXn,FontWeight:()=>MXn,FooterLinksConfig:()=>y4o,FooterNavThemeConfig:()=>Y4o,FullStoryAnalyticsConfig:()=>WUo,GithubEditThisPageConfig:()=>XUo,GoogleAnalytics4Config:()=>KUo,GtmConfig:()=>HUo,HeaderPosition:()=>L4o,HttpSnippetLanguage:()=>W4o,HttpSnippetsConfig:()=>G4o,IntegrationsConfig:()=>eLo,IntercomConfig:()=>GUo,InternalProduct:()=>i4o,JsConfig:()=>aLo,JsConfigOptions:()=>v3a,JsFileConfig:()=>nLo,JsFileConfigSettings:()=>iLo,JsRemoteConfig:()=>rLo,JsScriptStrategy:()=>IXn,Language:()=>PXn,LanguageSwitcherThemeConfig:()=>X4o,LayoutConfig:()=>V4o,LinkConfiguration:()=>CXn,LogoConfiguration:()=>D4o,MetadataConfig:()=>S4o,NavbarDropdownConfig:()=>_4o,NavbarGithubConfig:()=>p4o,NavbarGithubConfigWithOptions:()=>d4o,NavbarLink:()=>h4o,NavbarLinkConfig:()=>wHt,NavigationConfig:()=>Oxi,NavigationItem:()=>jHt,PageActionOption:()=>b4o,PageActionOptions:()=>g4o,PageActionsConfig:()=>O4o,PageActionsThemeConfig:()=>$4o,PageConfiguration:()=>I0e,PlaygroundButtonSettings:()=>sLo,PlaygroundSettings:()=>SHt,PostHogConfig:()=>xUo,ProductConfig:()=>a4o,ProductConfigBase:()=>SXn,ProductFileConfig:()=>w8p,ProductPath:()=>j8p,ProductSwitcherThemeConfig:()=>Z4o,ProgrammingLanguage:()=>LUo,PythonDocsConfiguration:()=>lLo,RedirectConfig:()=>M4o,RelativeProductPath:()=>vLo,Role:()=>wXn,RoleId:()=>Ldn,SearchbarPlacement:()=>F4o,SectionConfiguration:()=>pLo,SegmentConfig:()=>VUo,SidebarThemeConfig:()=>H4o,SnippetLanguageConfiguration:()=>C0e,SnippetsConfiguration:()=>uLo,TabConfig:()=>gxi,TabId:()=>D0e,TabVariant:()=>s4o,TabbedNavigationConfig:()=>f4o,TabbedNavigationItem:()=>l4o,TabbedNavigationItemWithLayout:()=>u4o,TabbedNavigationItemWithVariants:()=>c4o,TabsPlacement:()=>Q4o,TabsThemeConfig:()=>J4o,Target:()=>B0e,ThemeConfig:()=>k4o,TwitterCardSetting:()=>E4o,UntabbedNavigationConfig:()=>o4o,VersionAvailability:()=>r4o,VersionConfig:()=>EXn,VersionFileConfig:()=>P8p,VersionedSnippetLanguageConfiguration:()=>oLo,WithFeatureFlags:()=>S0,WithPermissions:()=>E0,WithViewers:()=>mxi,docs:()=>cyc});var cyc={};Yt(cyc,{AbsoluteProductPath:()=>gLo,AiChatConfig:()=>b3a,AiChatDatasource:()=>w4o,AiChatLocation:()=>P4o,AiChatModel:()=>A4o,AiChatWebsiteDatasource:()=>j4o,AiExamplesConfig:()=>$Uo,AnalyticsConfig:()=>JUo,AnnouncementConfig:()=>vxi,ApiReferenceConfiguration:()=>cLo,ApiReferenceEndpointConfiguration:()=>_Lo,ApiReferenceLayoutItem:()=>MHt,ApiReferencePackageConfiguration:()=>yLo,ApiReferencePackageConfigurationWithOptions:()=>bLo,ApiReferenceSectionConfiguration:()=>hLo,Audience:()=>PHt,AudienceId:()=>h3a,Availability:()=>S8,BackgroundImageConfiguration:()=>I4o,BackgroundImageThemedConfig:()=>B4o,BodyThemeConfig:()=>K4o,ChangelogConfiguration:()=>fLo,ChangelogFolderRelativePath:()=>jXn,ColorConfig:()=>EHt,ColorThemedConfig:()=>C4o,ColorsConfiguration:()=>q4o,ContentAlignment:()=>U4o,CssConfig:()=>tLo,CustomDomain:()=>YUo,CustomPageAction:()=>v4o,DocsConfiguration:()=>A8p,DocsInstance:()=>e4o,DocsSettingsConfig:()=>x4o,DocsTypographyConfig:()=>N4o,EditThisPageConfig:()=>kUo,EditThisPageLaunch:()=>ZUo,ExperimentalConfig:()=>m4o,ExternalProduct:()=>n4o,FeatureFlag:()=>y3a,FeatureFlagConfiguration:()=>t4o,FolderConfiguration:()=>dLo,FontConfig:()=>BXn,FontConfigPath:()=>R4o,FontConfigVariant:()=>T4o,FontDisplay:()=>z4o,FontStyle:()=>DXn,FontWeight:()=>MXn,FooterLinksConfig:()=>y4o,FooterNavThemeConfig:()=>Y4o,FullStoryAnalyticsConfig:()=>WUo,GithubEditThisPageConfig:()=>XUo,GoogleAnalytics4Config:()=>KUo,GtmConfig:()=>HUo,HeaderPosition:()=>L4o,HttpSnippetLanguage:()=>W4o,HttpSnippetsConfig:()=>G4o,IntegrationsConfig:()=>eLo,IntercomConfig:()=>GUo,InternalProduct:()=>i4o,JsConfig:()=>aLo,JsConfigOptions:()=>v3a,JsFileConfig:()=>nLo,JsFileConfigSettings:()=>iLo,JsRemoteConfig:()=>rLo,JsScriptStrategy:()=>IXn,Language:()=>PXn,LanguageSwitcherThemeConfig:()=>X4o,LayoutConfig:()=>V4o,LinkConfiguration:()=>CXn,LogoConfiguration:()=>D4o,MetadataConfig:()=>S4o,NavbarDropdownConfig:()=>_4o,NavbarGithubConfig:()=>p4o,NavbarGithubConfigWithOptions:()=>d4o,NavbarLink:()=>h4o,NavbarLinkConfig:()=>wHt,NavigationConfig:()=>Oxi,NavigationItem:()=>jHt,PageActionOption:()=>b4o,PageActionOptions:()=>g4o,PageActionsConfig:()=>O4o,PageActionsThemeConfig:()=>$4o,PageConfiguration:()=>I0e,PlaygroundButtonSettings:()=>sLo,PlaygroundSettings:()=>SHt,PostHogConfig:()=>xUo,ProductConfig:()=>a4o,ProductConfigBase:()=>SXn,ProductFileConfig:()=>w8p,ProductPath:()=>j8p,ProductSwitcherThemeConfig:()=>Z4o,ProgrammingLanguage:()=>LUo,PythonDocsConfiguration:()=>lLo,RedirectConfig:()=>M4o,RelativeProductPath:()=>vLo,Role:()=>wXn,RoleId:()=>Ldn,SearchbarPlacement:()=>F4o,SectionConfiguration:()=>pLo,SegmentConfig:()=>VUo,SidebarThemeConfig:()=>H4o,SnippetLanguageConfiguration:()=>C0e,SnippetsConfiguration:()=>uLo,TabConfig:()=>gxi,TabId:()=>D0e,TabVariant:()=>s4o,TabbedNavigationConfig:()=>f4o,TabbedNavigationItem:()=>l4o,TabbedNavigationItemWithLayout:()=>u4o,TabbedNavigationItemWithVariants:()=>c4o,TabsPlacement:()=>Q4o,TabsThemeConfig:()=>J4o,Target:()=>B0e,ThemeConfig:()=>k4o,TwitterCardSetting:()=>E4o,UntabbedNavigationConfig:()=>o4o,VersionAvailability:()=>r4o,VersionConfig:()=>EXn,VersionFileConfig:()=>P8p,VersionedSnippetLanguageConfiguration:()=>oLo,WithFeatureFlags:()=>S0,WithPermissions:()=>E0,WithViewers:()=>mxi});var ee={};Yt(ee,{JsonError:()=>OXn,ParseError:()=>mXn,any:()=>c8p,bigint:()=>Y3p,boolean:()=>l8p,booleanLiteral:()=>s8p,date:()=>X3p,discriminant:()=>g8p,enum_:()=>FUo,getObjectLikeUtils:()=>AVt,getObjectUtils:()=>Udn,getSchemaUtils:()=>sA,isProperty:()=>bxi,lazy:()=>Z3p,lazyObject:()=>a8p,list:()=>UUo,number:()=>f8p,object:()=>QUo,objectWithoutOptionalProperties:()=>n8p,optional:()=>ayc,property:()=>e8p,record:()=>h8p,set:()=>y8p,string:()=>d8p,stringLiteral:()=>u8p,transform:()=>oyc,undiscriminatedUnion:()=>v8p,union:()=>m8p,unknown:()=>p8p,withParsedProperties:()=>syc});var _p={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",NULLABLE:"nullable",OPTIONAL:"optional",OPTIONAL_NULLABLE:"optionalNullable"};function uA(e,t){return`Expected ${t}. Received ${IbS(e)}.`}function IbS(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function EN(e){return{...e,json:$3p(e.json),parse:$3p(e.parse)}}function $3p(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
927
927
|
`)),{ok:!0,value:t}):i}}function NUo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var OXn=class e extends Error{errors;constructor(t){super(t.map(NUo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var mXn=class e extends Error{errors;constructor(t){super(t.map(NUo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function sA(e){return{nullable:()=>CbS(e),optional:()=>ayc(e),optionalNullable:()=>qbS(e),transform:t=>oyc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new mXn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new OXn(i.errors)}}}function CbS(e){let t={parse:(r,i)=>r==null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>_p.NULLABLE};return{...t,...sA(t)}}function ayc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>_p.OPTIONAL};return{...t,...sA(t)}}function qbS(e){let t={parse:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,i),getType:()=>_p.OPTIONAL_NULLABLE};return{...t,...sA(t)}}function oyc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...sA(r)}}function Y3p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:uA(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:uA(t,"bigint")}]}:{ok:!0,value:t},getType:()=>_p.BIGINT};return{...EN(e),...sA(e)}}var TbS=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function X3p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:uA(t,"string")}]}:TbS.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:uA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:uA(t,"Date object")}]},getType:()=>_p.DATE};return{...EN(e),...sA(e)}}function E8(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...EN(r),...sA(r)}}}function FUo(e){let t=new Set(e);return E8(_p.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:uA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:uA(i,"enum")}]}:{ok:!0,value:i})()}function Z3p(e){let t=uyc(e);return{...t,...sA(t)}}function uyc(e){return{parse:(t,r)=>AXn(e).parse(t,r),json:(t,r)=>AXn(e).json(t,r),getType:()=>AXn(e).getType()}}function AXn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function d3a(e){return Object.entries(e)}function p3a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function yxi(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function _3a(e){return Object.keys(e)}function k3p(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function AVt(e){return{withParsedProperties:t=>syc(e,t)}}function syc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...o}}},json:(i,n)=>{if(!yxi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uA(i,"object")}]};let a=new Set(Object.keys(t)),o=p3a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...sA(r),...AVt(r)}}function e8p(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function bxi(e){return e.isProperty}function QUo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>bxi(i)?i.rawKey:r),_getParsedProperties:()=>_3a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of d3a(e)){let d=bxi(c)?c.rawKey:o,s=bxi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,i8p(s)&&a.push(d)}return t8p({value:r,requiredKeys:a,getProperty:o=>{let c=n[o];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,o]of d3a(e)){let c=bxi(o)?o.valueSchema:o;i8p(c)&&n.push(a)}return t8p({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return bxi(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>_p.OBJECT};return{...EN(t),...sA(t),...AVt(t),...Udn(t)}}function t8p({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!yxi(e))return{ok:!1,errors:[{path:a,message:uA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.transformedKey]=p.value:(d[s]=u,c.push(...p.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=u;break}}return c.push(...t.filter(s=>o.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function Udn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>r8p({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>r8p({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>_p.OBJECT};return{...r,...sA(r),...AVt(r),...Udn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>_p.OBJECT};return{...t,...sA(t),...AVt(t),...Udn(t)}}}}function r8p({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=k3p(_3a(t),s=>n.has(s)),c=r(p3a(t,o)),d=i(p3a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function i8p(e){return!RbS(e)}function RbS(e){switch(e.getType()){case _p.ANY:case _p.UNKNOWN:case _p.OPTIONAL:case _p.OPTIONAL_NULLABLE:return!0;default:return!1}}function n8p(e){return QUo(e)}function a8p(e){let t={...uyc(e),_getRawProperties:()=>AXn(e)._getRawProperties(),_getParsedProperties:()=>AXn(e)._getParsedProperties()};return{...t,...sA(t),...AVt(t),...Udn(t)}}function UUo(e){let t={parse:(r,i)=>o8p(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>o8p(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>_p.LIST};return{...EN(t),...sA(t)}}function o8p(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:uA(e,"list"),path:[]}]}}function u8p(e){return E8(_p.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uA(r,`"${e}"`)}]})()}function s8p(e){return E8(_p.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:uA(r,`${e.toString()}`)}]})()}var c8p=E8(_p.ANY,e=>({ok:!0,value:e}));var l8p=E8(_p.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uA(e,"boolean")}]});var f8p=E8(_p.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uA(e,"number")}]});var d8p=E8(_p.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:uA(e,"string")}]});var p8p=E8(_p.UNKNOWN,e=>({ok:!0,value:e}));function h8p(e,t){let r={parse:(i,n)=>_8p({value:i,isKeyNumeric:e.getType()===_p.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>_8p({value:i,isKeyNumeric:e.getType()===_p.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>_p.RECORD};return{...EN(r),...sA(r)}}function _8p({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return yxi(e)?d3a(e).reduce((a,[o,c])=>{if(c===void 0)return a;let d=a,s=o;if(t){let _=o.length>0?Number(o):NaN;isNaN(_)||(s=_)}let u=r(s),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:uA(e,"object")}]}}function y8p(e){let t=UUo(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:uA(i,"Set")}]},getType:()=>_p.SET};return{...EN(r),...sA(r)}}function v8p(e){let t={parse:(r,i)=>b8p((n,a)=>n.parse(r,a),e,i),json:(r,i)=>b8p((n,a)=>n.json(r,a),e,i),getType:()=>_p.UNDISCRIMINATED_UNION};return{...EN(t),...sA(t)}}function b8p(e,t,r){let i=[];for(let[n,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function g8p(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function m8p(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=FUo(_3a(t)),a={parse:(o,c)=>O8p({value:o,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>O8p({value:o,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>_p.UNION};return{...EN(a),...sA(a),...AVt(a)}}function O8p({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!yxi(e))return{ok:!1,errors:[{path:c,message:uA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let u=i(d);if(!u.ok)return{ok:!1,errors:u.errors};let l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var LUo=ee.enum_(["typescript","javascript","python","java","go","ruby","csharp","php","swift","rust","nodets","nodejs","dotnet","curl","jvm","ts","js"]);var PXn=ee.enum_(["en","es","fr","de","it","pt","ja","zh","ko","el","no","pl","ru","sv","tr"]);var VUo=ee.object({writeKey:ee.property("write-key",ee.string())});var WUo=ee.object({orgId:ee.property("org-id",ee.string())});var GUo=ee.object({appId:ee.property("app-id",ee.string()),apiBase:ee.property("api-base",ee.string().optional())});var xUo=ee.object({apiKey:ee.property("api-key",ee.string()),endpoint:ee.string().optional()});var HUo=ee.object({containerId:ee.property("container-id",ee.string())});var KUo=ee.object({measurementId:ee.property("measurement-id",ee.string())});var JUo=ee.object({segment:VUo.optional(),fullstory:WUo.optional(),intercom:GUo.optional(),posthog:xUo.optional(),gtm:HUo.optional(),ga4:KUo.optional()});var $Uo=ee.object({enabled:ee.boolean().optional(),style:ee.string().optional()});var YUo=ee.undiscriminatedUnion([ee.string(),ee.list(ee.string())]);var XUo=ee.object({host:ee.string().optional(),owner:ee.string(),repo:ee.string(),branch:ee.string().optional()});var ZUo=ee.enum_(["github","dashboard"]);var kUo=ee.object({github:XUo.optional(),launch:ZUo.optional()});var h3a=ee.string();var PHt=ee.undiscriminatedUnion([h3a,ee.list(h3a)]);var e4o=ee.object({url:ee.string(),customDomain:ee.property("custom-domain",YUo.optional()),private:ee.boolean().optional(),editThisPage:ee.property("edit-this-page",kUo.optional()),audiences:PHt.optional()});var vxi=ee.object({message:ee.string()});var Ldn=ee.string();var D0e=ee.string();var B0e=ee.enum_(["_blank","_self","_parent","_top"]);var jXn=ee.string();var wXn=ee.undiscriminatedUnion([Ldn,ee.list(Ldn)]);var E0=ee.object({viewers:wXn.optional(),orphaned:ee.boolean().optional()});var y3a=ee.object({flag:ee.string(),fallbackValue:ee.property("fallback-value",ee.unknown().optional()),match:ee.unknown().optional()});var t4o=ee.undiscriminatedUnion([ee.string(),y3a,ee.list(y3a)]);var S0=ee.object({featureFlag:ee.property("feature-flag",t4o.optional())});var gxi=ee.object({displayName:ee.property("display-name",ee.string()),icon:ee.string().optional(),slug:ee.string().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),hidden:ee.boolean().optional(),href:ee.string().optional(),target:B0e.optional(),changelog:jXn.optional()}).extend(E0).extend(S0);var r4o=ee.enum_(["deprecated","ga","stable","beta"]);var EXn=ee.object({displayName:ee.property("display-name",ee.string()),path:ee.string(),slug:ee.string().optional(),availability:r4o.optional(),audiences:PHt.optional(),hidden:ee.boolean().optional(),announcement:vxi.optional()}).extend(E0).extend(S0);var SXn=ee.object({displayName:ee.property("display-name",ee.string()),subtitle:ee.string().optional(),icon:ee.string().optional(),image:ee.string().optional(),versions:ee.list(EXn).optional(),audiences:PHt.optional()}).extend(E0).extend(S0);var i4o=ee.object({path:ee.string(),slug:ee.string().optional(),announcement:vxi.optional()}).extend(SXn);var n4o=ee.object({href:ee.string(),target:B0e.optional()}).extend(SXn);var a4o=ee.undiscriminatedUnion([i4o,n4o]);var S8=ee.enum_(["stable","generally-available","in-development","pre-release","deprecated","beta"]);var I0e=ee.object({page:ee.string(),path:ee.string(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),noindex:ee.boolean().optional(),availability:S8.optional()}).extend(E0).extend(S0);var o4o=ee.list(ee.lazy(()=>jHt));var u4o=ee.object({tab:D0e,layout:ee.list(ee.lazy(()=>jHt)).optional()});var s4o=ee.object({title:ee.string(),subtitle:ee.string().optional(),icon:ee.string().optional(),layout:ee.list(ee.lazy(()=>jHt)),slug:ee.string().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),hidden:ee.boolean().optional(),default:ee.boolean().optional()}).extend(E0).extend(S0);var c4o=ee.object({tab:D0e,variants:ee.list(s4o)});var l4o=ee.undiscriminatedUnion([u4o,c4o]);var f4o=ee.list(l4o);var Oxi=ee.undiscriminatedUnion([o4o,f4o]);var mxi=ee.object({viewers:wXn.optional()});var wHt=ee.object({href:ee.string().optional(),target:B0e.optional(),url:ee.string().optional(),text:ee.string().optional(),icon:ee.string().optional(),rightIcon:ee.string().optional(),rounded:ee.boolean().optional()}).extend(mxi);var d4o=ee.object({url:ee.string(),target:B0e.optional()}).extend(mxi);var p4o=ee.undiscriminatedUnion([ee.string(),d4o]);var _4o=ee.object({links:ee.list(wHt),text:ee.string().optional(),icon:ee.string().optional(),rightIcon:ee.string().optional(),rounded:ee.boolean().optional()}).extend(mxi);var h4o=ee.union("type",{filled:wHt,outlined:wHt,minimal:wHt,github:ee.object({value:p4o}),dropdown:_4o,primary:wHt,secondary:wHt}).transform({transform:e=>e,untransform:e=>e});var y4o=ee.object({github:ee.string().optional(),twitter:ee.string().optional(),x:ee.string().optional(),linkedin:ee.string().optional(),youtube:ee.string().optional(),instagram:ee.string().optional(),facebook:ee.string().optional(),discord:ee.string().optional(),slack:ee.string().optional(),hackernews:ee.string().optional(),medium:ee.string().optional(),website:ee.string().optional()});var b4o=ee.enum_(["copy-page","view-as-markdown","ask-ai","chatgpt","claude","cursor","vscode"]);var v4o=ee.object({title:ee.string(),subtitle:ee.string().optional(),url:ee.string(),icon:ee.string().optional(),default:ee.boolean().optional()});var g4o=ee.object({copyPage:ee.property("copy-page",ee.boolean().optional()),viewAsMarkdown:ee.property("view-as-markdown",ee.boolean().optional()),askAi:ee.property("ask-ai",ee.boolean().optional()),chatgpt:ee.boolean().optional(),claude:ee.boolean().optional(),cursor:ee.boolean().optional(),vscode:ee.boolean().optional(),custom:ee.list(v4o).optional()});var O4o=ee.object({default:b4o.optional(),options:g4o.optional()});var m4o=ee.object({mdxComponents:ee.property("mdx-components",ee.list(ee.string()).optional()),disableStreamToggle:ee.property("disable-stream-toggle",ee.boolean().optional()),openapiParserV2:ee.property("openapi-parser-v2",ee.boolean().optional()),openapiParserV3:ee.property("openapi-parser-v3",ee.boolean().optional()),dynamicSnippets:ee.property("dynamic-snippets",ee.boolean().optional()),aiExamples:ee.property("ai-examples",ee.boolean().optional()),aiExampleStyleInstructions:ee.property("ai-example-style-instructions",ee.string().optional()),excludeApis:ee.property("exclude-apis",ee.boolean().optional())});var A4o=ee.enum_(["claude-3.7","claude-4","command-a"]);var P4o=ee.enum_(["docs","slack","discord"]);var j4o=ee.object({url:ee.string(),title:ee.string().optional()});var w4o=ee.undiscriminatedUnion([j4o]);var b3a=ee.object({model:A4o.optional(),systemPrompt:ee.property("system-prompt",ee.string().optional()),location:ee.list(P4o).optional(),datasources:ee.list(w4o).optional()});var E4o=ee.enum_(["summary","summary_large_image","app","player"]);var S4o=ee.object({ogSiteName:ee.property("og:site_name",ee.string().optional()),ogTitle:ee.property("og:title",ee.string().optional()),ogDescription:ee.property("og:description",ee.string().optional()),ogUrl:ee.property("og:url",ee.string().optional()),ogImage:ee.property("og:image",ee.string().optional()),ogImageWidth:ee.property("og:image:width",ee.number().optional()),ogImageHeight:ee.property("og:image:height",ee.number().optional()),ogLocale:ee.property("og:locale",ee.string().optional()),ogLogo:ee.property("og:logo",ee.string().optional()),twitterTitle:ee.property("twitter:title",ee.string().optional()),twitterDescription:ee.property("twitter:description",ee.string().optional()),twitterHandle:ee.property("twitter:handle",ee.string().optional()),twitterImage:ee.property("twitter:image",ee.string().optional()),twitterSite:ee.property("twitter:site",ee.string().optional()),twitterUrl:ee.property("twitter:url",ee.string().optional()),twitterCard:ee.property("twitter:card",E4o.optional()),canonicalHost:ee.property("canonical-host",ee.string().optional())});var M4o=ee.object({source:ee.string(),destination:ee.string(),permanent:ee.boolean().optional()});var D4o=ee.object({dark:ee.string().optional(),light:ee.string().optional(),height:ee.number().optional(),href:ee.string().optional(),rightText:ee.property("right-text",ee.string().optional())});var B4o=ee.object({dark:ee.string().optional(),light:ee.string().optional()});var I4o=ee.undiscriminatedUnion([ee.string(),B4o]);var C4o=ee.object({dark:ee.string().optional(),light:ee.string().optional()});var EHt=ee.undiscriminatedUnion([ee.string(),C4o]);var q4o=ee.object({accentPrimary:ee.property("accent-primary",EHt.optional()),accentPrimaryDeprecated:ee.property("accentPrimary",EHt.optional()),background:EHt.optional(),border:EHt.optional(),sidebarBackground:ee.property("sidebar-background",EHt.optional()),headerBackground:ee.property("header-background",EHt.optional()),cardBackground:ee.property("card-background",EHt.optional())});var MXn=ee.undiscriminatedUnion([ee.string(),ee.number()]);var DXn=ee.enum_(["normal","italic"]);var T4o=ee.object({path:ee.string(),weight:MXn.optional(),style:DXn.optional()});var R4o=ee.undiscriminatedUnion([ee.string(),T4o]);var z4o=ee.enum_(["auto","block","swap","fallback","optional"]);var BXn=ee.object({name:ee.string().optional(),path:ee.string().optional(),weight:MXn.optional(),style:DXn.optional(),paths:ee.list(R4o).optional(),display:z4o.optional(),fallback:ee.list(ee.string()).optional(),fontVariationSettings:ee.property("font-variation-settings",ee.string().optional())});var N4o=ee.object({headingsFont:BXn.optional(),bodyFont:BXn.optional(),codeFont:BXn.optional()});var F4o=ee.enum_(["header","header-tabs","sidebar"]);var Q4o=ee.enum_(["header","sidebar"]);var U4o=ee.enum_(["center","left"]);var L4o=ee.enum_(["fixed","static"]);var V4o=ee.object({pageWidth:ee.property("page-width",ee.string().optional()),contentWidth:ee.property("content-width",ee.string().optional()),sidebarWidth:ee.property("sidebar-width",ee.string().optional()),headerHeight:ee.property("header-height",ee.string().optional()),searchbarPlacement:ee.property("searchbar-placement",F4o.optional()),tabsPlacement:ee.property("tabs-placement",Q4o.optional()),contentAlignment:ee.property("content-alignment",U4o.optional()),headerPosition:ee.property("header-position",L4o.optional()),disableHeader:ee.property("disable-header",ee.boolean().optional()),hideNavLinks:ee.property("hide-nav-links",ee.boolean().optional()),hideFeedback:ee.property("hide-feedback",ee.boolean().optional())});var W4o=ee.enum_(["curl","csharp","go","java","javascript","php","python","ruby","swift","typescript"]);var G4o=ee.undiscriminatedUnion([ee.boolean(),ee.list(W4o)]);var x4o=ee.object({searchText:ee.property("search-text",ee.string().optional()),disableSearch:ee.property("disable-search",ee.boolean().optional()),darkModeCode:ee.property("dark-mode-code",ee.boolean().optional()),defaultSearchFilters:ee.property("default-search-filters",ee.boolean().optional()),httpSnippets:ee.property("http-snippets",G4o.optional()),hide404Page:ee.property("hide-404-page",ee.boolean().optional()),useJavascriptAsTypescript:ee.property("use-javascript-as-typescript",ee.boolean().optional()),disableExplorerProxy:ee.property("disable-explorer-proxy",ee.boolean().optional()),disableAnalytics:ee.property("disable-analytics",ee.boolean().optional()),language:PXn.optional(),substituteEnvVars:ee.property("substitute-env-vars",ee.boolean().optional())});var H4o=ee.enum_(["default","minimal"]);var K4o=ee.enum_(["default","canvas"]);var J4o=ee.enum_(["default","bubble"]);var $4o=ee.enum_(["default","toolbar"]);var Y4o=ee.enum_(["default","minimal"]);var X4o=ee.enum_(["default","minimal"]);var Z4o=ee.enum_(["default","toggle"]);var k4o=ee.object({sidebar:H4o.optional(),body:K4o.optional(),tabs:J4o.optional(),pageActions:ee.property("page-actions",$4o.optional()),footerNav:ee.property("footer-nav",Y4o.optional()),languageSwitcher:ee.property("language-switcher",X4o.optional()),productSwitcher:ee.property("product-switcher",Z4o.optional())});var eLo=ee.object({intercom:ee.string().optional()});var tLo=ee.undiscriminatedUnion([ee.string(),ee.list(ee.string())]);var IXn=ee.enum_(["beforeInteractive","afterInteractive","lazyOnload"]);var rLo=ee.object({url:ee.string(),strategy:IXn.optional()});var iLo=ee.object({path:ee.string(),strategy:IXn.optional()});var nLo=ee.undiscriminatedUnion([ee.string(),iLo]);var v3a=ee.undiscriminatedUnion([rLo,nLo]);var aLo=ee.undiscriminatedUnion([v3a,ee.list(v3a)]);var A8p=ee.object({instances:ee.list(e4o),title:ee.string().optional(),analytics:JUo.optional(),announcement:vxi.optional(),roles:ee.list(Ldn).optional(),tabs:ee.record(D0e,gxi).optional(),versions:ee.list(EXn).optional(),products:ee.list(a4o).optional(),landingPage:ee.property("landing-page",I0e.optional()),navigation:Oxi.optional(),navbarLinks:ee.property("navbar-links",ee.list(h4o).optional()),footerLinks:ee.property("footer-links",y4o.optional()),pageActions:ee.property("page-actions",O4o.optional()),experimental:m4o.optional(),defaultLanguage:ee.property("default-language",LUo.optional()),languages:ee.list(PXn).optional(),aiChat:ee.property("ai-chat",b3a.optional()),aiSearch:ee.property("ai-search",b3a.optional()),aiExamples:ee.property("ai-examples",$Uo.optional()),metadata:S4o.optional(),redirects:ee.list(M4o).optional(),logo:D4o.optional(),favicon:ee.string().optional(),backgroundImage:ee.property("background-image",I4o.optional()),colors:q4o.optional(),typography:N4o.optional(),layout:V4o.optional(),settings:x4o.optional(),theme:k4o.optional(),integrations:eLo.optional(),css:tLo.optional(),js:aLo.optional()});var P8p=ee.object({tabs:ee.record(D0e,gxi).optional(),landingPage:ee.property("landing-page",I0e.optional()),navigation:Oxi});var oLo=ee.object({version:ee.string(),package:ee.string()});var C0e=ee.undiscriminatedUnion([ee.string(),oLo]);var uLo=ee.object({python:C0e.optional(),typescript:C0e.optional(),go:C0e.optional(),java:C0e.optional(),ruby:C0e.optional(),csharp:C0e.optional(),php:C0e.optional(),swift:C0e.optional(),rust:C0e.optional()});var sLo=ee.object({href:ee.string().optional()});var SHt=ee.object({hidden:ee.boolean().optional(),environments:ee.list(ee.string()).optional(),button:sLo.optional(),oauth:ee.boolean().optional(),limitWebsocketMessagesPerConnection:ee.property("limit-websocket-messages-per-connection",ee.number().optional())});var cLo=ee.object({api:ee.string(),apiName:ee.property("api-name",ee.string().optional()),openrpc:ee.string().optional(),audiences:PHt.optional(),displayErrors:ee.property("display-errors",ee.boolean().optional()),tagDescriptionPages:ee.property("tag-description-pages",ee.boolean().optional()),snippets:uLo.optional(),postman:ee.string().optional(),summary:ee.string().optional(),layout:ee.list(ee.lazy(()=>MHt)).optional(),collapsed:ee.boolean().optional(),icon:ee.string().optional(),slug:ee.string().optional(),hidden:ee.boolean().optional(),availability:S8.optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),alphabetized:ee.boolean().optional(),flattened:ee.boolean().optional(),paginated:ee.boolean().optional(),playground:SHt.optional()}).extend(E0).extend(S0);var lLo=ee.object({pythonDocs:ee.property("python-docs",ee.string()),title:ee.string().optional(),slug:ee.string().optional()});var CXn=ee.object({link:ee.string(),href:ee.string(),icon:ee.string().optional(),target:B0e.optional()});var fLo=ee.object({changelog:jXn,title:ee.string().optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional()}).extend(E0).extend(S0);var dLo=ee.object({folder:ee.string(),title:ee.string().optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),collapsed:ee.boolean().optional(),availability:S8.optional()}).extend(E0).extend(S0);var jHt=ee.undiscriminatedUnion([I0e,ee.lazyObject(()=>pLo),cLo,lLo,CXn,fLo,dLo]);var pLo=ee.object({section:ee.string(),path:ee.string().optional(),contents:ee.list(ee.lazy(()=>jHt)),collapsed:ee.boolean().optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),availability:S8.optional()}).extend(E0).extend(S0);var _Lo=ee.object({endpoint:ee.string(),title:ee.string().optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),availability:S8.optional(),playground:SHt.optional()}).extend(E0).extend(S0);var MHt=ee.undiscriminatedUnion([ee.string(),ee.record(ee.string(),ee.lazy(()=>yLo)),ee.lazyObject(()=>hLo),_Lo,I0e,CXn]);var hLo=ee.object({section:ee.string(),referencedPackages:ee.property("referenced-packages",ee.list(ee.string()).optional()),summary:ee.string().optional(),contents:ee.list(ee.lazy(()=>MHt)).optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),availability:S8.optional(),playground:SHt.optional()}).extend(E0).extend(S0);var yLo=ee.undiscriminatedUnion([ee.list(ee.lazy(()=>MHt)),ee.lazyObject(()=>bLo)]);var bLo=ee.object({title:ee.string().optional(),summary:ee.string().optional(),contents:ee.list(ee.lazy(()=>MHt)).optional(),availability:S8.optional(),slug:ee.string().optional(),icon:ee.string().optional(),hidden:ee.boolean().optional(),skipSlug:ee.property("skip-slug",ee.boolean().optional()),playground:SHt.optional()}).extend(E0).extend(S0);var vLo=ee.object({displayName:ee.property("display-name",ee.string()),path:ee.string(),slug:ee.string().optional()}).extend(E0).extend(S0);var gLo=ee.object({href:ee.string()});var j8p=ee.undiscriminatedUnion([vLo,gLo]);var w8p=ee.object({tabs:ee.record(D0e,gxi).optional(),landingPage:ee.property("landing-page",I0e.optional()),navigation:Oxi});var E8p=require("fs/promises");var zbS=/\r?\n/;async function Vdn({absolutePathToFernignore:e}){let t=(await(0,E8p.readFile)(e)).toString();return S8p(t)}function S8p(e){return[yHt,...e.trim().split(zbS).map(t=>{let r=t.indexOf("#");return r!==-1?t.slice(0,r).trim():t.trim()}).filter(t=>t.length>0)]}var an={};Yt(an,{API_ORIGIN_LOCATION_KEY:()=>SLp,API_SETTINGS_KEY:()=>ILp,ASYNC_API_LOCATION_KEY:()=>MLp,DEFAULT_GROUP_GENERATORS_CONFIG_KEY:()=>rXn,DEFAULT_GROUP_NAME:()=>JVa,DefaultIntegerFormat:()=>F8p,ExampleStyle:()=>C8p,FormParameterEncoding:()=>N8p,GenerationLanguage:()=>M8p,GithubCommitAndReleaseMode:()=>L8p,GithubLicenseType:()=>V8p,GithubSelfhostedMode:()=>U8p,Language:()=>Q8p,MessageNamingSettingsSchema:()=>z8p,ModelProvider:()=>I8p,OPENAPI_LOCATION_KEY:()=>DLp,OPENAPI_OVERRIDES_LOCATION_KEY:()=>BLp,PathParameterOrder:()=>T8p,RemoveDiscriminantsFromSchemas:()=>q8p,UnionSettingsSchema:()=>R8p,ai:()=>fyc,fernDefinition:()=>yyc,generators:()=>dyc,getPackageName:()=>D8p,group:()=>pyc,isApiConfigurationV2Schema:()=>SWp,isAsyncApiSpecSchema:()=>MWp,isConjureSchema:()=>DWp,isNamespacedApiConfiguration:()=>BWp,isOpenApiSpecSchema:()=>IWp,isOpenRpcSpecSchema:()=>CWp,isProtoSpecSchema:()=>qWp,isRawProtobufAPIDefinitionSchema:()=>B8p,license:()=>_yc,reviewers:()=>W8p,serialization:()=>zyc});var M8p={TYPESCRIPT:"typescript",JAVA:"java",PYTHON:"python",GO:"go",RUBY:"ruby",CSHARP:"csharp",SWIFT:"swift",PHP:"php",RUST:"rust"};function D8p({generatorInvocation:e}){return e.language==="go"?NbS(e):e.outputMode._visit({downloadFiles:()=>{},github:t=>t.publishInfo?._visit({maven:r=>r.coordinate,npm:r=>r.packageName,pypi:r=>r.packageName,postman:()=>{},rubygems:r=>r.packageName,nuget:r=>r.packageName,crates:r=>r.packageName,_other:()=>{}}),githubV2:t=>t.publishInfo?._visit({maven:r=>r.coordinate,npm:r=>r.packageName,pypi:r=>r.packageName,postman:()=>{},rubygems:r=>r.packageName,nuget:r=>r.packageName,crates:r=>r.packageName,_other:()=>{}}),publish:()=>{},publishV2:()=>{},_other:()=>{}})}function NbS(e){return e.outputMode._visit({downloadFiles:()=>{},github:t=>`github.com/${t.owner}/${t.repo}`,githubV2:t=>`github.com/${t.owner}/${t.repo}`,publish:()=>{},publishV2:()=>{},_other:()=>{}})}function B8p(e){return typeof e!="string"&&"proto"in e}var fyc={};Yt(fyc,{ModelProvider:()=>I8p});var I8p={Openai:"openai",Anthropic:"anthropic",Bedrock:"bedrock"};var dyc={};Yt(dyc,{DefaultIntegerFormat:()=>F8p,ExampleStyle:()=>C8p,FormParameterEncoding:()=>N8p,Language:()=>Q8p,MessageNamingSettingsSchema:()=>z8p,PathParameterOrder:()=>T8p,RemoveDiscriminantsFromSchemas:()=>q8p,UnionSettingsSchema:()=>R8p});var C8p={Minimal:"minimal",Comprehensive:"comprehensive"};var q8p={Always:"always",Never:"never"};var T8p={UrlOrder:"url-order",SpecOrder:"spec-order"};var R8p={V1:"v1"};var z8p={V1:"v1",V2:"v2"};var N8p={Form:"form",Json:"json"};var F8p={Int32:"int32",Int64:"int64",Uint32:"uint32",Uint64:"uint64"};var Q8p={Java:"java",Python:"python",Go:"go",Ruby:"ruby",Csharp:"csharp",Typescript:"typescript",Php:"php",Rust:"rust",Swift:"swift"};var pyc={};Yt(pyc,{GithubCommitAndReleaseMode:()=>L8p,GithubSelfhostedMode:()=>U8p});var U8p={PullRequest:"pull-request",Push:"push"};var L8p={Commit:"commit",Release:"release"};var _yc={};Yt(_yc,{GithubLicenseType:()=>V8p});var V8p={Mit:"MIT",Apache:"Apache-2.0"};var W8p={};var yyc={};Yt(yyc,{AvailabilityStatusSchema:()=>x8p,auth:()=>G8p,availability:()=>hyc,commons:()=>H8p,encoding:()=>K8p,environments:()=>J8p,file:()=>$8p,service:()=>Y8p,types:()=>X8p,validation:()=>Z8p});var G8p={};var hyc={};Yt(hyc,{AvailabilityStatusSchema:()=>x8p});var x8p={InDevelopment:"in-development",PreRelease:"pre-release",Deprecated:"deprecated",GenerallyAvailable:"generally-available"};var H8p={};var K8p={};var J8p={};var $8p={};var Y8p={};var X8p={};var Z8p={};var zyc={};Yt(zyc,{AiServicesSchema:()=>ELo,ApiConfigurationSchema:()=>MVo,ApiConfigurationSchemaInternal:()=>GXn,ApiConfigurationV2Schema:()=>SVo,ApiConfigurationV2SettingsSchema:()=>YXn,ApiConfigurationV2SpecsSchema:()=>$Xn,ApiDefinitionList:()=>xLo,ApiDefinitionPathSchema:()=>Exi,ApiDefinitionSchema:()=>GLo,ApiDefinitionSettingsSchema:()=>UXn,ApiDefinitionWithOverridesSchema:()=>LXn,AsyncApiSettingsSchema:()=>JXn,AsyncApiSpecSchema:()=>nVo,BaseApiSettingsSchema:()=>KXn,ConjureSchema:()=>sVo,CratesOutputLocationSchema:()=>HVo,DefaultIntegerFormat:()=>rVo,ExampleStyle:()=>RVo,FormParameterEncoding:()=>XLo,GeneratorApiSettingsSchema:()=>n3o,GeneratorGroupSchema:()=>o3o,GeneratorInvocationSchema:()=>a3o,GeneratorOutputSchema:()=>KVo,GeneratorPublishMetadataSchema:()=>w3a,GeneratorSnippetsSchema:()=>i3o,GeneratorsConfigurationSchema:()=>EWp,GeneratorsOpenApiObjectSchema:()=>u3o,GeneratorsOpenApiSchema:()=>s3o,GithubCommitAndReleaseMode:()=>ZVo,GithubCommitAndReleaseSchema:()=>kVo,GithubConfigurationSchema:()=>r3o,GithubLicenseCustomSchema:()=>YVo,GithubLicenseSchema:()=>q0e,GithubLicenseType:()=>$Vo,GithubPullRequestSchema:()=>e3o,GithubPushSchema:()=>t3o,GithubSelfhostedMode:()=>JVo,GithubSelfhostedSchema:()=>XVo,Language:()=>qVo,LocalFileSystemOutputLocationSchema:()=>WVo,MavenOutputLocationSchema:()=>QVo,MavenOutputSignatureSchema:()=>FVo,MessageNamingSettingsSchema:()=>NXn,ModelName:()=>wLo,ModelProvider:()=>jLo,NamespacedApiConfigurationSchema:()=>HLo,NpmOutputLocationSchema:()=>NVo,NugetOutputLocationSchema:()=>GVo,OpenApiExampleGenerationSchema:()=>kLo,OpenApiFilterSchema:()=>ZLo,OpenApiSettingsSchema:()=>Sxi,OpenApiSpecSchema:()=>iVo,OpenRpcSpecSchema:()=>oVo,OutputMetadataAuthor:()=>IVo,OutputMetadataSchema:()=>Dxi,PathParameterOrder:()=>QXn,PostmanOutputLocationSchema:()=>VVo,ProtobufApiDefinitionSchema:()=>WXn,ProtobufDefinitionSchema:()=>VXn,ProtobufSpecSchema:()=>aVo,PypiOutputLocationSchema:()=>LVo,PypiOutputMetadataSchema:()=>UVo,ReadmeCustomSectionSchema:()=>TVo,ReadmeEndpointObjectSchema:()=>CVo,ReadmeEndpointSchema:()=>P3a,ReadmeSchema:()=>zVo,RemoveDiscriminantsFromSchemas:()=>FXn,RequestOrResponseExampleGenerationSchema:()=>A3a,ResolveAliases:()=>tVo,ResolveAliasesSchema:()=>eVo,ReviewerSchema:()=>j3a,ReviewersSchema:()=>Bxi,RubyGemsOutputLocationSchema:()=>xVo,SpecSchema:()=>uVo,UnionSettingsSchema:()=>WLo,WhitelabelConfigurationSchema:()=>BVo,WhitelabelGithubConfigurationSchema:()=>DVo,ai:()=>myc,fernDefinition:()=>Ryc,generators:()=>Ayc,group:()=>Pyc,license:()=>jyc,reviewers:()=>wyc});var myc={};Yt(myc,{AiServicesSchema:()=>ELo,ModelName:()=>wLo,ModelProvider:()=>jLo});var fe={};Yt(fe,{JsonError:()=>qXn,ParseError:()=>TXn,any:()=>pWp,bigint:()=>eWp,boolean:()=>_Wp,booleanLiteral:()=>dWp,date:()=>tWp,discriminant:()=>PWp,enum_:()=>mLo,getObjectLikeUtils:()=>PVt,getObjectUtils:()=>Wdn,getSchemaUtils:()=>lA,isProperty:()=>Pxi,lazy:()=>rWp,lazyObject:()=>cWp,list:()=>PLo,number:()=>hWp,object:()=>ALo,objectWithoutOptionalProperties:()=>sWp,optional:()=>byc,property:()=>nWp,record:()=>gWp,set:()=>OWp,string:()=>yWp,stringLiteral:()=>fWp,transform:()=>vyc,undiscriminatedUnion:()=>AWp,union:()=>wWp,unknown:()=>bWp,withParsedProperties:()=>Oyc});var hp={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",NULLABLE:"nullable",OPTIONAL:"optional",OPTIONAL_NULLABLE:"optionalNullable"};function cA(e,t){return`Expected ${t}. Received ${FbS(e)}.`}function FbS(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function SN(e){return{...e,json:k8p(e.json),parse:k8p(e.parse)}}function k8p(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
928
|
-
`)),{ok:!0,value:t}):i}}function OLo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var qXn=class e extends Error{errors;constructor(t){super(t.map(OLo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var TXn=class e extends Error{errors;constructor(t){super(t.map(OLo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function lA(e){return{nullable:()=>QbS(e),optional:()=>byc(e),optionalNullable:()=>UbS(e),transform:t=>vyc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new TXn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new qXn(i.errors)}}}function QbS(e){let t={parse:(r,i)=>r==null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.NULLABLE};return{...t,...lA(t)}}function byc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.OPTIONAL};return{...t,...lA(t)}}function UbS(e){let t={parse:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.OPTIONAL_NULLABLE};return{...t,...lA(t)}}function vyc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...lA(r)}}function eWp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:cA(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:cA(t,"bigint")}]}:{ok:!0,value:t},getType:()=>hp.BIGINT};return{...SN(e),...lA(e)}}var LbS=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function tWp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:cA(t,"string")}]}:LbS.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:cA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:cA(t,"Date object")}]},getType:()=>hp.DATE};return{...SN(e),...lA(e)}}function M8(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...SN(r),...lA(r)}}}function mLo(e){let t=new Set(e);return M8(hp.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:cA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:cA(i,"enum")}]}:{ok:!0,value:i})()}function rWp(e){let t=gyc(e);return{...t,...lA(t)}}function gyc(e){return{parse:(t,r)=>RXn(e).parse(t,r),json:(t,r)=>RXn(e).json(t,r),getType:()=>RXn(e).getType()}}function RXn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function g3a(e){return Object.entries(e)}function O3a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function Axi(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function m3a(e){return Object.keys(e)}function iWp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function PVt(e){return{withParsedProperties:t=>Oyc(e,t)}}function Oyc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...o}}},json:(i,n)=>{if(!Axi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:cA(i,"object")}]};let a=new Set(Object.keys(t)),o=O3a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...lA(r),...PVt(r)}}function nWp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Pxi(e){return e.isProperty}function ALo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>Pxi(i)?i.rawKey:r),_getParsedProperties:()=>m3a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of g3a(e)){let d=Pxi(c)?c.rawKey:o,s=Pxi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,uWp(s)&&a.push(d)}return aWp({value:r,requiredKeys:a,getProperty:o=>{let c=n[o];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,o]of g3a(e)){let c=Pxi(o)?o.valueSchema:o;uWp(c)&&n.push(a)}return aWp({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return Pxi(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>hp.OBJECT};return{...SN(t),...lA(t),...PVt(t),...Wdn(t)}}function aWp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!Axi(e))return{ok:!1,errors:[{path:a,message:cA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.transformedKey]=p.value:(d[s]=u,c.push(...p.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=u;break}}return c.push(...t.filter(s=>o.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function Wdn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>oWp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>oWp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>hp.OBJECT};return{...r,...lA(r),...PVt(r),...Wdn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>hp.OBJECT};return{...t,...lA(t),...PVt(t),...Wdn(t)}}}}function oWp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=iWp(m3a(t),s=>n.has(s)),c=r(O3a(t,o)),d=i(O3a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function uWp(e){return!VbS(e)}function VbS(e){switch(e.getType()){case hp.ANY:case hp.UNKNOWN:case hp.OPTIONAL:case hp.OPTIONAL_NULLABLE:return!0;default:return!1}}function sWp(e){return ALo(e)}function cWp(e){let t={...gyc(e),_getRawProperties:()=>RXn(e)._getRawProperties(),_getParsedProperties:()=>RXn(e)._getParsedProperties()};return{...t,...lA(t),...PVt(t),...Wdn(t)}}function PLo(e){let t={parse:(r,i)=>lWp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>lWp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>hp.LIST};return{...SN(t),...lA(t)}}function lWp(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:cA(e,"list"),path:[]}]}}function fWp(e){return M8(hp.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:cA(r,`"${e}"`)}]})()}function dWp(e){return M8(hp.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:cA(r,`${e.toString()}`)}]})()}var pWp=M8(hp.ANY,e=>({ok:!0,value:e}));var _Wp=M8(hp.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"boolean")}]});var hWp=M8(hp.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"number")}]});var yWp=M8(hp.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"string")}]});var bWp=M8(hp.UNKNOWN,e=>({ok:!0,value:e}));function gWp(e,t){let r={parse:(i,n)=>vWp({value:i,isKeyNumeric:e.getType()===hp.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>vWp({value:i,isKeyNumeric:e.getType()===hp.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>hp.RECORD};return{...SN(r),...lA(r)}}function vWp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return Axi(e)?g3a(e).reduce((a,[o,c])=>{if(c===void 0)return a;let d=a,s=o;if(t){let _=o.length>0?Number(o):NaN;isNaN(_)||(s=_)}let u=r(s),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:cA(e,"object")}]}}function OWp(e){let t=PLo(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:cA(i,"Set")}]},getType:()=>hp.SET};return{...SN(r),...lA(r)}}function AWp(e){let t={parse:(r,i)=>mWp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>mWp((n,a)=>n.json(r,a),e,i),getType:()=>hp.UNDISCRIMINATED_UNION};return{...SN(t),...lA(t)}}function mWp(e,t,r){let i=[];for(let[n,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function PWp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function wWp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=mLo(m3a(t)),a={parse:(o,c)=>jWp({value:o,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>jWp({value:o,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>hp.UNION};return{...SN(a),...lA(a),...PVt(a)}}function jWp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!Axi(e))return{ok:!1,errors:[{path:c,message:cA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let u=i(d);if(!u.ok)return{ok:!1,errors:u.errors};let l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var jLo=fe.enum_(["openai","anthropic","bedrock"]);var wLo=fe.string();var ELo=fe.object({provider:jLo,model:wLo});var Ayc={};Yt(Ayc,{ApiConfigurationSchema:()=>MVo,ApiConfigurationSchemaInternal:()=>GXn,ApiConfigurationV2Schema:()=>SVo,ApiConfigurationV2SettingsSchema:()=>YXn,ApiConfigurationV2SpecsSchema:()=>$Xn,ApiDefinitionList:()=>xLo,ApiDefinitionPathSchema:()=>Exi,ApiDefinitionSchema:()=>GLo,ApiDefinitionSettingsSchema:()=>UXn,ApiDefinitionWithOverridesSchema:()=>LXn,AsyncApiSettingsSchema:()=>JXn,AsyncApiSpecSchema:()=>nVo,BaseApiSettingsSchema:()=>KXn,ConjureSchema:()=>sVo,DefaultIntegerFormat:()=>rVo,ExampleStyle:()=>RVo,FormParameterEncoding:()=>XLo,GeneratorsConfigurationSchema:()=>EWp,GeneratorsOpenApiObjectSchema:()=>u3o,GeneratorsOpenApiSchema:()=>s3o,Language:()=>qVo,MessageNamingSettingsSchema:()=>NXn,NamespacedApiConfigurationSchema:()=>HLo,OpenApiExampleGenerationSchema:()=>kLo,OpenApiFilterSchema:()=>ZLo,OpenApiSettingsSchema:()=>Sxi,OpenApiSpecSchema:()=>iVo,OpenRpcSpecSchema:()=>oVo,OutputMetadataAuthor:()=>IVo,OutputMetadataSchema:()=>Dxi,PathParameterOrder:()=>QXn,ProtobufApiDefinitionSchema:()=>WXn,ProtobufDefinitionSchema:()=>VXn,ProtobufSpecSchema:()=>aVo,ReadmeCustomSectionSchema:()=>TVo,ReadmeEndpointObjectSchema:()=>CVo,ReadmeEndpointSchema:()=>P3a,ReadmeSchema:()=>zVo,RemoveDiscriminantsFromSchemas:()=>FXn,RequestOrResponseExampleGenerationSchema:()=>A3a,ResolveAliases:()=>tVo,ResolveAliasesSchema:()=>eVo,SpecSchema:()=>uVo,UnionSettingsSchema:()=>WLo,WhitelabelConfigurationSchema:()=>BVo,WhitelabelGithubConfigurationSchema:()=>DVo});var SLo=fe.string();var MLo=fe.object({"client-id":fe.string().optional(),"client-secret":fe.string().optional(),scopes:fe.string().optional()});var DLo=fe.object({"access-token":fe.string().optional(),"expires-in":fe.string().optional(),"refresh-token":fe.string().optional()});var BLo=fe.object({endpoint:fe.string(),"request-properties":MLo.optional(),"response-properties":DLo.optional()});var ILo=fe.object({"refresh-token":fe.string()});var CLo=fe.object({"access-token":fe.string().optional(),"expires-in":fe.string().optional(),"refresh-token":fe.string().optional()});var qLo=fe.object({endpoint:fe.string(),"request-properties":ILo.optional(),"response-properties":CLo.optional()});var hM=fe.object({docs:fe.string().optional()});var TLo=fe.object({scheme:fe.stringLiteral("oauth"),type:fe.stringLiteral("client-credentials"),scopes:fe.list(SLo).optional(),"client-id-env":fe.string().optional(),"client-secret-env":fe.string().optional(),"token-prefix":fe.string().optional(),"token-header":fe.string().optional(),"get-token":BLo,"refresh-token":qLo.optional()}).extend(hM);var zXn=fe.object({env:fe.string().optional()});var jxi=fe.object({name:fe.string().optional()});var RLo=fe.object({header:fe.string(),type:fe.string().optional(),prefix:fe.string().optional()}).extend(zXn).extend(jxi).extend(hM);var Gdn=fe.object({}).extend(zXn).extend(jxi);var zLo=fe.object({scheme:fe.stringLiteral("basic"),username:Gdn.optional(),password:Gdn.optional()}).extend(hM);var NLo=fe.object({scheme:fe.stringLiteral("bearer"),token:Gdn.optional()}).extend(hM);var FLo=fe.object({"response-property":fe.string(),"header-name":fe.string(),"value-prefix":fe.string().optional()});var QLo=fe.object({endpoint:fe.string(),"expiry-response-property":fe.string().optional(),"authenticated-request-headers":fe.list(FLo).optional()});var ULo=fe.undiscriminatedUnion([fe.string(),QLo]);var LLo=fe.object({scheme:fe.stringLiteral("bearer"),"get-token":ULo}).extend(hM);var VLo=fe.undiscriminatedUnion([NLo,LLo]);var wxi=fe.undiscriminatedUnion([TLo,RLo,zLo,VLo]);var Exi=fe.string();var WLo=fe.enum_(["v1"]);var NXn=fe.enum_(["v1","v2"]);var FXn=fe.enum_(["always","never"]);var QXn=fe.enum_(["url-order","spec-order"]);var UXn=fe.object({"use-title":fe.boolean().optional(),unions:WLo.optional(),"message-naming":NXn.optional(),"respect-nullable-schemas":fe.boolean().optional(),"only-include-referenced-schemas":fe.boolean().optional(),"inline-path-parameters":fe.boolean().optional(),"idiomatic-request-names":fe.boolean().optional(),"wrap-references-to-nullable-in-optional":fe.boolean().optional(),"coerce-optional-schemas-to-nullable":fe.boolean().optional(),"group-environments-by-host":fe.boolean().optional(),"remove-discriminants-from-schemas":FXn.optional(),"path-parameter-order":QXn.optional()});var LXn=fe.object({path:Exi,origin:fe.string().optional(),overrides:fe.string().optional(),audiences:fe.list(fe.string()).optional(),settings:UXn.optional()});var VXn=fe.object({target:fe.string().optional(),root:fe.string(),overrides:fe.string().optional(),"local-generation":fe.boolean().optional(),"from-openapi":fe.boolean().optional(),dependencies:fe.list(fe.string()).optional()});var WXn=fe.object({proto:VXn});var GLo=fe.undiscriminatedUnion([Exi,LXn,WXn]);var xLo=fe.list(GLo);var GXn=fe.undiscriminatedUnion([Exi,LXn,xLo,WXn]);var HLo=fe.object({namespaces:fe.record(fe.string(),GXn)});var xXn=fe.object({scheme:fe.string()}).extend(hM);var KLo=fe.undiscriminatedUnion([fe.string(),xXn]);var JLo=fe.object({any:fe.list(KLo)}).extend(hM);var $Lo=fe.object({});var YLo=fe.object({"endpoint-security":$Lo}).extend(hM);var HXn=fe.undiscriminatedUnion([fe.string(),xXn,JLo,YLo]);var XLo=fe.enum_(["form","json"]);var ZLo=fe.object({endpoints:fe.list(fe.string()).optional()});var A3a=fe.object({"max-depth":fe.number().optional()});var kLo=fe.object({request:A3a.optional(),response:A3a.optional()});var eVo=fe.object({except:fe.list(fe.string()).optional()});var tVo=fe.undiscriminatedUnion([fe.boolean(),eVo]);var rVo=fe.enum_(["int32","int64","uint32","uint64"]);var KXn=fe.object({"respect-nullable-schemas":fe.boolean().optional(),"title-as-schema-name":fe.boolean().optional(),"optional-additional-properties":fe.boolean().optional(),"coerce-enums-to-literals":fe.boolean().optional(),"idiomatic-request-names":fe.boolean().optional(),"wrap-references-to-nullable-in-optional":fe.boolean().optional(),"coerce-optional-schemas-to-nullable":fe.boolean().optional(),"group-environments-by-host":fe.boolean().optional(),"remove-discriminants-from-schemas":FXn.optional(),"path-parameter-order":QXn.optional()});var Sxi=fe.object({"only-include-referenced-schemas":fe.boolean().optional(),"inline-path-parameters":fe.boolean().optional(),"prefer-undiscriminated-unions-with-literals":fe.boolean().optional(),"object-query-parameters":fe.boolean().optional(),"respect-readonly-schemas":fe.boolean().optional(),"respect-forward-compatible-enums":fe.boolean().optional(),"use-bytes-for-binary-response":fe.boolean().optional(),"default-form-parameter-encoding":XLo.optional(),filter:ZLo.optional(),"example-generation":kLo.optional(),"additional-properties-defaults-to":fe.boolean().optional(),"type-dates-as-strings":fe.boolean().optional(),"preserve-single-schema-oneof":fe.boolean().optional(),"inline-all-of-schemas":fe.boolean().optional(),"resolve-aliases":tVo.optional(),"group-multi-api-environments":fe.boolean().optional(),"default-integer-format":rVo.optional()}).extend(KXn);var iVo=fe.object({openapi:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),overlays:fe.string().optional(),namespace:fe.string().optional(),settings:Sxi.optional()});var JXn=fe.object({"message-naming":NXn.optional()}).extend(KXn);var nVo=fe.object({asyncapi:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),namespace:fe.string().optional(),settings:JXn.optional()});var aVo=fe.object({proto:VXn});var oVo=fe.object({openrpc:fe.string(),overrides:fe.string().optional(),namespace:fe.string().optional()});var uVo=fe.undiscriminatedUnion([iVo,nVo,aVo,oVo]);var sVo=fe.object({conjure:fe.string()});var $Xn=fe.undiscriminatedUnion([fe.list(uVo),sVo]);var YXn=fe.object({}).extend(Sxi).extend(JXn);var cVo=fe.object({type:fe.string()});var lVo=fe.object({proto:cVo.optional()});var fVo=fe.object({minLength:fe.number().optional(),maxLength:fe.number().optional(),pattern:fe.string().optional(),format:fe.string().optional()});var dVo=fe.object({min:fe.number().optional(),max:fe.number().optional(),exclusiveMin:fe.boolean().optional(),exclusiveMax:fe.boolean().optional(),multipleOf:fe.number().optional()});var pVo=fe.undiscriminatedUnion([fVo,dVo]);var XXn=fe.enum_(["in-development","pre-release","deprecated","generally-available"]);var _Vo=fe.object({status:XXn,message:fe.string().optional()});var hVo=fe.undiscriminatedUnion([XXn,_Vo]);var yVo=fe.object({availability:hVo.optional()});var bVo=fe.object({default:fe.unknown().optional(),encoding:lVo.optional(),validation:pVo.optional()}).extend(hM).extend(yVo);var Mxi=fe.object({audiences:fe.list(fe.string()).optional()});var vVo=fe.object({type:fe.string()}).extend(bVo).extend(jxi).extend(Mxi);var gVo=fe.object({env:fe.string().optional()}).extend(vVo);var OVo=fe.undiscriminatedUnion([fe.string(),gVo]);var mVo=OVo;var AVo=fe.object({headers:fe.record(fe.string(),mVo).optional()});var PVo=fe.object({url:fe.string()}).extend(Mxi).extend(hM);var jVo=fe.object({urls:fe.record(fe.string(),fe.string())}).extend(Mxi).extend(hM);var wVo=fe.undiscriminatedUnion([fe.string(),PVo,jVo]);var EVo=fe.object({"default-url":fe.string().optional(),"default-environment":fe.string().optional(),environments:fe.record(fe.string(),wVo).optional()});var SVo=fe.object({auth:HXn.optional(),"auth-schemes":fe.record(fe.string(),wxi).optional(),specs:$Xn,settings:YXn.optional()}).extend(AVo).extend(EVo);var MVo=fe.undiscriminatedUnion([GXn,HLo,SVo]);var DVo=fe.object({username:fe.string(),email:fe.string(),token:fe.string()});var BVo=fe.object({github:DVo.optional()});var IVo=fe.object({name:fe.string(),email:fe.string()});var Dxi=fe.object({description:fe.string().optional(),authors:fe.list(IVo).optional()});var CVo=fe.object({method:fe.string(),path:fe.string(),stream:fe.boolean().optional()});var P3a=fe.undiscriminatedUnion([fe.string(),CVo]);var qVo=fe.enum_(["java","python","go","ruby","csharp","typescript","php","rust","swift"]);var TVo=fe.object({title:fe.string(),language:qVo,content:fe.string()});var RVo=fe.enum_(["minimal","comprehensive"]);var zVo=fe.object({bannerLink:fe.string().optional(),introduction:fe.string().optional(),apiReferenceLink:fe.string().optional(),apiName:fe.string().optional(),disabledSections:fe.list(fe.string()).optional(),defaultEndpoint:P3a.optional(),features:fe.record(fe.string(),fe.list(P3a)).optional(),customSections:fe.list(TVo).optional(),exampleStyle:RVo.optional()});var NVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional()});var FVo=fe.object({keyId:fe.string(),password:fe.string(),secretKey:fe.string()});var QVo=fe.object({url:fe.string().optional(),coordinate:fe.string(),username:fe.string().optional(),password:fe.string().optional(),signature:FVo.optional()});var UVo=fe.object({keywords:fe.list(fe.string()).optional(),"documentation-link":fe.string().optional(),"homepage-link":fe.string().optional()}).extend(Dxi);var LVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional(),username:fe.string().optional(),password:fe.string().optional(),metadata:UVo.optional()});var VVo=fe.object({"api-key":fe.string(),"workspace-id":fe.string(),"collection-id":fe.string().optional()});var WVo=fe.object({path:fe.string()});var GVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),"api-key":fe.string().optional()});var xVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),"api-key":fe.string().optional()});var HVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional()});var KVo=fe.union("location",{npm:NVo,maven:QVo,pypi:LVo,postman:VVo,"local-file-system":WVo,nuget:GVo,rubygems:xVo,crates:HVo}).transform({transform:e=>e,untransform:e=>e});var JVo=fe.enum_(["pull-request","push"]);var $Vo=fe.enum_(["MIT","Apache-2.0"]);var YVo=fe.object({custom:fe.string()});var q0e=fe.undiscriminatedUnion([$Vo,YVo]);var XVo=fe.object({uri:fe.string(),token:fe.string(),mode:JVo.optional(),branch:fe.string().optional(),license:q0e.optional()});var ZVo=fe.enum_(["commit","release"]);var kVo=fe.object({repository:fe.string(),license:q0e.optional(),mode:ZVo.optional()});var j3a=fe.object({name:fe.string()});var Bxi=fe.object({teams:fe.list(j3a).optional(),users:fe.list(j3a).optional()});var e3o=fe.object({repository:fe.string(),branch:fe.string().optional(),license:q0e.optional(),mode:fe.stringLiteral("pull-request"),reviewers:Bxi.optional()});var t3o=fe.object({repository:fe.string(),license:q0e.optional(),mode:fe.stringLiteral("push"),branch:fe.string().optional()});var r3o=fe.undiscriminatedUnion([XVo,kVo,e3o,t3o]);var w3a=fe.object({"package-description":fe.string().optional(),email:fe.string().optional(),"reference-url":fe.string().optional(),author:fe.string().optional(),license:q0e.optional()});var i3o=fe.object({path:fe.string()});var n3o=fe.object({auth:HXn.optional(),"auth-schemes":fe.record(fe.string(),wxi).optional(),settings:YXn.optional(),specs:$Xn.optional()});var a3o=fe.object({name:fe.string(),version:fe.string(),output:KVo.optional(),github:r3o.optional(),config:fe.unknown().optional(),metadata:w3a.optional(),keywords:fe.list(fe.string()).optional(),snippets:i3o.optional(),"ir-version":fe.string().optional(),"smart-casing":fe.boolean().optional(),api:n3o.optional(),"disable-examples":fe.boolean().optional(),"publish-metadata":w3a.optional(),autorelease:fe.boolean().optional()});var o3o=fe.object({audiences:fe.list(fe.string()).optional(),generators:fe.list(a3o),metadata:Dxi.optional(),reviewers:Bxi.optional()});var u3o=fe.object({path:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),"disable-examples":fe.boolean().optional(),settings:Sxi});var s3o=fe.undiscriminatedUnion([u3o,fe.string()]);var EWp=fe.object({"auth-schemes":fe.record(fe.string(),wxi).optional(),api:MVo.optional(),whitelabel:BVo.optional(),metadata:Dxi.optional(),readme:zVo.optional(),"default-group":fe.string().optional(),aliases:fe.record(fe.string(),fe.list(fe.string())).optional(),groups:fe.record(fe.string(),o3o).optional(),reviewers:Bxi.optional(),ai:ELo.optional(),autorelease:fe.boolean().optional(),openapi:s3o.optional(),"openapi-overrides":fe.string().optional(),"spec-origin":fe.string().optional(),"async-api":fe.string().optional(),"api-settings":UXn.optional()});var Pyc={};Yt(Pyc,{CratesOutputLocationSchema:()=>HVo,GeneratorApiSettingsSchema:()=>n3o,GeneratorGroupSchema:()=>o3o,GeneratorInvocationSchema:()=>a3o,GeneratorOutputSchema:()=>KVo,GeneratorPublishMetadataSchema:()=>w3a,GeneratorSnippetsSchema:()=>i3o,GithubCommitAndReleaseMode:()=>ZVo,GithubCommitAndReleaseSchema:()=>kVo,GithubConfigurationSchema:()=>r3o,GithubPullRequestSchema:()=>e3o,GithubPushSchema:()=>t3o,GithubSelfhostedMode:()=>JVo,GithubSelfhostedSchema:()=>XVo,LocalFileSystemOutputLocationSchema:()=>WVo,MavenOutputLocationSchema:()=>QVo,MavenOutputSignatureSchema:()=>FVo,NpmOutputLocationSchema:()=>NVo,NugetOutputLocationSchema:()=>GVo,PostmanOutputLocationSchema:()=>VVo,PypiOutputLocationSchema:()=>LVo,PypiOutputMetadataSchema:()=>UVo,RubyGemsOutputLocationSchema:()=>xVo});var jyc={};Yt(jyc,{GithubLicenseCustomSchema:()=>YVo,GithubLicenseSchema:()=>q0e,GithubLicenseType:()=>$Vo});var wyc={};Yt(wyc,{ReviewerSchema:()=>j3a,ReviewersSchema:()=>Bxi});var Ryc={};Yt(Ryc,{AnyAuthItem:()=>KLo,AnyAuthSchemesSchema:()=>JLo,ApiAuthSchema:()=>HXn,AuthSchemeDeclarationSchema:()=>wxi,AuthSchemeReferenceSchema:()=>xXn,AuthScope:()=>SLo,AuthVariable:()=>Gdn,AvailabilitySchema:()=>_Vo,AvailabilityStatusSchema:()=>XXn,AvailabilityUnionSchema:()=>hVo,BaseTypeReferenceSchema:()=>bVo,BasicAuthSchemeSchema:()=>zLo,BearerAuthSchemeSchema:()=>VLo,EncodingSchema:()=>lVo,EndpointSecuritySchema:()=>YLo,EndpointSecuritySchemaDetails:()=>$Lo,EnvironmentSchema:()=>wVo,HeaderAuthSchemeSchema:()=>RLo,HttpHeaderSchema:()=>mVo,InferredAuthenticatedRequestHeader:()=>FLo,InferredBearerAuthSchema:()=>LLo,InferredGetTokenEndpointSchema:()=>ULo,InferredGetTokenEndpointSchemaObject:()=>QLo,MultipleBaseUrlsEnvironmentSchema:()=>jVo,NumberValidationSchema:()=>dVo,OAuthAccessTokenRequestPropertiesSchema:()=>MLo,OAuthAccessTokenResponsePropertiesSchema:()=>DLo,OAuthGetTokenEndpointSchema:()=>BLo,OAuthRefreshTokenEndpointSchema:()=>qLo,OAuthRefreshTokenRequestPropertiesSchema:()=>ILo,OAuthRefreshTokenResponsePropertiesSchema:()=>CLo,OAuthSchemeSchema:()=>TLo,ProtobufTypeSchema:()=>cVo,SingleBaseUrlEnvironmentSchema:()=>PVo,StringValidationSchema:()=>fVo,TokenBearerAuthSchema:()=>NLo,TypeReferenceDeclarationWithEnvOverride:()=>OVo,TypeReferenceDeclarationWithEnvOverrideSchema:()=>gVo,TypeReferenceDeclarationWithName:()=>vVo,ValidationSchema:()=>pVo,WithAudiences:()=>Mxi,WithAvailability:()=>yVo,WithDocsSchema:()=>hM,WithEnvironmentVariable:()=>zXn,WithEnvironmentsSchema:()=>EVo,WithHeadersSchema:()=>AVo,WithName:()=>jxi,auth:()=>Eyc,availability:()=>Syc,commons:()=>Myc,encoding:()=>Dyc,environments:()=>Byc,file:()=>Iyc,service:()=>Cyc,types:()=>qyc,validation:()=>Tyc});var Eyc={};Yt(Eyc,{AnyAuthItem:()=>KLo,AnyAuthSchemesSchema:()=>JLo,ApiAuthSchema:()=>HXn,AuthSchemeDeclarationSchema:()=>wxi,AuthSchemeReferenceSchema:()=>xXn,AuthScope:()=>SLo,AuthVariable:()=>Gdn,BasicAuthSchemeSchema:()=>zLo,BearerAuthSchemeSchema:()=>VLo,EndpointSecuritySchema:()=>YLo,EndpointSecuritySchemaDetails:()=>$Lo,HeaderAuthSchemeSchema:()=>RLo,InferredAuthenticatedRequestHeader:()=>FLo,InferredBearerAuthSchema:()=>LLo,InferredGetTokenEndpointSchema:()=>ULo,InferredGetTokenEndpointSchemaObject:()=>QLo,OAuthAccessTokenRequestPropertiesSchema:()=>MLo,OAuthAccessTokenResponsePropertiesSchema:()=>DLo,OAuthGetTokenEndpointSchema:()=>BLo,OAuthRefreshTokenEndpointSchema:()=>qLo,OAuthRefreshTokenRequestPropertiesSchema:()=>ILo,OAuthRefreshTokenResponsePropertiesSchema:()=>CLo,OAuthSchemeSchema:()=>TLo,TokenBearerAuthSchema:()=>NLo,WithEnvironmentVariable:()=>zXn});var Syc={};Yt(Syc,{AvailabilitySchema:()=>_Vo,AvailabilityStatusSchema:()=>XXn,AvailabilityUnionSchema:()=>hVo});var Myc={};Yt(Myc,{WithAudiences:()=>Mxi,WithAvailability:()=>yVo,WithDocsSchema:()=>hM,WithName:()=>jxi});var Dyc={};Yt(Dyc,{EncodingSchema:()=>lVo,ProtobufTypeSchema:()=>cVo});var Byc={};Yt(Byc,{EnvironmentSchema:()=>wVo,MultipleBaseUrlsEnvironmentSchema:()=>jVo,SingleBaseUrlEnvironmentSchema:()=>PVo,WithEnvironmentsSchema:()=>EVo});var Iyc={};Yt(Iyc,{WithHeadersSchema:()=>AVo});var Cyc={};Yt(Cyc,{HttpHeaderSchema:()=>mVo,TypeReferenceDeclarationWithEnvOverride:()=>OVo,TypeReferenceDeclarationWithEnvOverrideSchema:()=>gVo});var qyc={};Yt(qyc,{BaseTypeReferenceSchema:()=>bVo,TypeReferenceDeclarationWithName:()=>vVo});var Tyc={};Yt(Tyc,{NumberValidationSchema:()=>dVo,StringValidationSchema:()=>fVo,ValidationSchema:()=>pVo});function SWp(e){return e?.specs!=null}function MWp(e){return e?.asyncapi!=null}function DWp(e){return e?.conjure!=null}function BWp(e){return e?.namespaces!=null}function IWp(e){return e?.openapi!=null}function CWp(e){return e?.openrpc!=null}function qWp(e){return e?.proto!=null}var TWp=ue(require("path"),1);async function c3o({schema:e,value:t,context:r,filepathBeingParsed:i}){let n=await e.safeParseAsync(t);if(n.success)return n.data;let a=n.error.errors.map(c=>{let d=c.path.length>0?`${c.message} at "${WbS(c.path)}"`:c.message;return tVt({content:d,prefix:" - "})}),o=[`Failed to parse file: ${TWp.default.relative(process.cwd(),i)}`,...a].join(`
|
|
928
|
+
`)),{ok:!0,value:t}):i}}function OLo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var qXn=class e extends Error{errors;constructor(t){super(t.map(OLo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var TXn=class e extends Error{errors;constructor(t){super(t.map(OLo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function lA(e){return{nullable:()=>QbS(e),optional:()=>byc(e),optionalNullable:()=>UbS(e),transform:t=>vyc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new TXn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new qXn(i.errors)}}}function QbS(e){let t={parse:(r,i)=>r==null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.NULLABLE};return{...t,...lA(t)}}function byc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.OPTIONAL};return{...t,...lA(t)}}function UbS(e){let t={parse:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,i),getType:()=>hp.OPTIONAL_NULLABLE};return{...t,...lA(t)}}function vyc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...lA(r)}}function eWp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:cA(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:cA(t,"bigint")}]}:{ok:!0,value:t},getType:()=>hp.BIGINT};return{...SN(e),...lA(e)}}var LbS=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function tWp(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:cA(t,"string")}]}:LbS.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:cA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:cA(t,"Date object")}]},getType:()=>hp.DATE};return{...SN(e),...lA(e)}}function M8(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...SN(r),...lA(r)}}}function mLo(e){let t=new Set(e);return M8(hp.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:cA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:cA(i,"enum")}]}:{ok:!0,value:i})()}function rWp(e){let t=gyc(e);return{...t,...lA(t)}}function gyc(e){return{parse:(t,r)=>RXn(e).parse(t,r),json:(t,r)=>RXn(e).json(t,r),getType:()=>RXn(e).getType()}}function RXn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function g3a(e){return Object.entries(e)}function O3a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function Axi(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function m3a(e){return Object.keys(e)}function iWp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function PVt(e){return{withParsedProperties:t=>Oyc(e,t)}}function Oyc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...o}}},json:(i,n)=>{if(!Axi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:cA(i,"object")}]};let a=new Set(Object.keys(t)),o=O3a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...lA(r),...PVt(r)}}function nWp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Pxi(e){return e.isProperty}function ALo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>Pxi(i)?i.rawKey:r),_getParsedProperties:()=>m3a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of g3a(e)){let d=Pxi(c)?c.rawKey:o,s=Pxi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,uWp(s)&&a.push(d)}return aWp({value:r,requiredKeys:a,getProperty:o=>{let c=n[o];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,o]of g3a(e)){let c=Pxi(o)?o.valueSchema:o;uWp(c)&&n.push(a)}return aWp({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return Pxi(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>hp.OBJECT};return{...SN(t),...lA(t),...PVt(t),...Wdn(t)}}function aWp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!Axi(e))return{ok:!1,errors:[{path:a,message:cA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.transformedKey]=p.value:(d[s]=u,c.push(...p.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=u;break}}return c.push(...t.filter(s=>o.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function Wdn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>oWp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>oWp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>hp.OBJECT};return{...r,...lA(r),...PVt(r),...Wdn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>hp.OBJECT};return{...t,...lA(t),...PVt(t),...Wdn(t)}}}}function oWp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=iWp(m3a(t),s=>n.has(s)),c=r(O3a(t,o)),d=i(O3a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function uWp(e){return!VbS(e)}function VbS(e){switch(e.getType()){case hp.ANY:case hp.UNKNOWN:case hp.OPTIONAL:case hp.OPTIONAL_NULLABLE:return!0;default:return!1}}function sWp(e){return ALo(e)}function cWp(e){let t={...gyc(e),_getRawProperties:()=>RXn(e)._getRawProperties(),_getParsedProperties:()=>RXn(e)._getParsedProperties()};return{...t,...lA(t),...PVt(t),...Wdn(t)}}function PLo(e){let t={parse:(r,i)=>lWp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>lWp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>hp.LIST};return{...SN(t),...lA(t)}}function lWp(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:cA(e,"list"),path:[]}]}}function fWp(e){return M8(hp.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:cA(r,`"${e}"`)}]})()}function dWp(e){return M8(hp.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:cA(r,`${e.toString()}`)}]})()}var pWp=M8(hp.ANY,e=>({ok:!0,value:e}));var _Wp=M8(hp.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"boolean")}]});var hWp=M8(hp.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"number")}]});var yWp=M8(hp.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:cA(e,"string")}]});var bWp=M8(hp.UNKNOWN,e=>({ok:!0,value:e}));function gWp(e,t){let r={parse:(i,n)=>vWp({value:i,isKeyNumeric:e.getType()===hp.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>vWp({value:i,isKeyNumeric:e.getType()===hp.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>hp.RECORD};return{...SN(r),...lA(r)}}function vWp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return Axi(e)?g3a(e).reduce((a,[o,c])=>{if(c===void 0)return a;let d=a,s=o;if(t){let _=o.length>0?Number(o):NaN;isNaN(_)||(s=_)}let u=r(s),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:cA(e,"object")}]}}function OWp(e){let t=PLo(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:cA(i,"Set")}]},getType:()=>hp.SET};return{...SN(r),...lA(r)}}function AWp(e){let t={parse:(r,i)=>mWp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>mWp((n,a)=>n.json(r,a),e,i),getType:()=>hp.UNDISCRIMINATED_UNION};return{...SN(t),...lA(t)}}function mWp(e,t,r){let i=[];for(let[n,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function PWp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function wWp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=mLo(m3a(t)),a={parse:(o,c)=>jWp({value:o,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>jWp({value:o,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>hp.UNION};return{...SN(a),...lA(a),...PVt(a)}}function jWp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!Axi(e))return{ok:!1,errors:[{path:c,message:cA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let u=i(d);if(!u.ok)return{ok:!1,errors:u.errors};let l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var jLo=fe.enum_(["openai","anthropic","bedrock"]);var wLo=fe.string();var ELo=fe.object({provider:jLo,model:wLo});var Ayc={};Yt(Ayc,{ApiConfigurationSchema:()=>MVo,ApiConfigurationSchemaInternal:()=>GXn,ApiConfigurationV2Schema:()=>SVo,ApiConfigurationV2SettingsSchema:()=>YXn,ApiConfigurationV2SpecsSchema:()=>$Xn,ApiDefinitionList:()=>xLo,ApiDefinitionPathSchema:()=>Exi,ApiDefinitionSchema:()=>GLo,ApiDefinitionSettingsSchema:()=>UXn,ApiDefinitionWithOverridesSchema:()=>LXn,AsyncApiSettingsSchema:()=>JXn,AsyncApiSpecSchema:()=>nVo,BaseApiSettingsSchema:()=>KXn,ConjureSchema:()=>sVo,DefaultIntegerFormat:()=>rVo,ExampleStyle:()=>RVo,FormParameterEncoding:()=>XLo,GeneratorsConfigurationSchema:()=>EWp,GeneratorsOpenApiObjectSchema:()=>u3o,GeneratorsOpenApiSchema:()=>s3o,Language:()=>qVo,MessageNamingSettingsSchema:()=>NXn,NamespacedApiConfigurationSchema:()=>HLo,OpenApiExampleGenerationSchema:()=>kLo,OpenApiFilterSchema:()=>ZLo,OpenApiSettingsSchema:()=>Sxi,OpenApiSpecSchema:()=>iVo,OpenRpcSpecSchema:()=>oVo,OutputMetadataAuthor:()=>IVo,OutputMetadataSchema:()=>Dxi,PathParameterOrder:()=>QXn,ProtobufApiDefinitionSchema:()=>WXn,ProtobufDefinitionSchema:()=>VXn,ProtobufSpecSchema:()=>aVo,ReadmeCustomSectionSchema:()=>TVo,ReadmeEndpointObjectSchema:()=>CVo,ReadmeEndpointSchema:()=>P3a,ReadmeSchema:()=>zVo,RemoveDiscriminantsFromSchemas:()=>FXn,RequestOrResponseExampleGenerationSchema:()=>A3a,ResolveAliases:()=>tVo,ResolveAliasesSchema:()=>eVo,SpecSchema:()=>uVo,UnionSettingsSchema:()=>WLo,WhitelabelConfigurationSchema:()=>BVo,WhitelabelGithubConfigurationSchema:()=>DVo});var SLo=fe.string();var MLo=fe.object({"client-id":fe.string().optional(),"client-secret":fe.string().optional(),scopes:fe.string().optional()});var DLo=fe.object({"access-token":fe.string().optional(),"expires-in":fe.string().optional(),"refresh-token":fe.string().optional()});var BLo=fe.object({endpoint:fe.string(),"request-properties":MLo.optional(),"response-properties":DLo.optional()});var ILo=fe.object({"refresh-token":fe.string()});var CLo=fe.object({"access-token":fe.string().optional(),"expires-in":fe.string().optional(),"refresh-token":fe.string().optional()});var qLo=fe.object({endpoint:fe.string(),"request-properties":ILo.optional(),"response-properties":CLo.optional()});var hM=fe.object({docs:fe.string().optional()});var TLo=fe.object({scheme:fe.stringLiteral("oauth"),type:fe.stringLiteral("client-credentials"),scopes:fe.list(SLo).optional(),"client-id-env":fe.string().optional(),"client-secret-env":fe.string().optional(),"token-prefix":fe.string().optional(),"token-header":fe.string().optional(),"get-token":BLo,"refresh-token":qLo.optional()}).extend(hM);var zXn=fe.object({env:fe.string().optional()});var jxi=fe.object({name:fe.string().optional()});var RLo=fe.object({header:fe.string(),type:fe.string().optional(),prefix:fe.string().optional()}).extend(zXn).extend(jxi).extend(hM);var Gdn=fe.object({omit:fe.boolean().optional()}).extend(zXn).extend(jxi);var zLo=fe.object({scheme:fe.stringLiteral("basic"),username:Gdn.optional(),password:Gdn.optional()}).extend(hM);var NLo=fe.object({scheme:fe.stringLiteral("bearer"),token:Gdn.optional()}).extend(hM);var FLo=fe.object({"response-property":fe.string(),"header-name":fe.string(),"value-prefix":fe.string().optional()});var QLo=fe.object({endpoint:fe.string(),"expiry-response-property":fe.string().optional(),"authenticated-request-headers":fe.list(FLo).optional()});var ULo=fe.undiscriminatedUnion([fe.string(),QLo]);var LLo=fe.object({scheme:fe.stringLiteral("bearer"),"get-token":ULo}).extend(hM);var VLo=fe.undiscriminatedUnion([NLo,LLo]);var wxi=fe.undiscriminatedUnion([TLo,RLo,zLo,VLo]);var Exi=fe.string();var WLo=fe.enum_(["v1"]);var NXn=fe.enum_(["v1","v2"]);var FXn=fe.enum_(["always","never"]);var QXn=fe.enum_(["url-order","spec-order"]);var UXn=fe.object({"use-title":fe.boolean().optional(),unions:WLo.optional(),"message-naming":NXn.optional(),"respect-nullable-schemas":fe.boolean().optional(),"only-include-referenced-schemas":fe.boolean().optional(),"inline-path-parameters":fe.boolean().optional(),"idiomatic-request-names":fe.boolean().optional(),"wrap-references-to-nullable-in-optional":fe.boolean().optional(),"coerce-optional-schemas-to-nullable":fe.boolean().optional(),"group-environments-by-host":fe.boolean().optional(),"remove-discriminants-from-schemas":FXn.optional(),"path-parameter-order":QXn.optional()});var LXn=fe.object({path:Exi,origin:fe.string().optional(),overrides:fe.string().optional(),audiences:fe.list(fe.string()).optional(),settings:UXn.optional()});var VXn=fe.object({target:fe.string().optional(),root:fe.string(),overrides:fe.string().optional(),"local-generation":fe.boolean().optional(),"from-openapi":fe.boolean().optional(),dependencies:fe.list(fe.string()).optional()});var WXn=fe.object({proto:VXn});var GLo=fe.undiscriminatedUnion([Exi,LXn,WXn]);var xLo=fe.list(GLo);var GXn=fe.undiscriminatedUnion([Exi,LXn,xLo,WXn]);var HLo=fe.object({namespaces:fe.record(fe.string(),GXn)});var xXn=fe.object({scheme:fe.string()}).extend(hM);var KLo=fe.undiscriminatedUnion([fe.string(),xXn]);var JLo=fe.object({any:fe.list(KLo)}).extend(hM);var $Lo=fe.object({});var YLo=fe.object({"endpoint-security":$Lo}).extend(hM);var HXn=fe.undiscriminatedUnion([fe.string(),xXn,JLo,YLo]);var XLo=fe.enum_(["form","json"]);var ZLo=fe.object({endpoints:fe.list(fe.string()).optional()});var A3a=fe.object({"max-depth":fe.number().optional()});var kLo=fe.object({request:A3a.optional(),response:A3a.optional()});var eVo=fe.object({except:fe.list(fe.string()).optional()});var tVo=fe.undiscriminatedUnion([fe.boolean(),eVo]);var rVo=fe.enum_(["int32","int64","uint32","uint64"]);var KXn=fe.object({"respect-nullable-schemas":fe.boolean().optional(),"title-as-schema-name":fe.boolean().optional(),"optional-additional-properties":fe.boolean().optional(),"coerce-enums-to-literals":fe.boolean().optional(),"idiomatic-request-names":fe.boolean().optional(),"wrap-references-to-nullable-in-optional":fe.boolean().optional(),"coerce-optional-schemas-to-nullable":fe.boolean().optional(),"group-environments-by-host":fe.boolean().optional(),"remove-discriminants-from-schemas":FXn.optional(),"path-parameter-order":QXn.optional()});var Sxi=fe.object({"only-include-referenced-schemas":fe.boolean().optional(),"inline-path-parameters":fe.boolean().optional(),"prefer-undiscriminated-unions-with-literals":fe.boolean().optional(),"object-query-parameters":fe.boolean().optional(),"respect-readonly-schemas":fe.boolean().optional(),"respect-forward-compatible-enums":fe.boolean().optional(),"use-bytes-for-binary-response":fe.boolean().optional(),"default-form-parameter-encoding":XLo.optional(),filter:ZLo.optional(),"example-generation":kLo.optional(),"additional-properties-defaults-to":fe.boolean().optional(),"type-dates-as-strings":fe.boolean().optional(),"preserve-single-schema-oneof":fe.boolean().optional(),"inline-all-of-schemas":fe.boolean().optional(),"resolve-aliases":tVo.optional(),"group-multi-api-environments":fe.boolean().optional(),"default-integer-format":rVo.optional()}).extend(KXn);var iVo=fe.object({openapi:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),overlays:fe.string().optional(),namespace:fe.string().optional(),settings:Sxi.optional()});var JXn=fe.object({"message-naming":NXn.optional()}).extend(KXn);var nVo=fe.object({asyncapi:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),namespace:fe.string().optional(),settings:JXn.optional()});var aVo=fe.object({proto:VXn});var oVo=fe.object({openrpc:fe.string(),overrides:fe.string().optional(),namespace:fe.string().optional()});var uVo=fe.undiscriminatedUnion([iVo,nVo,aVo,oVo]);var sVo=fe.object({conjure:fe.string()});var $Xn=fe.undiscriminatedUnion([fe.list(uVo),sVo]);var YXn=fe.object({}).extend(Sxi).extend(JXn);var cVo=fe.object({type:fe.string()});var lVo=fe.object({proto:cVo.optional()});var fVo=fe.object({minLength:fe.number().optional(),maxLength:fe.number().optional(),pattern:fe.string().optional(),format:fe.string().optional()});var dVo=fe.object({min:fe.number().optional(),max:fe.number().optional(),exclusiveMin:fe.boolean().optional(),exclusiveMax:fe.boolean().optional(),multipleOf:fe.number().optional()});var pVo=fe.undiscriminatedUnion([fVo,dVo]);var XXn=fe.enum_(["in-development","pre-release","deprecated","generally-available"]);var _Vo=fe.object({status:XXn,message:fe.string().optional()});var hVo=fe.undiscriminatedUnion([XXn,_Vo]);var yVo=fe.object({availability:hVo.optional()});var bVo=fe.object({default:fe.unknown().optional(),encoding:lVo.optional(),validation:pVo.optional()}).extend(hM).extend(yVo);var Mxi=fe.object({audiences:fe.list(fe.string()).optional()});var vVo=fe.object({type:fe.string()}).extend(bVo).extend(jxi).extend(Mxi);var gVo=fe.object({env:fe.string().optional()}).extend(vVo);var OVo=fe.undiscriminatedUnion([fe.string(),gVo]);var mVo=OVo;var AVo=fe.object({headers:fe.record(fe.string(),mVo).optional()});var PVo=fe.object({url:fe.string()}).extend(Mxi).extend(hM);var jVo=fe.object({urls:fe.record(fe.string(),fe.string())}).extend(Mxi).extend(hM);var wVo=fe.undiscriminatedUnion([fe.string(),PVo,jVo]);var EVo=fe.object({"default-url":fe.string().optional(),"default-environment":fe.string().optional(),environments:fe.record(fe.string(),wVo).optional()});var SVo=fe.object({auth:HXn.optional(),"auth-schemes":fe.record(fe.string(),wxi).optional(),specs:$Xn,settings:YXn.optional()}).extend(AVo).extend(EVo);var MVo=fe.undiscriminatedUnion([GXn,HLo,SVo]);var DVo=fe.object({username:fe.string(),email:fe.string(),token:fe.string()});var BVo=fe.object({github:DVo.optional()});var IVo=fe.object({name:fe.string(),email:fe.string()});var Dxi=fe.object({description:fe.string().optional(),authors:fe.list(IVo).optional()});var CVo=fe.object({method:fe.string(),path:fe.string(),stream:fe.boolean().optional()});var P3a=fe.undiscriminatedUnion([fe.string(),CVo]);var qVo=fe.enum_(["java","python","go","ruby","csharp","typescript","php","rust","swift"]);var TVo=fe.object({title:fe.string(),language:qVo,content:fe.string()});var RVo=fe.enum_(["minimal","comprehensive"]);var zVo=fe.object({bannerLink:fe.string().optional(),introduction:fe.string().optional(),apiReferenceLink:fe.string().optional(),apiName:fe.string().optional(),disabledSections:fe.list(fe.string()).optional(),defaultEndpoint:P3a.optional(),features:fe.record(fe.string(),fe.list(P3a)).optional(),customSections:fe.list(TVo).optional(),exampleStyle:RVo.optional()});var NVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional()});var FVo=fe.object({keyId:fe.string(),password:fe.string(),secretKey:fe.string()});var QVo=fe.object({url:fe.string().optional(),coordinate:fe.string(),username:fe.string().optional(),password:fe.string().optional(),signature:FVo.optional()});var UVo=fe.object({keywords:fe.list(fe.string()).optional(),"documentation-link":fe.string().optional(),"homepage-link":fe.string().optional()}).extend(Dxi);var LVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional(),username:fe.string().optional(),password:fe.string().optional(),metadata:UVo.optional()});var VVo=fe.object({"api-key":fe.string(),"workspace-id":fe.string(),"collection-id":fe.string().optional()});var WVo=fe.object({path:fe.string()});var GVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),"api-key":fe.string().optional()});var xVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),"api-key":fe.string().optional()});var HVo=fe.object({url:fe.string().optional(),"package-name":fe.string(),token:fe.string().optional()});var KVo=fe.union("location",{npm:NVo,maven:QVo,pypi:LVo,postman:VVo,"local-file-system":WVo,nuget:GVo,rubygems:xVo,crates:HVo}).transform({transform:e=>e,untransform:e=>e});var JVo=fe.enum_(["pull-request","push"]);var $Vo=fe.enum_(["MIT","Apache-2.0"]);var YVo=fe.object({custom:fe.string()});var q0e=fe.undiscriminatedUnion([$Vo,YVo]);var XVo=fe.object({uri:fe.string(),token:fe.string(),mode:JVo.optional(),branch:fe.string().optional(),license:q0e.optional()});var ZVo=fe.enum_(["commit","release"]);var kVo=fe.object({repository:fe.string(),license:q0e.optional(),mode:ZVo.optional()});var j3a=fe.object({name:fe.string()});var Bxi=fe.object({teams:fe.list(j3a).optional(),users:fe.list(j3a).optional()});var e3o=fe.object({repository:fe.string(),branch:fe.string().optional(),license:q0e.optional(),mode:fe.stringLiteral("pull-request"),reviewers:Bxi.optional()});var t3o=fe.object({repository:fe.string(),license:q0e.optional(),mode:fe.stringLiteral("push"),branch:fe.string().optional()});var r3o=fe.undiscriminatedUnion([XVo,kVo,e3o,t3o]);var w3a=fe.object({"package-description":fe.string().optional(),email:fe.string().optional(),"reference-url":fe.string().optional(),author:fe.string().optional(),license:q0e.optional()});var i3o=fe.object({path:fe.string()});var n3o=fe.object({auth:HXn.optional(),"auth-schemes":fe.record(fe.string(),wxi).optional(),settings:YXn.optional(),specs:$Xn.optional()});var a3o=fe.object({name:fe.string(),version:fe.string(),output:KVo.optional(),github:r3o.optional(),config:fe.unknown().optional(),metadata:w3a.optional(),keywords:fe.list(fe.string()).optional(),snippets:i3o.optional(),"ir-version":fe.string().optional(),"smart-casing":fe.boolean().optional(),api:n3o.optional(),"disable-examples":fe.boolean().optional(),"publish-metadata":w3a.optional(),autorelease:fe.boolean().optional()});var o3o=fe.object({audiences:fe.list(fe.string()).optional(),generators:fe.list(a3o),metadata:Dxi.optional(),reviewers:Bxi.optional()});var u3o=fe.object({path:fe.string(),origin:fe.string().optional(),overrides:fe.string().optional(),"disable-examples":fe.boolean().optional(),settings:Sxi});var s3o=fe.undiscriminatedUnion([u3o,fe.string()]);var EWp=fe.object({"auth-schemes":fe.record(fe.string(),wxi).optional(),api:MVo.optional(),whitelabel:BVo.optional(),metadata:Dxi.optional(),readme:zVo.optional(),"default-group":fe.string().optional(),aliases:fe.record(fe.string(),fe.list(fe.string())).optional(),groups:fe.record(fe.string(),o3o).optional(),reviewers:Bxi.optional(),ai:ELo.optional(),autorelease:fe.boolean().optional(),openapi:s3o.optional(),"openapi-overrides":fe.string().optional(),"spec-origin":fe.string().optional(),"async-api":fe.string().optional(),"api-settings":UXn.optional()});var Pyc={};Yt(Pyc,{CratesOutputLocationSchema:()=>HVo,GeneratorApiSettingsSchema:()=>n3o,GeneratorGroupSchema:()=>o3o,GeneratorInvocationSchema:()=>a3o,GeneratorOutputSchema:()=>KVo,GeneratorPublishMetadataSchema:()=>w3a,GeneratorSnippetsSchema:()=>i3o,GithubCommitAndReleaseMode:()=>ZVo,GithubCommitAndReleaseSchema:()=>kVo,GithubConfigurationSchema:()=>r3o,GithubPullRequestSchema:()=>e3o,GithubPushSchema:()=>t3o,GithubSelfhostedMode:()=>JVo,GithubSelfhostedSchema:()=>XVo,LocalFileSystemOutputLocationSchema:()=>WVo,MavenOutputLocationSchema:()=>QVo,MavenOutputSignatureSchema:()=>FVo,NpmOutputLocationSchema:()=>NVo,NugetOutputLocationSchema:()=>GVo,PostmanOutputLocationSchema:()=>VVo,PypiOutputLocationSchema:()=>LVo,PypiOutputMetadataSchema:()=>UVo,RubyGemsOutputLocationSchema:()=>xVo});var jyc={};Yt(jyc,{GithubLicenseCustomSchema:()=>YVo,GithubLicenseSchema:()=>q0e,GithubLicenseType:()=>$Vo});var wyc={};Yt(wyc,{ReviewerSchema:()=>j3a,ReviewersSchema:()=>Bxi});var Ryc={};Yt(Ryc,{AnyAuthItem:()=>KLo,AnyAuthSchemesSchema:()=>JLo,ApiAuthSchema:()=>HXn,AuthSchemeDeclarationSchema:()=>wxi,AuthSchemeReferenceSchema:()=>xXn,AuthScope:()=>SLo,AuthVariable:()=>Gdn,AvailabilitySchema:()=>_Vo,AvailabilityStatusSchema:()=>XXn,AvailabilityUnionSchema:()=>hVo,BaseTypeReferenceSchema:()=>bVo,BasicAuthSchemeSchema:()=>zLo,BearerAuthSchemeSchema:()=>VLo,EncodingSchema:()=>lVo,EndpointSecuritySchema:()=>YLo,EndpointSecuritySchemaDetails:()=>$Lo,EnvironmentSchema:()=>wVo,HeaderAuthSchemeSchema:()=>RLo,HttpHeaderSchema:()=>mVo,InferredAuthenticatedRequestHeader:()=>FLo,InferredBearerAuthSchema:()=>LLo,InferredGetTokenEndpointSchema:()=>ULo,InferredGetTokenEndpointSchemaObject:()=>QLo,MultipleBaseUrlsEnvironmentSchema:()=>jVo,NumberValidationSchema:()=>dVo,OAuthAccessTokenRequestPropertiesSchema:()=>MLo,OAuthAccessTokenResponsePropertiesSchema:()=>DLo,OAuthGetTokenEndpointSchema:()=>BLo,OAuthRefreshTokenEndpointSchema:()=>qLo,OAuthRefreshTokenRequestPropertiesSchema:()=>ILo,OAuthRefreshTokenResponsePropertiesSchema:()=>CLo,OAuthSchemeSchema:()=>TLo,ProtobufTypeSchema:()=>cVo,SingleBaseUrlEnvironmentSchema:()=>PVo,StringValidationSchema:()=>fVo,TokenBearerAuthSchema:()=>NLo,TypeReferenceDeclarationWithEnvOverride:()=>OVo,TypeReferenceDeclarationWithEnvOverrideSchema:()=>gVo,TypeReferenceDeclarationWithName:()=>vVo,ValidationSchema:()=>pVo,WithAudiences:()=>Mxi,WithAvailability:()=>yVo,WithDocsSchema:()=>hM,WithEnvironmentVariable:()=>zXn,WithEnvironmentsSchema:()=>EVo,WithHeadersSchema:()=>AVo,WithName:()=>jxi,auth:()=>Eyc,availability:()=>Syc,commons:()=>Myc,encoding:()=>Dyc,environments:()=>Byc,file:()=>Iyc,service:()=>Cyc,types:()=>qyc,validation:()=>Tyc});var Eyc={};Yt(Eyc,{AnyAuthItem:()=>KLo,AnyAuthSchemesSchema:()=>JLo,ApiAuthSchema:()=>HXn,AuthSchemeDeclarationSchema:()=>wxi,AuthSchemeReferenceSchema:()=>xXn,AuthScope:()=>SLo,AuthVariable:()=>Gdn,BasicAuthSchemeSchema:()=>zLo,BearerAuthSchemeSchema:()=>VLo,EndpointSecuritySchema:()=>YLo,EndpointSecuritySchemaDetails:()=>$Lo,HeaderAuthSchemeSchema:()=>RLo,InferredAuthenticatedRequestHeader:()=>FLo,InferredBearerAuthSchema:()=>LLo,InferredGetTokenEndpointSchema:()=>ULo,InferredGetTokenEndpointSchemaObject:()=>QLo,OAuthAccessTokenRequestPropertiesSchema:()=>MLo,OAuthAccessTokenResponsePropertiesSchema:()=>DLo,OAuthGetTokenEndpointSchema:()=>BLo,OAuthRefreshTokenEndpointSchema:()=>qLo,OAuthRefreshTokenRequestPropertiesSchema:()=>ILo,OAuthRefreshTokenResponsePropertiesSchema:()=>CLo,OAuthSchemeSchema:()=>TLo,TokenBearerAuthSchema:()=>NLo,WithEnvironmentVariable:()=>zXn});var Syc={};Yt(Syc,{AvailabilitySchema:()=>_Vo,AvailabilityStatusSchema:()=>XXn,AvailabilityUnionSchema:()=>hVo});var Myc={};Yt(Myc,{WithAudiences:()=>Mxi,WithAvailability:()=>yVo,WithDocsSchema:()=>hM,WithName:()=>jxi});var Dyc={};Yt(Dyc,{EncodingSchema:()=>lVo,ProtobufTypeSchema:()=>cVo});var Byc={};Yt(Byc,{EnvironmentSchema:()=>wVo,MultipleBaseUrlsEnvironmentSchema:()=>jVo,SingleBaseUrlEnvironmentSchema:()=>PVo,WithEnvironmentsSchema:()=>EVo});var Iyc={};Yt(Iyc,{WithHeadersSchema:()=>AVo});var Cyc={};Yt(Cyc,{HttpHeaderSchema:()=>mVo,TypeReferenceDeclarationWithEnvOverride:()=>OVo,TypeReferenceDeclarationWithEnvOverrideSchema:()=>gVo});var qyc={};Yt(qyc,{BaseTypeReferenceSchema:()=>bVo,TypeReferenceDeclarationWithName:()=>vVo});var Tyc={};Yt(Tyc,{NumberValidationSchema:()=>dVo,StringValidationSchema:()=>fVo,ValidationSchema:()=>pVo});function SWp(e){return e?.specs!=null}function MWp(e){return e?.asyncapi!=null}function DWp(e){return e?.conjure!=null}function BWp(e){return e?.namespaces!=null}function IWp(e){return e?.openapi!=null}function CWp(e){return e?.openrpc!=null}function qWp(e){return e?.proto!=null}var TWp=ue(require("path"),1);async function c3o({schema:e,value:t,context:r,filepathBeingParsed:i}){let n=await e.safeParseAsync(t);if(n.success)return n.data;let a=n.error.errors.map(c=>{let d=c.path.length>0?`${c.message} at "${WbS(c.path)}"`:c.message;return tVt({content:d,prefix:" - "})}),o=[`Failed to parse file: ${TWp.default.relative(process.cwd(),i)}`,...a].join(`
|
|
929
929
|
`);return r.failAndThrow(o)}function WbS(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var RWp=ue(require("path"),1),GbS={dependencies:{}};async function zWp({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return GbS;let i={};for(let[n,a]of Object.entries(t.dependencies))if(HbS(a)){let o=Sr.of(RWp.default.join(e,a));await Ai(o)?i[n]={type:"local",absoluteFilepath:o,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${o}`)}else{let c=n.substring(1).split("/"),d=c[0],s=c[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===Qw.Failure&&r.failAndThrow(),{dependencies:i}}var xbS=/^\.\.\/.*$/;function HbS(e){return xbS.test(e)}var V5p=require("fs/promises");function ZWp(e){return typeof e>"u"||e===null}function KbS(e){return typeof e=="object"&&e!==null}function JbS(e){return Array.isArray(e)?e:ZWp(e)?[]:[e]}function $bS(e,t){var r,i,n,a;if(t)for(a=Object.keys(t),r=0,i=a.length;r<i;r+=1)n=a[r],e[n]=t[n];return e}function YbS(e,t){var r="",i;for(i=0;i<t;i+=1)r+=e;return r}function XbS(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var ZbS=ZWp,kbS=KbS,evS=JbS,tvS=YbS,rvS=XbS,ivS=$bS,cR={isNothing:ZbS,isObject:kbS,toArray:evS,repeat:tvS,isNegativeZero:rvS,extend:ivS};function kWp(e,t){var r="",i=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+=`
|
|
930
930
|
|
|
931
931
|
`+e.mark.snippet),i+" "+r):i}function S3a(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=kWp(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}S3a.prototype=Object.create(Error.prototype);S3a.prototype.constructor=S3a;S3a.prototype.toString=function(t){return this.name+": "+kWp(this,t)};var BG=S3a;function Nyc(e,t,r,i,n){var a="",o="",c=Math.floor(n/2)-1;return i-t>c&&(a=" ... ",t=i-c+a.length),r-i>c&&(o=" ...",r=i+c-o.length),{str:a+e.slice(t,r).replace(/\t/g,"\u2192")+o,pos:i-t+a.length}}function Fyc(e,t){return cR.repeat(" ",t-e.length)+e}function nvS(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),typeof t.indent!="number"&&(t.indent=1),typeof t.linesBefore!="number"&&(t.linesBefore=3),typeof t.linesAfter!="number"&&(t.linesAfter=2);for(var r=/\r?\n|\r|\0/g,i=[0],n=[],a,o=-1;a=r.exec(e.buffer);)n.push(a.index),i.push(a.index+a[0].length),e.position<=a.index&&o<0&&(o=i.length-2);o<0&&(o=i.length-1);var c="",d,s,u=Math.min(e.line+t.linesAfter,n.length).toString().length,l=t.maxLength-(t.indent+u+3);for(d=1;d<=t.linesBefore&&!(o-d<0);d++)s=Nyc(e.buffer,i[o-d],n[o-d],e.position-(i[o]-i[o-d]),l),c=cR.repeat(" ",t.indent)+Fyc((e.line-d+1).toString(),u)+" | "+s.str+`
|
|
@@ -1266,7 +1266,7 @@ ${c9_.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&ORc(th
|
|
|
1266
1266
|
`+khn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?khn.default.cyan(v9_(t,this.opt.mask)):khn.default.italic(khn.default.dim("[hidden]")):this.opt.mask?v9_(t,this.opt.mask):khn.default.italic(khn.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 zXo=ue(PR(),1);var vG_=ue(tzc(),1),TXo=require("child_process"),xta=require("fs"),qXo=ue(require("path"),1),gG_=ue(require("os"),1),OG_=require("crypto"),Qzc=ue(yG_(),1);var BXo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var wGa=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var IXo=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var CXo=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function RXo(e="",t,r){let i=new Uzc(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function bG_(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function JpD(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var Uzc=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=JpD(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??gG_.default.tmpdir(),r=(0,OG_.randomUUID)(),i=bG_(this.fileOptions.prefix),n=bG_(this.fileOptions.postfix),a=`${i}${r}${n}`,o=qXo.default.resolve(t,a),c=qXo.default.resolve(t)+qXo.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,xta.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new BXo(t)}}readTemporaryFile(){try{let t=(0,xta.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,vG_.detect)(t)??"utf8";Qzc.default.encodingExists(r)||(r="utf8"),this.text=Qzc.default.decode(t,r)}}catch(t){throw new IXo(t)}}removeTemporaryFile(){try{(0,xta.unlinkSync)(this.tempFile)}catch(t){throw new CXo(t)}}launchEditor(){try{let t=(0,TXo.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new wGa(t)}}launchEditorAsync(t){try{(0,TXo.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new wGa(r)}}};var mG_=ue(Tve(),1);var EGa=class extends jR{_run(t){this.done=t,this.editorResult=new mG_.Subject;let r=aL(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?zXo.default.dim("Received"):zXo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=zXo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),RXo(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 EG_=require("stream");var jG_=ue(require("readline"),1),wG_=ue(PG_(),1),iyn=class{constructor(t){this.rl||=jG_.default.createInterface(YpD(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 YpD(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new wG_.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var SGa=class extends iyn{constructor(t={}){super(t),this.log=new EG_.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return lGa(this.rl,this.bottomBar.split(`
|
|
1267
1267
|
`).length),this}updateBottomBar(t){return lGa(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+`
|
|
1268
1268
|
`}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&&nXo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var sm=ue(Tve(),1),DG_=ue(L9a(),1);var NXo=ue(Tve(),1),SG_=ue(L9a(),1),FXo=function(e,t,r){return typeof e[t]!="function"?(0,NXo.of)(e):(0,NXo.from)((0,SG_.default)(e[t])(r).then(i=>(e[t]=i,e)))};var MG_={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},Hta=class extends iyn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,sm.from)(t):(0,sm.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,sm.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,sm.from)([t]),this.process=i.pipe((0,sm.concatMap)(this.processQuestion.bind(this)),(0,sm.publish)()),this.process.connect(),this.process.pipe((0,sm.reduce)((n,a)=>(MG_.set(n,a.name,a.answer),n),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,sm.defer)(()=>(0,sm.of)(t).pipe((0,sm.concatMap)(this.setDefaultType.bind(this)),(0,sm.concatMap)(this.filterIfRunnable.bind(this)),(0,sm.concatMap)(()=>FXo(t,"message",this.answers)),(0,sm.concatMap)(()=>FXo(t,"default",this.answers)),(0,sm.concatMap)(()=>FXo(t,"choices",this.answers)),(0,sm.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,sm.defer)(()=>(0,sm.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,sm.defer)(()=>(0,sm.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&MG_.get(this.answers,t.name)!==void 0)return sm.EMPTY;if(t.when===!1)return sm.EMPTY;if(typeof t.when!="function")return(0,sm.of)(t);let{answers:r}=this;return(0,sm.defer)(()=>(0,sm.from)((0,DG_.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,sm.filter)(i=>i!=null)))}};function BG_(e){let t=function(r,i){let n;try{n=new Hta(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",dGa),this.registerPrompt("input",Zhn),this.registerPrompt("number",pGa),this.registerPrompt("confirm",_Ga),this.registerPrompt("rawlist",hGa),this.registerPrompt("expand",yGa),this.registerPrompt("checkbox",bGa),this.registerPrompt("password",vGa),this.registerPrompt("editor",EGa)},t.restoreDefaultPrompts(),t}var Vzc=BG_();function ZpD(e,t){Vzc.registerPrompt(e,t)}function kpD(){Vzc.restoreDefaultPrompts()}var e_D={prompt:Vzc,ui:{BottomBar:SGa,Prompt:Hta},createPromptModule:BG_,registerPrompt:ZpD,restoreDefaultPrompts:kpD,Separator:U$},QXo=e_D;var Kta=require("path");function CG_(){let e=t_D();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function t_D(e=process.argv[1]?(0,Kta.dirname)(process.argv[1]):process.cwd(),t=Kta.sep==="\\"){let r=t?IG_(e):e;return i=>{if(!i)return;let n=t?IG_(i):i,{dir:a,base:o,ext:c}=Kta.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function IG_(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Wzc=e=>{if("flags"in e){let t=qG_(e.flags),r=TG_(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,RG_(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,r_D(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function r_D(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 qG_=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,nyn(r)]).filter(([,t])=>t!==void 0)),TG_=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?RG_(i):void 0]}))};var nyn=e=>e===void 0?void 0:e.variant??e.enabled,RG_=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var UXo="0123456789abcdef",LXo=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,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}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 i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=UXo.charAt(this.bytes[r]>>>4),t+=UXo.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+=UXo.charAt(this.bytes[r]>>>4),t+=UXo.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 i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gzc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??i_D()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}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 LXo.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,LXo.ofInner(t)}},i_D=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),zG_,R$t=()=>n_D().toString(),n_D=()=>(zG_||(zG_=new Gzc)).generate();var a_D=["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"],NG_=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return a_D.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var V$=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",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 u_D=Array.isArray,FG_=Object.prototype,b39=FG_.hasOwnProperty,xzc=FG_.toString,QG_=u_D||function(e){return xzc.call(e)==="[object Array]"};var Jta=e=>e===void 0,MGa=e=>xzc.call(e)=="[object String]",UG_=e=>MGa(e)&&e.trim().length===0;var LG_=e=>xzc.call(e)=="[object Number]";var Hzc=e=>e instanceof Error;function s_D(e,t){try{return e instanceof t}catch{return!1}}function DGa(e){return e===null||typeof e!="object"}function ayn(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function VG_(e){return ayn(e,"ErrorEvent")}function VXo(e){return!Jta(Event)&&s_D(e,Event)}function WG_(e){return ayn(e,"Object")}function BGa(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),LG_(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),BGa(n||r,t,r,i))}var c_D=864e5,WXo=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=BGa(t.bucketSize,0,100,t._logger),this._refillRate=BGa(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=BGa(t.refillInterval,0,c_D,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var GXo=class{add(t){let r=R$t();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 l_D(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var GG_=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>GG_(`${e} ${a}`,t,r)}},f_D=e=>e();function xG_(e,t=f_D){return GG_(e,t,l_D())}var Yta="Mobile",HXo="iOS",$ta="Android",HG_="Tablet",D39=$ta+" "+HG_;var d_D="Apple",B39=d_D+" Watch",KG_="Safari",KXo="BlackBerry",JG_="Samsung",p_D=JG_+"Browser",__D=JG_+" Internet",JXo="Chrome",h_D=JXo+" OS",y_D=JXo+" "+HXo,$G_="Internet Explorer",b_D=$G_+" "+Yta,Jzc="Opera",I39=Jzc+" Mini",YG_="Edge",v_D="Microsoft "+YG_,$zc="Firefox",g_D=$zc+" "+HXo,Yzc="Nintendo",Xzc="PlayStation",xXo="Xbox",O_D=$ta+" "+Yta,m_D=Yta+" "+KG_,IGa="Windows",A_D=IGa+" Phone";var XG_="Generic",C39=XG_+" "+Yta.toLowerCase(),q39=XG_+" "+HG_.toLowerCase(),P_D="Konqueror",$G="(\\d+(\\.\\d+)?)",Kzc=new RegExp("Version/"+$G),T39=new RegExp(xXo,"i"),R39=new RegExp(Xzc+" \\w+","i"),z39=new RegExp(Yzc+" \\w+","i"),j_D=new RegExp(KXo+"|PlayBook|BB10","i"),w_D={"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 N39={[b_D]:[new RegExp("rv:"+$G)],[v_D]:[new RegExp(YG_+"?\\/"+$G)],[JXo]:[new RegExp("("+JXo+"|CrMo)\\/"+$G)],[y_D]:[new RegExp("CriOS\\/"+$G)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$G)],[KG_]:[Kzc],[m_D]:[Kzc],[Jzc]:[new RegExp("("+Jzc+"|OPR)\\/"+$G)],[$zc]:[new RegExp($zc+"\\/"+$G)],[g_D]:[new RegExp("FxiOS\\/"+$G)],[P_D]:[new RegExp("Konqueror[:/]?"+$G,"i")],[KXo]:[new RegExp(KXo+" "+$G),Kzc],[O_D]:[new RegExp("android\\s"+$G,"i")],[__D]:[new RegExp(p_D+"\\/"+$G)],[$G_]:[new RegExp("(rv:|MSIE )"+$G)],Mozilla:[new RegExp("rv:"+$G)]};var F39=[[new RegExp(xXo+"; "+xXo+" (.*?)[);]","i"),e=>[xXo,e&&e[1]||""]],[new RegExp(Yzc,"i"),[Yzc,""]],[new RegExp(Xzc,"i"),[Xzc,""]],[j_D,[KXo,""]],[new RegExp(IGa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[A_D,""];if(new RegExp(Yta).test(t)&&!/IEMobile\b/.test(t))return[IGa+" "+Yta,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=w_D[i]||"";return/arm/i.test(t)&&(n="RT"),[IGa,n]}return[IGa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[HXo,t.join(".")]}return[HXo,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Jta(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+$ta+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$ta+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[$ta,t.join(".")]}return[$ta,""]}],[/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/,[h_D,""]],[/Linux|debian/i,["Linux",""]]];var ZG_="utf8";function kG_(e,t){if(!e||typeof e!="string"||E_D(e))throw new Error(t)}function E_D(e){return e.trim().length===0}function ex_(e){return e?.replace(/\/+$/,"")}async function tx_(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function $Xo(){return new Date().toISOString()}function oyn(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var rx_=e=>e instanceof Error;function Zzc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var YXo=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(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};function ix_(){return"CompressionStream"in globalThis}async function kzc(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Xta=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()}},CGa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function nx_(e){if(e instanceof Xta){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 eNc(e){return typeof e=="object"&&(e instanceof Xta||e instanceof CGa)}function ax_(e){return typeof e=="object"&&e instanceof Xta&&e.status===413}var qGa=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new GXo,this._events=new YXo,this._isInitialized=!1,kG_(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=ex_(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:eNc},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.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=xG_("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!ix_()||(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(V$.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(V$.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(V$.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(i,n));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,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}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`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(l=>l.json()).then(l=>Wzc(l)).catch(l=>{this._events.emit("error",l)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=nyn(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId,evaluatedAt:c.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let d=await this.getFlags(t,r,i,n,c);if(d!==void 0)return d.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"),d.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:d?.requestId}):d}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"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(V$.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(V$.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(V$.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(V$.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(V$.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=oyn(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:$Xo()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await kzc(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:$Xo(),uuid:i?.uuid?i.uuid:R$t()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await nx_(t)})}async flush(){let t=Zzc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Zzc([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(V$.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(_=>_.message),o=()=>{let h=(this.getPersistedProperty(V$.Queue)||[]).slice(n.length);this.setPersistedProperty(V$.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:$Xo()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await kzc(d,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>ax_(_)?!1:eNc(_)};try{await this.fetchWithRetry(s,l,p)}catch(_){if(ax_(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof CGa||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,ZG_)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await tx_(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new CGa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new Xta(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(V$.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!eNc(n))throw n;await nx_(n)}};return Promise.race([new Promise((n,a)=>{oyn(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),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 W$={};Yt(W$,{DOMExceptionCoercer:()=>rNc,ErrorCoercer:()=>iNc,ErrorEventCoercer:()=>nNc,ErrorPropertiesBuilder:()=>tNc,EventCoercer:()=>uNc,ObjectCoercer:()=>oNc,PrimitiveCoercer:()=>sNc,PromiseRejectionEventCoercer:()=>cNc,ReduceableCache:()=>lNc,StringCoercer:()=>aNc,chromeStackLineParser:()=>sx_,createStackParser:()=>U_D,geckoStackLineParser:()=>lx_,nodeStackLineParser:()=>_x_,opera10StackLineParser:()=>fx_,opera11StackLineParser:()=>dx_,reverseAndStripFrames:()=>bx_,winjsStackLineParser:()=>cx_});var XXo,ox_,ZXo;function ux_(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return ZXo&&r.length===ox_||(ox_=r.length,ZXo=r.reduce((i,n)=>{XXo||(XXo={});let a=XXo[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,XXo[n]=[s,u];break}}}return i},{})),ZXo}var S_D=4,tNc=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&QG_(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 i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:ux_(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=S_D){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var uL="?";function z$t(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?uL:r,in_app:!0};return Jta(i)||(a.lineno=i),Jta(n)||(a.colno=n),a}var kXo=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:uL,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var M_D=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,D_D=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,B_D=/\((\S*)(?::(\d+))(?::(\d+))\)/,sx_=(e,t)=>{let r=M_D.exec(e);if(r){let[,n,a,o]=r;return z$t(t,n,uL,+a,+o)}let i=D_D.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=B_D.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=kXo(i[1]||uL,i[2]);return z$t(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var I_D=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,cx_=(e,t)=>{let r=I_D.exec(e);return r?z$t(t,r[2],r[1]||uL,+r[3],r[4]?+r[4]:void 0):void 0};var C_D=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,q_D=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,lx_=(e,t)=>{let r=C_D.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=q_D.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||uL;return[a,n]=kXo(a,n),z$t(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var T_D=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,fx_=(e,t)=>{let r=T_D.exec(e);return r?z$t(t,r[2],r[3]||uL,+r[1]):void 0},R_D=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,dx_=(e,t)=>{let r=R_D.exec(e);return r?z$t(t,r[5],r[3]||r[4]||uL,+r[1],+r[2]):void 0};var z_D=/^\s*[-]{4,}$/,N_D=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,_x_=(e,t)=>{let r=e.match(N_D);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let l=i.indexOf(".Module");l>0&&(a=a.slice(l+1),i=i.slice(0,l))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||uL,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:px_(r[3]),colno:px_(r[4]),in_app:F_D(d||"",s),platform:t}}if(e.match(z_D))return{filename:e,platform:t}};function F_D(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 px_(e){return parseInt(e||"",10)||void 0}var hx_=/\(error: (.*)\)/,yx_=50;function bx_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,yx_).map(r=>({...r,filename:r.filename||Q_D(t).filename,function:r.function||uL}))}function Q_D(e){return e[e.length-1]||{}}function U_D(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
1269
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=hx_.test(c)?c.replace(hx_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=yx_)break}}return bx_(n)}}var rNc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=MGa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 ayn(t,"DOMException")}isDOMError(t){return ayn(t,"DOMError")}};var iNc=class{match(t){return Hzc(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 i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var nNc=class{constructor(){}match(t){return VG_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var L_D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,aNc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(L_D);return n&&(r=n[1],i=n[2]),[r,i]}};var vx_=["fatal","error","warning","log","info","debug"];function eZo(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var oNc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{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 VXo(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=eZo(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return MGa(t)&&!UG_(t)&&vx_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(rx_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var uNc=class{match(t){return VXo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${eZo(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var sNc=class{match(t){return DGa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var cNc=class{match(t){return ayn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return DGa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(DGa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var lNc=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 mx_=require("fs"),Ax_=require("readline"),tZo=new W$.ReduceableCache(25),Px_=new W$.ReduceableCache(20),fNc=7,V_D=1e3,W_D=1e4;async function jx_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||K_D(o)||J_D(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Px_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=Y_D(a);if(o.every(d=>$_D(n,d)))continue;let c=X_D(tZo,n,{});i.push(G_D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&x_D(e,tZo),tZo.reduce(),e}function G_D(e,t,r){return new Promise(i=>{let n=(0,mx_.createReadStream)(e),a=(0,Ax_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],l=s[1];function p(){Px_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=Z_D(_,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function x_D(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;H_D(r.lineno,r,i)}}function H_D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=wx_(e);n<e;n++){let a=r[n];if(a===void 0)return void gx_(t);t.pre_context.push(a)}if(r[e]===void 0)return void gx_(t);t.context_line=r[e];let i=Ex_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function gx_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function K_D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function J_D(e){return e.lineno!==void 0&&e.lineno>W_D||e.colno!==void 0&&e.colno>V_D}function $_D(e,t){let r=tZo.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function Y_D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Ox_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+fNc:(n.push(i),i=Ox_(a)),t++}return n}function Ox_(e){return[wx_(e),Ex_(e)]}function wx_(e){return Math.max(1,e-fNc)}function Ex_(e){return e+fNc}function X_D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function Z_D(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function k_D(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function Sx_(e,t){globalThis.process?.on("uncaughtException",k_D(e,t))}function Mx_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ehD=2e3,vQi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new WXo({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||R$t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(Sx_(this.onException.bind(this),this.onFatalError.bind(this)),Mx_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(ehD),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Dx_="5.17.4";async function Bx_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var thD=6e4,rhD=1152921504606847e3,ihD=["is_not"],Zta=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},q0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N$t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},rZo=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){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=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof N$t||d instanceof q0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof N$t||p instanceof q0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new q0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new q0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new q0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new q0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new q0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new q0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new q0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new q0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new q0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N$t)throw u;if(u instanceof q0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new q0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?Rx_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):Tx_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await Ix_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await Ix_(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}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),!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 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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(thD,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof Zta&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=oyn(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}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((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Ix_(e,t,r=""){let i=await Bx_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/rhD}function Tx_(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new q0("Operator is_not_set is not supported")}else throw new q0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!ihD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return Cx_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return Cx_(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q0("Date operations cannot be performed on boolean values");let s=ahD(String(n));if(s==null&&(s=qx_(n)),s==null)throw new q0(`Invalid date: ${n}`);let u=qx_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new q0(`Unknown operator: ${a}`)}}function nhD(e,t){if(!(e in t))throw new N$t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Rx_(e,t,r,i=!1){let n=String(e.value);nhD(n,r);let a=r[n];return zx_(a,t,r,i)}function zx_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=zx_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=Rx_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=Tx_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof N$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("can't match cohort without a given cohort property value");return n==="AND"}function Cx_(e){try{return new RegExp(e),!0}catch{return!1}}function qx_(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 q0(`${e} is in an invalid date format`)}throw new q0(`The date provided ${e} must be a string, number, or date object`)}function ahD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var iZo=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var ohD=100,Nx_=3e4,uhD=5e4,nZo=class extends qGa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new iZo,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,ohD):Nx_,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 rZo({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new vQi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||uhD}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 Dx_}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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}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=Nx_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,l=nyn(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let l;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,l=y.payload)}catch(y){if(y instanceof N$t||y instanceof q0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=oyn(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(WG_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(vQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(vQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=R$t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[g,m]of Object.entries(y))b[`$feature/${g}`]=m;let v=Object.keys(y||{}).filter(g=>y?.[g]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&NG_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var Fx_=require("async_hooks"),aZo=class{constructor(){this.storage=new Fx_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var Qx_="posthog-node";function shD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[dNc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var dNc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=Qx_,this.name=Qx_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(shD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};vQi.errorPropertiesBuilder=new W$.ErrorPropertiesBuilder([new W$.EventCoercer,new W$.ErrorCoercer,new W$.ObjectCoercer,new W$.StringCoercer,new W$.PrimitiveCoercer],W$.createStackParser("node:javascript",W$.nodeStackLineParser),[CG_(),jx_]);var kta=class extends nZo{getLibraryId(){return"posthog-node"}initializeContext(){return new aZo}};var oZo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new kta(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.49.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var TGa=class{async sendEvent(){}async identify(){}async flush(){}};var era=require("fs/promises"),Wx_=require("os"),Gx_=require("path");var Ux_=ue(require("crypto")),sZo=new Uint8Array(256),uZo=sZo.length;function pNc(){return uZo>sZo.length-16&&(Ux_.default.randomFillSync(sZo),uZo=0),sZo.slice(uZo,uZo+=16)}var sL=[];for(let e=0;e<256;++e)sL.push((e+256).toString(16).slice(1));function Lx_(e,t=0){return sL[e[t+0]]+sL[e[t+1]]+sL[e[t+2]]+sL[e[t+3]]+"-"+sL[e[t+4]]+sL[e[t+5]]+"-"+sL[e[t+6]]+sL[e[t+7]]+"-"+sL[e[t+8]]+sL[e[t+9]]+"-"+sL[e[t+10]]+sL[e[t+11]]+sL[e[t+12]]+sL[e[t+13]]+sL[e[t+14]]+sL[e[t+15]]}var Vx_=ue(require("crypto")),_Nc={randomUUID:Vx_.default.randomUUID};function chD(e,t,r){if(_Nc.randomUUID&&!t&&!e)return _Nc.randomUUID();e=e||{};let i=e.random||(e.rng||pNc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return Lx_(i)}var zve=chD;var lhD="id",fhD=".fern",RGa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new kta(r),this.userId=t==null?void 0:UIc(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:"3.49.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 Z4({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=Tt(Sr.of((0,Wx_.homedir)()),He.of(fhD),He.of(lhD));await Ai(t)||(await(0,era.mkdir)((0,Gx_.dirname)(t),{recursive:!0}),await(0,era.writeFile)(t,zve())),this.persistedDistinctId=(await(0,era.readFile)(t)).toString()}return this.persistedDistinctId}};var hNc;async function tra(){return hNc==null&&(hNc=await dhD()),hNc}async function dhD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new TGa;let r=await t7o();return r!=null?new RGa({token:r,posthogApiKey:e}):await bea()!=null?new oZo({posthogApiKey:e}):new RGa({token:void 0,posthogApiKey:e})}catch{return new TGa}}function zGa(e,t){return function(){return e.apply(t,arguments)}}var{toString:phD}=Object.prototype,{getPrototypeOf:bNc}=Object,{iterator:lZo,toStringTag:Hx_}=Symbol,fZo=(e=>t=>{let r=phD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),H3t=e=>(e=e.toLowerCase(),t=>fZo(t)===e),dZo=e=>t=>typeof t===e,{isArray:ira}=Array,rra=dZo("undefined");function NGa(e){return e!==null&&!rra(e)&&e.constructor!==null&&!rra(e.constructor)&&G$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Kx_=H3t("ArrayBuffer");function _hD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Kx_(e.buffer),t}var hhD=dZo("string"),G$=dZo("function"),Jx_=dZo("number"),FGa=e=>e!==null&&typeof e=="object",yhD=e=>e===!0||e===!1,cZo=e=>{if(fZo(e)!=="object")return!1;let t=bNc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Hx_ in e)&&!(lZo in e)},bhD=e=>{if(!FGa(e)||NGa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},vhD=H3t("Date"),ghD=H3t("File"),OhD=H3t("Blob"),mhD=H3t("FileList"),AhD=e=>FGa(e)&&G$(e.pipe),PhD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||G$(e.append)&&((t=fZo(e))==="formdata"||t==="object"&&G$(e.toString)&&e.toString()==="[object FormData]"))},jhD=H3t("URLSearchParams"),[whD,EhD,ShD,MhD]=["ReadableStream","Request","Response","Headers"].map(H3t),DhD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function QGa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),ira(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(NGa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function $x_(e,t){if(NGa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var uyn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Yx_=e=>!rra(e)&&e!==uyn;function yNc(){let{caseless:e,skipUndefined:t}=Yx_(this)&&this||{},r={},i=(n,a)=>{let o=e&&$x_(r,a)||a;cZo(r[o])&&cZo(n)?r[o]=yNc(r[o],n):cZo(n)?r[o]=yNc({},n):ira(n)?r[o]=n.slice():(!t||!rra(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&QGa(arguments[n],i);return r}var BhD=(e,t,r,{allOwnKeys:i}={})=>(QGa(t,(n,a)=>{r&&G$(n)?e[a]=zGa(n,r):e[a]=n},{allOwnKeys:i}),e),IhD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ChD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},qhD=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&bNc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},ThD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},RhD=e=>{if(!e)return null;if(ira(e))return e;let t=e.length;if(!Jx_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},zhD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&bNc(Uint8Array)),NhD=(e,t)=>{let i=(e&&e[lZo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},FhD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},QhD=H3t("HTMLFormElement"),UhD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),xx_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),LhD=H3t("RegExp"),Xx_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};QGa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},VhD=e=>{Xx_(e,(t,r)=>{if(G$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(G$(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},WhD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return ira(e)?i(e):i(String(e).split(t)),r},GhD=()=>{},xhD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function HhD(e){return!!(e&&G$(e.append)&&e[Hx_]==="FormData"&&e[lZo])}var KhD=e=>{let t=new Array(10),r=(i,n)=>{if(FGa(i)){if(t.indexOf(i)>=0)return;if(NGa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=ira(i)?[]:{};return QGa(i,(o,c)=>{let d=r(o,n+1);!rra(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},JhD=H3t("AsyncFunction"),$hD=e=>e&&(FGa(e)||G$(e))&&G$(e.then)&&G$(e.catch),Zx_=((e,t)=>e?setImmediate:t?((r,i)=>(uyn.addEventListener("message",({source:n,data:a})=>{n===uyn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),uyn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",G$(uyn.postMessage)),YhD=typeof queueMicrotask<"u"?queueMicrotask.bind(uyn):typeof process<"u"&&process.nextTick||Zx_,XhD=e=>e!=null&&G$(e[lZo]),ir={isArray:ira,isArrayBuffer:Kx_,isBuffer:NGa,isFormData:PhD,isArrayBufferView:_hD,isString:hhD,isNumber:Jx_,isBoolean:yhD,isObject:FGa,isPlainObject:cZo,isEmptyObject:bhD,isReadableStream:whD,isRequest:EhD,isResponse:ShD,isHeaders:MhD,isUndefined:rra,isDate:vhD,isFile:ghD,isBlob:OhD,isRegExp:LhD,isFunction:G$,isStream:AhD,isURLSearchParams:jhD,isTypedArray:zhD,isFileList:mhD,forEach:QGa,merge:yNc,extend:BhD,trim:DhD,stripBOM:IhD,inherits:ChD,toFlatObject:qhD,kindOf:fZo,kindOfTest:H3t,endsWith:ThD,toArray:RhD,forEachEntry:NhD,matchAll:FhD,isHTMLForm:QhD,hasOwnProperty:xx_,hasOwnProp:xx_,reduceDescriptors:Xx_,freezeMethods:VhD,toObjectSet:WhD,toCamelCase:UhD,noop:GhD,toFiniteNumber:xhD,findKey:$x_,global:uyn,isContextDefined:Yx_,isSpecCompliantForm:HhD,toJSONObject:KhD,isAsyncFn:JhD,isThenable:$hD,setImmediate:Zx_,asap:YhD,isIterable:XhD};function nra(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}ir.inherits(nra,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ir.toJSONObject(this.config),code:this.code,status:this.status}}});var kx_=nra.prototype,eH_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eH_[e]={value:e}});Object.defineProperties(nra,eH_);Object.defineProperty(kx_,"isAxiosError",{value:!0});nra.from=(e,t,r,i,n,a)=>{let o=Object.create(kx_);ir.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return nra.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var za=nra;var tH_=ue(Rkn(),1),pZo=tH_.default;function vNc(e){return ir.isPlainObject(e)||ir.isArray(e)}function iH_(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function rH_(e,t,r){return e?e.concat(t).map(function(n,a){return n=iH_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function ZhD(e){return ir.isArray(e)&&!e.some(vNc)}var khD=ir.toFlatObject(ir,{},null,function(t){return/^is[A-Z]/.test(t)});function eyD(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(pZo||FormData),r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!ir.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ir.isSpecCompliantForm(t);if(!ir.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(ir.isDate(h))return h.toISOString();if(ir.isBoolean(h))return h.toString();if(!d&&ir.isBlob(h))throw new za("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(h)||ir.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(ir.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(ir.isArray(h)&&ZhD(h)||(ir.isFileList(h)||ir.endsWith(y,"[]"))&&(v=ir.toArray(h)))return y=iH_(y),v.forEach(function(m,O){!(ir.isUndefined(m)||m===null)&&t.append(o===!0?rH_([y],O,a):o===null?y:y+"[]",s(m))}),!1}return vNc(h)?!0:(t.append(rH_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(khD,{defaultVisitor:u,convertValue:s,isVisitable:vNc});function _(h,y){if(!ir.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),ir.forEach(h,function(v,g){(!(ir.isUndefined(v)||v===null)&&n.call(t,v,ir.isString(g)?g.trim():g,y,p))===!0&&_(v,y?y.concat(g):[g])}),l.pop()}}if(!ir.isObject(e))throw new TypeError("data must be an object");return _(e),t}var k7i=eyD;function nH_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aH_(e,t){this._pairs=[],e&&k7i(e,this,t)}var oH_=aH_.prototype;oH_.append=function(t,r){this._pairs.push([t,r])};oH_.toString=function(t){let r=t?function(i){return t.call(this,i,nH_)}:nH_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uH_=aH_;function tyD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function syn(e,t,r){if(!t)return e;let i=r&&r.encode||tyD;ir.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ir.isURLSearchParams(t)?t.toString():new uH_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var gNc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ir.forEach(this.handlers,function(i){i!==null&&t(i)})}},ONc=gNc;var ara={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fH_=ue(require("crypto"),1);var sH_=ue(require("url"),1),cH_=sH_.default.URLSearchParams;var mNc="abcdefghijklmnopqrstuvwxyz",lH_="0123456789",dH_={DIGIT:lH_,ALPHA:mNc,ALPHA_DIGIT:mNc+mNc.toUpperCase()+lH_},ryD=(e=16,t=dH_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fH_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pH_={isNode:!0,classes:{URLSearchParams:cH_,FormData:pZo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dH_,generateString:ryD,protocols:["http","https","file","data"]};var jNc={};Yt(jNc,{hasBrowserEnv:()=>PNc,hasStandardBrowserEnv:()=>iyD,hasStandardBrowserWebWorkerEnv:()=>nyD,navigator:()=>ANc,origin:()=>ayD});var PNc=typeof window<"u"&&typeof document<"u",ANc=typeof navigator=="object"&&navigator||void 0,iyD=PNc&&(!ANc||["ReactNative","NativeScript","NS"].indexOf(ANc.product)<0),nyD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ayD=PNc&&window.location.href||"http://localhost";var vA={...jNc,...pH_};function wNc(e,t){return k7i(e,new vA.classes.URLSearchParams,{visitor:function(r,i,n,a){return vA.isNode&&ir.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function oyD(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function uyD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function syD(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&ir.isArray(n)?n.length:o,d?(ir.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!ir.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&ir.isArray(n[o])&&(n[o]=uyD(n[o])),!c)}if(ir.isFormData(e)&&ir.isFunction(e.entries)){let r={};return ir.forEachEntry(e,(i,n)=>{t(oyD(i),n,r,0)}),r}return null}var _Zo=syD;function cyD(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ENc={transitional:ara,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ir.isObject(t);if(a&&ir.isHTMLForm(t)&&(t=new FormData(t)),ir.isFormData(t))return n?JSON.stringify(_Zo(t)):t;if(ir.isArrayBuffer(t)||ir.isBuffer(t)||ir.isStream(t)||ir.isFile(t)||ir.isBlob(t)||ir.isReadableStream(t))return t;if(ir.isArrayBufferView(t))return t.buffer;if(ir.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return wNc(t,this.formSerializer).toString();if((c=ir.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return k7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),cyD(t)):t}],transformResponse:[function(t){let r=this.transitional||ENc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ir.isResponse(t)||ir.isReadableStream(t))return t;if(t&&ir.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?za.from(c,za.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:vA.classes.FormData,Blob:vA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ir.forEach(["delete","get","head","post","put","patch"],e=>{ENc.headers[e]={}});var ora=ENc;var lyD=ir.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_H_=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1269
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=hx_.test(c)?c.replace(hx_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=yx_)break}}return bx_(n)}}var rNc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=MGa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 ayn(t,"DOMException")}isDOMError(t){return ayn(t,"DOMError")}};var iNc=class{match(t){return Hzc(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 i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var nNc=class{constructor(){}match(t){return VG_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var L_D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,aNc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(L_D);return n&&(r=n[1],i=n[2]),[r,i]}};var vx_=["fatal","error","warning","log","info","debug"];function eZo(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var oNc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{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 VXo(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=eZo(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return MGa(t)&&!UG_(t)&&vx_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(rx_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var uNc=class{match(t){return VXo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${eZo(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var sNc=class{match(t){return DGa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var cNc=class{match(t){return ayn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return DGa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(DGa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var lNc=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 mx_=require("fs"),Ax_=require("readline"),tZo=new W$.ReduceableCache(25),Px_=new W$.ReduceableCache(20),fNc=7,V_D=1e3,W_D=1e4;async function jx_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||K_D(o)||J_D(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Px_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=Y_D(a);if(o.every(d=>$_D(n,d)))continue;let c=X_D(tZo,n,{});i.push(G_D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&x_D(e,tZo),tZo.reduce(),e}function G_D(e,t,r){return new Promise(i=>{let n=(0,mx_.createReadStream)(e),a=(0,Ax_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],l=s[1];function p(){Px_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=Z_D(_,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function x_D(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;H_D(r.lineno,r,i)}}function H_D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=wx_(e);n<e;n++){let a=r[n];if(a===void 0)return void gx_(t);t.pre_context.push(a)}if(r[e]===void 0)return void gx_(t);t.context_line=r[e];let i=Ex_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function gx_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function K_D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function J_D(e){return e.lineno!==void 0&&e.lineno>W_D||e.colno!==void 0&&e.colno>V_D}function $_D(e,t){let r=tZo.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function Y_D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Ox_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+fNc:(n.push(i),i=Ox_(a)),t++}return n}function Ox_(e){return[wx_(e),Ex_(e)]}function wx_(e){return Math.max(1,e-fNc)}function Ex_(e){return e+fNc}function X_D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function Z_D(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function k_D(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function Sx_(e,t){globalThis.process?.on("uncaughtException",k_D(e,t))}function Mx_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ehD=2e3,vQi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new WXo({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||R$t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(Sx_(this.onException.bind(this),this.onFatalError.bind(this)),Mx_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(ehD),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Dx_="5.17.4";async function Bx_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var thD=6e4,rhD=1152921504606847e3,ihD=["is_not"],Zta=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},q0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N$t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},rZo=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){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=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof N$t||d instanceof q0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof N$t||p instanceof q0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new q0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new q0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new q0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new q0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new q0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new q0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new q0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new q0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new q0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N$t)throw u;if(u instanceof q0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new q0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?Rx_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):Tx_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await Ix_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await Ix_(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}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),!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 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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(thD,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Zta(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof Zta&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=oyn(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}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((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Ix_(e,t,r=""){let i=await Bx_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/rhD}function Tx_(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new q0("Operator is_not_set is not supported")}else throw new q0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!ihD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return Cx_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return Cx_(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q0("Date operations cannot be performed on boolean values");let s=ahD(String(n));if(s==null&&(s=qx_(n)),s==null)throw new q0(`Invalid date: ${n}`);let u=qx_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new q0(`Unknown operator: ${a}`)}}function nhD(e,t){if(!(e in t))throw new N$t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Rx_(e,t,r,i=!1){let n=String(e.value);nhD(n,r);let a=r[n];return zx_(a,t,r,i)}function zx_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=zx_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=Rx_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=Tx_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof N$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("can't match cohort without a given cohort property value");return n==="AND"}function Cx_(e){try{return new RegExp(e),!0}catch{return!1}}function qx_(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 q0(`${e} is in an invalid date format`)}throw new q0(`The date provided ${e} must be a string, number, or date object`)}function ahD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var iZo=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var ohD=100,Nx_=3e4,uhD=5e4,nZo=class extends qGa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new iZo,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,ohD):Nx_,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 rZo({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new vQi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||uhD}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 Dx_}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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}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=Nx_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,l=nyn(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let l;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,l=y.payload)}catch(y){if(y instanceof N$t||y instanceof q0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=oyn(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(WG_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(vQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(vQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=R$t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[g,m]of Object.entries(y))b[`$feature/${g}`]=m;let v=Object.keys(y||{}).filter(g=>y?.[g]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&NG_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var Fx_=require("async_hooks"),aZo=class{constructor(){this.storage=new Fx_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var Qx_="posthog-node";function shD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[dNc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var dNc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=Qx_,this.name=Qx_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(shD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};vQi.errorPropertiesBuilder=new W$.ErrorPropertiesBuilder([new W$.EventCoercer,new W$.ErrorCoercer,new W$.ObjectCoercer,new W$.StringCoercer,new W$.PrimitiveCoercer],W$.createStackParser("node:javascript",W$.nodeStackLineParser),[CG_(),jx_]);var kta=class extends nZo{getLibraryId(){return"posthog-node"}initializeContext(){return new aZo}};var oZo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new kta(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.49.2",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var TGa=class{async sendEvent(){}async identify(){}async flush(){}};var era=require("fs/promises"),Wx_=require("os"),Gx_=require("path");var Ux_=ue(require("crypto")),sZo=new Uint8Array(256),uZo=sZo.length;function pNc(){return uZo>sZo.length-16&&(Ux_.default.randomFillSync(sZo),uZo=0),sZo.slice(uZo,uZo+=16)}var sL=[];for(let e=0;e<256;++e)sL.push((e+256).toString(16).slice(1));function Lx_(e,t=0){return sL[e[t+0]]+sL[e[t+1]]+sL[e[t+2]]+sL[e[t+3]]+"-"+sL[e[t+4]]+sL[e[t+5]]+"-"+sL[e[t+6]]+sL[e[t+7]]+"-"+sL[e[t+8]]+sL[e[t+9]]+"-"+sL[e[t+10]]+sL[e[t+11]]+sL[e[t+12]]+sL[e[t+13]]+sL[e[t+14]]+sL[e[t+15]]}var Vx_=ue(require("crypto")),_Nc={randomUUID:Vx_.default.randomUUID};function chD(e,t,r){if(_Nc.randomUUID&&!t&&!e)return _Nc.randomUUID();e=e||{};let i=e.random||(e.rng||pNc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return Lx_(i)}var zve=chD;var lhD="id",fhD=".fern",RGa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new kta(r),this.userId=t==null?void 0:UIc(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:"3.49.2",...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 Z4({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=Tt(Sr.of((0,Wx_.homedir)()),He.of(fhD),He.of(lhD));await Ai(t)||(await(0,era.mkdir)((0,Gx_.dirname)(t),{recursive:!0}),await(0,era.writeFile)(t,zve())),this.persistedDistinctId=(await(0,era.readFile)(t)).toString()}return this.persistedDistinctId}};var hNc;async function tra(){return hNc==null&&(hNc=await dhD()),hNc}async function dhD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new TGa;let r=await t7o();return r!=null?new RGa({token:r,posthogApiKey:e}):await bea()!=null?new oZo({posthogApiKey:e}):new RGa({token:void 0,posthogApiKey:e})}catch{return new TGa}}function zGa(e,t){return function(){return e.apply(t,arguments)}}var{toString:phD}=Object.prototype,{getPrototypeOf:bNc}=Object,{iterator:lZo,toStringTag:Hx_}=Symbol,fZo=(e=>t=>{let r=phD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),H3t=e=>(e=e.toLowerCase(),t=>fZo(t)===e),dZo=e=>t=>typeof t===e,{isArray:ira}=Array,rra=dZo("undefined");function NGa(e){return e!==null&&!rra(e)&&e.constructor!==null&&!rra(e.constructor)&&G$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Kx_=H3t("ArrayBuffer");function _hD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Kx_(e.buffer),t}var hhD=dZo("string"),G$=dZo("function"),Jx_=dZo("number"),FGa=e=>e!==null&&typeof e=="object",yhD=e=>e===!0||e===!1,cZo=e=>{if(fZo(e)!=="object")return!1;let t=bNc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Hx_ in e)&&!(lZo in e)},bhD=e=>{if(!FGa(e)||NGa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},vhD=H3t("Date"),ghD=H3t("File"),OhD=H3t("Blob"),mhD=H3t("FileList"),AhD=e=>FGa(e)&&G$(e.pipe),PhD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||G$(e.append)&&((t=fZo(e))==="formdata"||t==="object"&&G$(e.toString)&&e.toString()==="[object FormData]"))},jhD=H3t("URLSearchParams"),[whD,EhD,ShD,MhD]=["ReadableStream","Request","Response","Headers"].map(H3t),DhD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function QGa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),ira(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(NGa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function $x_(e,t){if(NGa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var uyn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Yx_=e=>!rra(e)&&e!==uyn;function yNc(){let{caseless:e,skipUndefined:t}=Yx_(this)&&this||{},r={},i=(n,a)=>{let o=e&&$x_(r,a)||a;cZo(r[o])&&cZo(n)?r[o]=yNc(r[o],n):cZo(n)?r[o]=yNc({},n):ira(n)?r[o]=n.slice():(!t||!rra(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&QGa(arguments[n],i);return r}var BhD=(e,t,r,{allOwnKeys:i}={})=>(QGa(t,(n,a)=>{r&&G$(n)?e[a]=zGa(n,r):e[a]=n},{allOwnKeys:i}),e),IhD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ChD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},qhD=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&bNc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},ThD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},RhD=e=>{if(!e)return null;if(ira(e))return e;let t=e.length;if(!Jx_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},zhD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&bNc(Uint8Array)),NhD=(e,t)=>{let i=(e&&e[lZo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},FhD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},QhD=H3t("HTMLFormElement"),UhD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),xx_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),LhD=H3t("RegExp"),Xx_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};QGa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},VhD=e=>{Xx_(e,(t,r)=>{if(G$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(G$(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},WhD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return ira(e)?i(e):i(String(e).split(t)),r},GhD=()=>{},xhD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function HhD(e){return!!(e&&G$(e.append)&&e[Hx_]==="FormData"&&e[lZo])}var KhD=e=>{let t=new Array(10),r=(i,n)=>{if(FGa(i)){if(t.indexOf(i)>=0)return;if(NGa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=ira(i)?[]:{};return QGa(i,(o,c)=>{let d=r(o,n+1);!rra(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},JhD=H3t("AsyncFunction"),$hD=e=>e&&(FGa(e)||G$(e))&&G$(e.then)&&G$(e.catch),Zx_=((e,t)=>e?setImmediate:t?((r,i)=>(uyn.addEventListener("message",({source:n,data:a})=>{n===uyn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),uyn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",G$(uyn.postMessage)),YhD=typeof queueMicrotask<"u"?queueMicrotask.bind(uyn):typeof process<"u"&&process.nextTick||Zx_,XhD=e=>e!=null&&G$(e[lZo]),ir={isArray:ira,isArrayBuffer:Kx_,isBuffer:NGa,isFormData:PhD,isArrayBufferView:_hD,isString:hhD,isNumber:Jx_,isBoolean:yhD,isObject:FGa,isPlainObject:cZo,isEmptyObject:bhD,isReadableStream:whD,isRequest:EhD,isResponse:ShD,isHeaders:MhD,isUndefined:rra,isDate:vhD,isFile:ghD,isBlob:OhD,isRegExp:LhD,isFunction:G$,isStream:AhD,isURLSearchParams:jhD,isTypedArray:zhD,isFileList:mhD,forEach:QGa,merge:yNc,extend:BhD,trim:DhD,stripBOM:IhD,inherits:ChD,toFlatObject:qhD,kindOf:fZo,kindOfTest:H3t,endsWith:ThD,toArray:RhD,forEachEntry:NhD,matchAll:FhD,isHTMLForm:QhD,hasOwnProperty:xx_,hasOwnProp:xx_,reduceDescriptors:Xx_,freezeMethods:VhD,toObjectSet:WhD,toCamelCase:UhD,noop:GhD,toFiniteNumber:xhD,findKey:$x_,global:uyn,isContextDefined:Yx_,isSpecCompliantForm:HhD,toJSONObject:KhD,isAsyncFn:JhD,isThenable:$hD,setImmediate:Zx_,asap:YhD,isIterable:XhD};function nra(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}ir.inherits(nra,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ir.toJSONObject(this.config),code:this.code,status:this.status}}});var kx_=nra.prototype,eH_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eH_[e]={value:e}});Object.defineProperties(nra,eH_);Object.defineProperty(kx_,"isAxiosError",{value:!0});nra.from=(e,t,r,i,n,a)=>{let o=Object.create(kx_);ir.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return nra.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var za=nra;var tH_=ue(Rkn(),1),pZo=tH_.default;function vNc(e){return ir.isPlainObject(e)||ir.isArray(e)}function iH_(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function rH_(e,t,r){return e?e.concat(t).map(function(n,a){return n=iH_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function ZhD(e){return ir.isArray(e)&&!e.some(vNc)}var khD=ir.toFlatObject(ir,{},null,function(t){return/^is[A-Z]/.test(t)});function eyD(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(pZo||FormData),r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!ir.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ir.isSpecCompliantForm(t);if(!ir.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(ir.isDate(h))return h.toISOString();if(ir.isBoolean(h))return h.toString();if(!d&&ir.isBlob(h))throw new za("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(h)||ir.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(ir.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(ir.isArray(h)&&ZhD(h)||(ir.isFileList(h)||ir.endsWith(y,"[]"))&&(v=ir.toArray(h)))return y=iH_(y),v.forEach(function(m,O){!(ir.isUndefined(m)||m===null)&&t.append(o===!0?rH_([y],O,a):o===null?y:y+"[]",s(m))}),!1}return vNc(h)?!0:(t.append(rH_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(khD,{defaultVisitor:u,convertValue:s,isVisitable:vNc});function _(h,y){if(!ir.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),ir.forEach(h,function(v,g){(!(ir.isUndefined(v)||v===null)&&n.call(t,v,ir.isString(g)?g.trim():g,y,p))===!0&&_(v,y?y.concat(g):[g])}),l.pop()}}if(!ir.isObject(e))throw new TypeError("data must be an object");return _(e),t}var k7i=eyD;function nH_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aH_(e,t){this._pairs=[],e&&k7i(e,this,t)}var oH_=aH_.prototype;oH_.append=function(t,r){this._pairs.push([t,r])};oH_.toString=function(t){let r=t?function(i){return t.call(this,i,nH_)}:nH_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uH_=aH_;function tyD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function syn(e,t,r){if(!t)return e;let i=r&&r.encode||tyD;ir.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ir.isURLSearchParams(t)?t.toString():new uH_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var gNc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ir.forEach(this.handlers,function(i){i!==null&&t(i)})}},ONc=gNc;var ara={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fH_=ue(require("crypto"),1);var sH_=ue(require("url"),1),cH_=sH_.default.URLSearchParams;var mNc="abcdefghijklmnopqrstuvwxyz",lH_="0123456789",dH_={DIGIT:lH_,ALPHA:mNc,ALPHA_DIGIT:mNc+mNc.toUpperCase()+lH_},ryD=(e=16,t=dH_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fH_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pH_={isNode:!0,classes:{URLSearchParams:cH_,FormData:pZo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dH_,generateString:ryD,protocols:["http","https","file","data"]};var jNc={};Yt(jNc,{hasBrowserEnv:()=>PNc,hasStandardBrowserEnv:()=>iyD,hasStandardBrowserWebWorkerEnv:()=>nyD,navigator:()=>ANc,origin:()=>ayD});var PNc=typeof window<"u"&&typeof document<"u",ANc=typeof navigator=="object"&&navigator||void 0,iyD=PNc&&(!ANc||["ReactNative","NativeScript","NS"].indexOf(ANc.product)<0),nyD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ayD=PNc&&window.location.href||"http://localhost";var vA={...jNc,...pH_};function wNc(e,t){return k7i(e,new vA.classes.URLSearchParams,{visitor:function(r,i,n,a){return vA.isNode&&ir.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function oyD(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function uyD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function syD(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&ir.isArray(n)?n.length:o,d?(ir.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!ir.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&ir.isArray(n[o])&&(n[o]=uyD(n[o])),!c)}if(ir.isFormData(e)&&ir.isFunction(e.entries)){let r={};return ir.forEachEntry(e,(i,n)=>{t(oyD(i),n,r,0)}),r}return null}var _Zo=syD;function cyD(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ENc={transitional:ara,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ir.isObject(t);if(a&&ir.isHTMLForm(t)&&(t=new FormData(t)),ir.isFormData(t))return n?JSON.stringify(_Zo(t)):t;if(ir.isArrayBuffer(t)||ir.isBuffer(t)||ir.isStream(t)||ir.isFile(t)||ir.isBlob(t)||ir.isReadableStream(t))return t;if(ir.isArrayBufferView(t))return t.buffer;if(ir.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return wNc(t,this.formSerializer).toString();if((c=ir.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return k7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),cyD(t)):t}],transformResponse:[function(t){let r=this.transitional||ENc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ir.isResponse(t)||ir.isReadableStream(t))return t;if(t&&ir.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?za.from(c,za.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:vA.classes.FormData,Blob:vA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ir.forEach(["delete","get","head","post","put","patch"],e=>{ENc.headers[e]={}});var ora=ENc;var lyD=ir.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_H_=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1270
1270
|
`).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&lyD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var hH_=Symbol("internals");function UGa(e){return e&&String(e).trim().toLowerCase()}function hZo(e){return e===!1||e==null?e:ir.isArray(e)?e.map(hZo):String(e)}function fyD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var dyD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function SNc(e,t,r,i,n){if(ir.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!ir.isString(t)){if(ir.isString(i))return t.indexOf(i)!==-1;if(ir.isRegExp(i))return i.test(t)}}function pyD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function _yD(e,t){let r=ir.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var ura=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let u=UGa(d);if(!u)throw new Error("header name must be a non-empty string");let l=ir.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=hZo(c))}let o=(c,d)=>ir.forEach(c,(s,u)=>a(s,u,d));if(ir.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(ir.isString(t)&&(t=t.trim())&&!dyD(t))o(_H_(t),r);else if(ir.isObject(t)&&ir.isIterable(t)){let c={},d,s;for(let u of t){if(!ir.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?ir.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=UGa(t),t){let i=ir.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return fyD(n);if(ir.isFunction(r))return r.call(this,n,i);if(ir.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=UGa(t),t){let i=ir.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||SNc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=UGa(o),o){let c=ir.findKey(i,o);c&&(!r||SNc(i,i[c],c,r))&&(delete i[c],n=!0)}}return ir.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||SNc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return ir.forEach(this,(n,a)=>{let o=ir.findKey(i,a);if(o){r[o]=hZo(n),delete r[a];return}let c=t?pyD(a):String(a).trim();c!==a&&delete r[a],r[c]=hZo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return ir.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&ir.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
|
|
1271
1271
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[hH_]=this[hH_]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=UGa(o);i[c]||(_yD(n,o),i[c]=!0)}return ir.isArray(t)?t.forEach(a):a(t),this}};ura.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ir.reduceDescriptors(ura.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ir.freezeMethods(ura);var AD=ura;function LGa(e,t){let r=this||ora,i=t||r,n=AD.from(i.headers),a=i.data;return ir.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function VGa(e){return!!(e&&e.__CANCEL__)}function yH_(e,t,r){za.call(this,e??"canceled",za.ERR_CANCELED,t,r),this.name="CanceledError"}ir.inherits(yH_,za,{__CANCEL__:!0});var Nve=yH_;function F$t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new za("Request failed with status code "+r.status,[za.ERR_BAD_REQUEST,za.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function MNc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function DNc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cyn(e,t,r){let i=!MNc(t);return e&&(i||r==!1)?DNc(e,t):t}var UH_=ue(BNc(),1),LH_=ue(require("http"),1),VH_=ue(require("https"),1),WH_=ue(require("util"),1),GH_=ue(jH_(),1),OQi=ue(require("zlib"),1);var dyn="1.12.2";function KGa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var IyD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function WNc(e,t,r){let i=r&&r.Blob||vA.classes.Blob,n=KGa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=IyD.exec(e);if(!a)throw new za("Invalid URL",za.ERR_INVALID_URL);let o=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new za("Blob is not supported",za.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new za("Unsupported protocol "+n,za.ERR_NOT_SUPPORT)}var _yn=ue(require("stream"),1);var wH_=ue(require("stream"),1);var GNc=Symbol("internals"),xNc=class extends wH_.default.Transform{constructor(t){t=ir.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!ir.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[GNc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[GNc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[GNc],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,g,m=0;if(a){let O=Date.now();(!n.ts||(m=O-n.ts)>=c)&&(n.ts=O,g=s-n.bytes,n.bytes=g<0?-g:0,m=0),g=s-n.bytes}if(a){if(g<=0)return setTimeout(()=>{h(null,_)},c-m);g<v&&(v=g)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),l(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},HNc=xNc;var xH_=require("events");var SH_=ue(require("util"),1),MH_=require("stream");var{asyncIterator:EH_}=Symbol,CyD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[EH_]?yield*e[EH_]():yield e},yZo=CyD;var qyD=vA.ALPHABET.ALPHA_DIGIT+"-_",JGa=typeof TextEncoder=="function"?new TextEncoder:new SH_.default.TextEncoder,pyn=`\r
|
|
1272
1272
|
`,TyD=JGa.encode(pyn),RyD=2,KNc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=ir.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${pyn}`;n?r=JGa.encode(String(r).replace(/\r?\n|\r\n?/g,pyn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${pyn}`,this.headers=JGa.encode(a+pyn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+RyD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ir.isTypedArray(t)?yield t:yield*yZo(t),yield TyD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},zyD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+vA.generateString(n,qyD)}=r||{};if(!ir.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=JGa.encode("--"+a+pyn),c=JGa.encode("--"+a+"--"+pyn),d=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new KNc(l,p);return d+=_.size,_});d+=o.byteLength*s.length,d=ir.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),MH_.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},DH_=zyD;var BH_=ue(require("stream"),1),JNc=class extends BH_.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},IH_=JNc;var NyD=(e,t)=>ir.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,CH_=NyD;function FyD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),u=i[a];o||(o=s),r[n]=d,i[n]=s;let l=a,p=0;for(;l!==n;)p+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var qH_=FyD;function QyD(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-l)))},()=>n&&o(n)]}var TH_=QyD;var gQi=(e,t,r=3)=>{let i=0,n=qH_(50,250);return TH_(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-i,s=n(d),u=o<=c;i=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},cra=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},lra=e=>(...t)=>ir.asap(()=>e(...t));function $Nc(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,d=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);d>=0&&(i.charCodeAt(d)===61?(c++,d--):s(d)&&(c++,d-=3)),c===1&&d>=0&&(i.charCodeAt(d)===61||s(d))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var RH_={flush:OQi.default.constants.Z_SYNC_FLUSH,finishFlush:OQi.default.constants.Z_SYNC_FLUSH},UyD={flush:OQi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:OQi.default.constants.BROTLI_OPERATION_FLUSH},zH_=ir.isFunction(OQi.default.createBrotliDecompress),{http:LyD,https:VyD}=GH_.default,WyD=/https:?/,NH_=vA.protocols.map(e=>e+":"),FH_=(e,[t,r])=>(e.on("end",r).on("error",r),t);function GyD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function HH_(e,t,r){let i=t;if(!i&&i!==!1){let n=UH_.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){HH_(a,t,a.href)}}var xyD=typeof process<"u"&&ir.kindOf(process)==="process",HyD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},o=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(o,c,d=>i=d).catch(c)}),KyD=({address:e,family:t})=>{if(!ir.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},QH_=(e,t)=>KyD(ir.isObject(e)?e:{address:e,family:t}),KH_=xyD&&function(t){return HyD(async function(i,n,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let $=CH_(c,de=>ir.isArray(de)?de:[de]);c=(de,be,W)=>{$(de,be,(x,Ee,se)=>{if(x)return W(x);let Oe=ir.isArray(Ee)?Ee.map(Fe=>QH_(Fe)):[QH_(Ee,se)];be.all?W(x,Oe):W(x,Oe[0].address,Oe[0].family)})}}let y=new xH_.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a(($,de)=>{p=!0,de&&(_=!0,b())});function v($){y.emit("abort",!$||$.type?new Nve(null,t,h):$)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let g=cyn(t.baseURL,t.url,t.allowAbsoluteUrls),m=new URL(g,vA.hasBrowserEnv?vA.origin:void 0),O=m.protocol||NH_[0];if(O==="data:"){if(t.maxContentLength>-1){let de=String(t.url||g||"");if($Nc(de)>t.maxContentLength)return n(new za("maxContentLength size of "+t.maxContentLength+" exceeded",za.ERR_BAD_RESPONSE,t))}let $;if(l!=="GET")return F$t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{$=WNc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(de){throw za.from(de,za.ERR_BAD_REQUEST,t)}return s==="text"?($=$.toString(u),(!u||u==="utf8")&&($=ir.stripBOM($))):s==="stream"&&($=_yn.default.Readable.from($)),F$t(i,n,{data:$,status:200,statusText:"OK",headers:new AD,config:t})}if(NH_.indexOf(O)===-1)return n(new za("Unsupported protocol "+O,za.ERR_BAD_REQUEST,t));let A=AD.from(t.headers).normalize();A.set("User-Agent","axios/"+dyn,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,w=t.maxRate,D,B;if(ir.isSpecCompliantForm(o)){let $=A.getContentType(/boundary=([-_\w\d]{10,70})/i);o=DH_(o,de=>{A.set(de)},{tag:`axios-${dyn}-boundary`,boundary:$&&$[1]||void 0})}else if(ir.isFormData(o)&&ir.isFunction(o.getHeaders)){if(A.set(o.getHeaders()),!A.hasContentLength())try{let $=await WH_.default.promisify(o.getLength).call(o);Number.isFinite($)&&$>=0&&A.setContentLength($)}catch{}}else if(ir.isBlob(o)||ir.isFile(o))o.size&&A.setContentType(o.type||"application/octet-stream"),A.setContentLength(o.size||0),o=_yn.default.Readable.from(yZo(o));else if(o&&!ir.isStream(o)){if(!Buffer.isBuffer(o))if(ir.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(ir.isString(o))o=Buffer.from(o,"utf-8");else return n(new za("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",za.ERR_BAD_REQUEST,t));if(A.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new za("Request body larger than maxBodyLength limit",za.ERR_BAD_REQUEST,t))}let R=ir.toFiniteNumber(A.getContentLength());ir.isArray(w)?(D=w[0],B=w[1]):D=B=w,o&&(j||D)&&(ir.isStream(o)||(o=_yn.default.Readable.from(o,{objectMode:!1})),o=_yn.default.pipeline([o,new HNc({maxRate:ir.toFiniteNumber(D)})],ir.noop),j&&o.on("progress",FH_(o,cra(R,gQi(lra(j),!1,3)))));let T;if(t.auth){let $=t.auth.username||"",de=t.auth.password||"";T=$+":"+de}if(!T&&m.username){let $=m.username,de=m.password;T=$+":"+de}T&&A.delete("authorization");let q;try{q=syn(m.pathname+m.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch($){let de=new Error($.message);return de.config=t,de.url=t.url,de.exists=!0,n(de)}A.set("Accept-Encoding","gzip, compress, deflate"+(zH_?", br":""),!1);let z={path:q,method:l,headers:A.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:T,protocol:O,family:d,beforeRedirect:GyD,beforeRedirects:{}};!ir.isUndefined(c)&&(z.lookup=c),t.socketPath?z.socketPath=t.socketPath:(z.hostname=m.hostname.startsWith("[")?m.hostname.slice(1,-1):m.hostname,z.port=m.port,HH_(z,t.proxy,O+"//"+m.hostname+(m.port?":"+m.port:"")+z.path));let N,H=WyD.test(z.protocol);if(z.agent=H?t.httpsAgent:t.httpAgent,t.transport?N=t.transport:t.maxRedirects===0?N=H?VH_.default:LH_.default:(t.maxRedirects&&(z.maxRedirects=t.maxRedirects),t.beforeRedirect&&(z.beforeRedirects.config=t.beforeRedirect),N=H?VyD:LyD),t.maxBodyLength>-1?z.maxBodyLength=t.maxBodyLength:z.maxBodyLength=1/0,t.insecureHTTPParser&&(z.insecureHTTPParser=t.insecureHTTPParser),h=N.request(z,function(de){if(h.destroyed)return;let be=[de],W=+de.headers["content-length"];if(M||B){let Fe=new HNc({maxRate:ir.toFiniteNumber(B)});M&&Fe.on("progress",FH_(Fe,cra(W,gQi(lra(M),!0,3)))),be.push(Fe)}let x=de,Ee=de.req||h;if(t.decompress!==!1&&de.headers["content-encoding"])switch((l==="HEAD"||de.statusCode===204)&&delete de.headers["content-encoding"],(de.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":be.push(OQi.default.createUnzip(RH_)),delete de.headers["content-encoding"];break;case"deflate":be.push(new IH_),be.push(OQi.default.createUnzip(RH_)),delete de.headers["content-encoding"];break;case"br":zH_&&(be.push(OQi.default.createBrotliDecompress(UyD)),delete de.headers["content-encoding"])}x=be.length>1?_yn.default.pipeline(be,ir.noop):be[0];let se=_yn.default.finished(x,()=>{se(),b()}),Oe={status:de.statusCode,statusText:de.statusMessage,headers:new AD(de.headers),config:t,request:Ee};if(s==="stream")Oe.data=x,F$t(i,n,Oe);else{let Fe=[],ae=0;x.on("data",function(Ge){Fe.push(Ge),ae+=Ge.length,t.maxContentLength>-1&&ae>t.maxContentLength&&(_=!0,x.destroy(),n(new za("maxContentLength size of "+t.maxContentLength+" exceeded",za.ERR_BAD_RESPONSE,t,Ee)))}),x.on("aborted",function(){if(_)return;let Ge=new za("stream has been aborted",za.ERR_BAD_RESPONSE,t,Ee);x.destroy(Ge),n(Ge)}),x.on("error",function(Ge){h.destroyed||n(za.from(Ge,null,t,Ee))}),x.on("end",function(){try{let Ge=Fe.length===1?Fe[0]:Buffer.concat(Fe);s!=="arraybuffer"&&(Ge=Ge.toString(u),(!u||u==="utf8")&&(Ge=ir.stripBOM(Ge))),Oe.data=Ge}catch(Ge){return n(za.from(Ge,null,t,Oe.request,Oe))}F$t(i,n,Oe)})}y.once("abort",Fe=>{x.destroyed||(x.emit("error",Fe),x.destroy())})}),y.once("abort",$=>{n($),h.destroy($)}),h.on("error",function(de){n(za.from(de,null,t,h))}),h.on("socket",function(de){de.setKeepAlive(!0,1e3*60)}),t.timeout){let $=parseInt(t.timeout,10);if(Number.isNaN($)){n(new za("error trying to parse `config.timeout` to int",za.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout($,function(){if(p)return;let be=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",W=t.transitional||ara;t.timeoutErrorMessage&&(be=t.timeoutErrorMessage),n(new za(be,W.clarifyTimeoutError?za.ETIMEDOUT:za.ECONNABORTED,t,h)),v()})}if(ir.isStream(o)){let $=!1,de=!1;o.on("end",()=>{$=!0}),o.once("error",be=>{de=!0,h.destroy(be)}),o.on("close",()=>{!$&&!de&&v(new Nve("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var JH_=vA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,vA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(vA.origin),vA.navigator&&/(msie|trident)/i.test(vA.navigator.userAgent)):()=>!0;var $H_=vA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];ir.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ir.isString(i)&&o.push("path="+i),ir.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var YH_=e=>e instanceof AD?{...e}:e;function K3t(e,t){t=t||{};let r={};function i(s,u,l,p){return ir.isPlainObject(s)&&ir.isPlainObject(u)?ir.merge.call({caseless:p},s,u):ir.isPlainObject(u)?ir.merge({},u):ir.isArray(u)?u.slice():u}function n(s,u,l,p){if(ir.isUndefined(u)){if(!ir.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!ir.isUndefined(u))return i(void 0,u)}function o(s,u){if(ir.isUndefined(u)){if(!ir.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,l){if(l in t)return i(s,u);if(l in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,l)=>n(YH_(s),YH_(u),l,!0)};return ir.forEach(Object.keys({...e,...t}),function(u){let l=d[u]||n,p=l(e[u],t[u],u);ir.isUndefined(p)&&l!==c||(r[u]=p)}),r}var bZo=e=>{let t=K3t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=AD.from(o),t.url=syn(cyn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ir.isFormData(r)){if(vA.hasStandardBrowserEnv||vA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(ir.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(vA.hasStandardBrowserEnv&&(i&&ir.isFunction(i)&&(i=i(t)),i||i!==!1&&JH_(t.url))){let d=n&&a&&$H_.read(a);d&&o.set(n,d)}return t};var JyD=typeof XMLHttpRequest<"u",XH_=JyD&&function(e){return new Promise(function(r,i){let n=bZo(e),a=n.data,o=AD.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,u,l,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let m=AD.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),A={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:m,config:e,request:b};F$t(function(M){r(M),y()},function(M){i(M),y()},A),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new za("Request aborted",za.ECONNABORTED,e,b)),b=null)},b.onerror=function(O){let A=O&&O.message?O.message:"Network Error",j=new za(A,za.ERR_NETWORK,e,b);j.event=O||null,i(j),b=null},b.ontimeout=function(){let O=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",A=n.transitional||ara;n.timeoutErrorMessage&&(O=n.timeoutErrorMessage),i(new za(O,A.clarifyTimeoutError?za.ETIMEDOUT:za.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&ir.forEach(o.toJSON(),function(O,A){b.setRequestHeader(A,O)}),ir.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=gQi(s,!0),b.addEventListener("progress",p)),d&&b.upload&&([l,_]=gQi(d),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=m=>{b&&(i(!m||m.type?new Nve(null,e,b):m),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let g=KGa(n.url);if(g&&vA.protocols.indexOf(g)===-1){i(new za("Unsupported protocol "+g+":",za.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var $yD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof za?u:new Nve(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new za(`timeout ${t} of ms exceeded`,za.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>ir.asap(c),d}},ZH_=$yD;var YyD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},XyD=async function*(e,t){for await(let r of ZyD(e))yield*YyD(r,t)},ZyD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},YNc=(e,t,r,i)=>{let n=XyD(e,t),a=0,o,c=d=>{o||(o=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:u}=await n.next();if(s){c(),d.close();return}let l=u.byteLength;if(r){let p=a+=l;r(p)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var kH_=64*1024,{isFunction:vZo}=ir,kyD=(({Request:e,Response:t})=>({Request:e,Response:t}))(ir.global),{ReadableStream:e7_,TextEncoder:t7_}=ir.global,r7_=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ebD=e=>{e=ir.merge.call({skipUndefined:!0},kyD,e);let{fetch:t,Request:r,Response:i}=e,n=t?vZo(t):typeof fetch=="function",a=vZo(r),o=vZo(i);if(!n)return!1;let c=n&&vZo(e7_),d=n&&(typeof t7_=="function"?(h=>y=>h.encode(y))(new t7_):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&r7_(()=>{let h=!1,y=new r(vA.origin,{body:new e7_,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&r7_(()=>ir.isReadableStream(new i("").body)),l={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!l[h]&&(l[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new za(`Response type '${h}' is not supported`,za.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(ir.isBlob(h))return h.size;if(ir.isSpecCompliantForm(h))return(await new r(vA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(ir.isArrayBufferView(h)||ir.isArrayBuffer(h))return h.byteLength;if(ir.isURLSearchParams(h)&&(h=h+""),ir.isString(h))return(await d(h)).byteLength},_=async(h,y)=>{let b=ir.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:g,cancelToken:m,timeout:O,onDownloadProgress:A,onUploadProgress:j,responseType:M,headers:w,withCredentials:D="same-origin",fetchOptions:B}=bZo(h),R=t||fetch;M=M?(M+"").toLowerCase():"text";let T=ZH_([g,m&&m.toAbortSignal()],O),q=null,z=T&&T.unsubscribe&&(()=>{T.unsubscribe()}),N;try{if(j&&s&&b!=="get"&&b!=="head"&&(N=await _(w,v))!==0){let x=new r(y,{method:"POST",body:v,duplex:"half"}),Ee;if(ir.isFormData(v)&&(Ee=x.headers.get("content-type"))&&w.setContentType(Ee),x.body){let[se,Oe]=cra(N,gQi(lra(j)));v=YNc(x.body,kH_,se,Oe)}}ir.isString(D)||(D=D?"include":"omit");let H=a&&"credentials"in r.prototype,$={...B,signal:T,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:v,duplex:"half",credentials:H?D:void 0};q=a&&new r(y,$);let de=await(a?R(q,B):R(y,$)),be=u&&(M==="stream"||M==="response");if(u&&(A||be&&z)){let x={};["status","statusText","headers"].forEach(Fe=>{x[Fe]=de[Fe]});let Ee=ir.toFiniteNumber(de.headers.get("content-length")),[se,Oe]=A&&cra(Ee,gQi(lra(A),!0))||[];de=new i(YNc(de.body,kH_,se,()=>{Oe&&Oe(),z&&z()}),x)}M=M||"text";let W=await l[ir.findKey(l,M)||"text"](de,h);return!be&&z&&z(),await new Promise((x,Ee)=>{F$t(x,Ee,{data:W,headers:AD.from(de.headers),status:de.status,statusText:de.statusText,config:h,request:q})})}catch(H){throw z&&z(),H&&H.name==="TypeError"&&/Load failed|fetch/i.test(H.message)?Object.assign(new za("Network Error",za.ERR_NETWORK,h,q),{cause:H.cause||H}):za.from(H,H&&H.code,h,q)}}},tbD=new Map,XNc=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,d,s,u=tbD;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:ebD(t)),u=s;return s},bG9=XNc();var ZNc={http:KH_,xhr:XH_,fetch:{get:XNc}};ir.forEach(ZNc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var i7_=e=>`- ${e}`,ibD=e=>ir.isFunction(e)||e===null||e===!1,gZo={getAdapter:(e,t)=>{e=ir.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!ibD(i)&&(n=ZNc[(c=String(i)).toLowerCase()],n===void 0))throw new za(`Unknown adapter '${c}'`);if(n&&(ir.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([d,s])=>`adapter ${d} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
|
|
@@ -1505,7 +1505,7 @@ ${O}${g}${A}${Woa}`});var jKa=class{result=Qw.Success;logImmediately;logPrefix;s
|
|
|
1505
1505
|
Run ${Rt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1506
1506
|
Run ${Rt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),dra(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function SHc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!syh(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
|
|
1507
1507
|
${await xWD(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Rt.dim(c.currentVersion)+Rt.reset(" \u2192 ")+Rt.green(c.latestVersion);return n+=`
|
|
1508
|
-
`,i?dra(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function xWD(e){let r=await new uyh.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 HWD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=sHi(u.name,l),_=await A3t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let l=sHi(s.name,u),p=await A3t({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Ive({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?zN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function fyh(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=dY(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function p_u({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await HWD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...fyh(s,d,t.logger));else o.push(...fyh(c.versions,void 0,t.logger))}return o}var wKa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var xoa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var MHc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),dyh=typeof globalThis.AbortController=="function",pyh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",_yh=typeof globalThis.ReadableStream=="function",hyh=typeof globalThis.FormData=="function",__u=["get","post","put","patch","head","delete"],KWD=()=>{};KWD();var yyh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},h_u=2147483647,byh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,y_u=Symbol("stop"),vyh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},gyh={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var JWD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=byh,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Oyh=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},myh=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Oyh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Ayh=(e,t,r)=>{if(!e.body)return e;let i=JWD(r??e.body);return new Request(e,{duplex:"half",body:Oyh(e.body,i,t)})};var Hoa=e=>e!==null&&typeof e=="object";var EKa=(...e)=>{for(let t of e)if((!Hoa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return IHc({},...e)},DHc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function b_u(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:IHc(e[r]??[],t[r]??[])}var BHc=(e={},t={})=>({beforeRequest:b_u(e,t,"beforeRequest"),beforeRetry:b_u(e,t,"beforeRetry"),afterResponse:b_u(e,t,"afterResponse"),beforeError:b_u(e,t,"beforeError")}),IHc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Hoa(n)){for(let[a,o]of Object.entries(n))Hoa(o)&&a in t&&(o=IHc(t[a],o)),t={...t,[a]:o};Hoa(n.hooks)&&(i=BHc(i,n.hooks),t.hooks=i),Hoa(n.headers)&&(r=DHc(r,n.headers),t.headers=r)}return t};var jyh=e=>__u.includes(e)?e.toUpperCase():e,$WD=["get","put","head","delete","options","trace"],YWD=[408,413,429,500,502,503,504],XWD=[413,429,503],Pyh={limit:2,methods:$WD,statusCodes:YWD,afterStatusCodes:XWD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},wyh=(e={})=>{if(typeof e=="number")return{...Pyh,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Pyh,...e}};async function CHc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new xoa(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function qHc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Eyh=(e,t)=>{let r={};for(let i in t)!(i in gyh)&&!(i in vyh)&&!(i in e)&&(r[i]=t[i]);return r},Syh=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var SKa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>h_u)throw new RangeError(`The \`timeout\` option cannot be greater than ${h_u}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new wKa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!_yh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return myh(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(yyh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:DHc(this._input.headers,r.headers),hooks:BHc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:jyh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:wyh(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(dyh&&pyh){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(MHc&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),Syh(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(hyh&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!MHc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ayh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof xoa)throw t;if(t instanceof wKa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),h_u);if(this._retryCount<1)throw r;await qHc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===y_u)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Eyh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):CHc(this._originalRequest,t,this.abortController,this._options)}};var THc=e=>{let t=(r,i)=>SKa.create(r,EKa(e,i));for(let r of __u)t[r]=(i,n)=>SKa.create(i,EKa(e,n,{method:r}));return t.create=r=>THc(EKa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),THc(EKa(e,r))),t.stop=y_u,t},ZWD=THc(),Myh=ZWD;var Xyh=ue(Yyh(),1);function QHc(e){let t=(0,Xyh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var xbh=ue(Gbh(),1),Hbh=ue(EJ(),1),ZHc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},kHc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function e7c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??QHc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,xbh.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Myh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new ZHc(e):l}if(t.allVersions)return s;let u=new kHc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Hbh.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function qKa(e,t){let{version:r}=await e7c(e.toLowerCase(),t);return r}async function NJi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:qKa(e.packageName,{version:t?"prerelease":"latest"})}var Kbh=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],D_u=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ou.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new tdn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.49.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Rt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pM}failWithoutThrowing(t,r){this.didSucceed=!1,k4a({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await tra()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await cyh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1508
|
+
`,i?dra(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function xWD(e){let r=await new uyh.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 HWD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=sHi(u.name,l),_=await A3t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let l=sHi(s.name,u),p=await A3t({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function lyh({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Ive({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?zN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function fyh(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=dY(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function p_u({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await HWD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...fyh(s,d,t.logger));else o.push(...fyh(c.versions,void 0,t.logger))}return o}var wKa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var xoa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var MHc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),dyh=typeof globalThis.AbortController=="function",pyh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",_yh=typeof globalThis.ReadableStream=="function",hyh=typeof globalThis.FormData=="function",__u=["get","post","put","patch","head","delete"],KWD=()=>{};KWD();var yyh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},h_u=2147483647,byh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,y_u=Symbol("stop"),vyh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},gyh={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var JWD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=byh,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Oyh=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},myh=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Oyh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Ayh=(e,t,r)=>{if(!e.body)return e;let i=JWD(r??e.body);return new Request(e,{duplex:"half",body:Oyh(e.body,i,t)})};var Hoa=e=>e!==null&&typeof e=="object";var EKa=(...e)=>{for(let t of e)if((!Hoa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return IHc({},...e)},DHc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function b_u(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:IHc(e[r]??[],t[r]??[])}var BHc=(e={},t={})=>({beforeRequest:b_u(e,t,"beforeRequest"),beforeRetry:b_u(e,t,"beforeRetry"),afterResponse:b_u(e,t,"afterResponse"),beforeError:b_u(e,t,"beforeError")}),IHc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Hoa(n)){for(let[a,o]of Object.entries(n))Hoa(o)&&a in t&&(o=IHc(t[a],o)),t={...t,[a]:o};Hoa(n.hooks)&&(i=BHc(i,n.hooks),t.hooks=i),Hoa(n.headers)&&(r=DHc(r,n.headers),t.headers=r)}return t};var jyh=e=>__u.includes(e)?e.toUpperCase():e,$WD=["get","put","head","delete","options","trace"],YWD=[408,413,429,500,502,503,504],XWD=[413,429,503],Pyh={limit:2,methods:$WD,statusCodes:YWD,afterStatusCodes:XWD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},wyh=(e={})=>{if(typeof e=="number")return{...Pyh,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Pyh,...e}};async function CHc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new xoa(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function qHc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Eyh=(e,t)=>{let r={};for(let i in t)!(i in gyh)&&!(i in vyh)&&!(i in e)&&(r[i]=t[i]);return r},Syh=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var SKa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>h_u)throw new RangeError(`The \`timeout\` option cannot be greater than ${h_u}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new wKa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!_yh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return myh(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(yyh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:DHc(this._input.headers,r.headers),hooks:BHc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:jyh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:wyh(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(dyh&&pyh){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(MHc&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),Syh(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(hyh&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!MHc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ayh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof xoa)throw t;if(t instanceof wKa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),h_u);if(this._retryCount<1)throw r;await qHc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===y_u)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Eyh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):CHc(this._originalRequest,t,this.abortController,this._options)}};var THc=e=>{let t=(r,i)=>SKa.create(r,EKa(e,i));for(let r of __u)t[r]=(i,n)=>SKa.create(i,EKa(e,n,{method:r}));return t.create=r=>THc(EKa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),THc(EKa(e,r))),t.stop=y_u,t},ZWD=THc(),Myh=ZWD;var Xyh=ue(Yyh(),1);function QHc(e){let t=(0,Xyh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var xbh=ue(Gbh(),1),Hbh=ue(EJ(),1),ZHc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},kHc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function e7c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??QHc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,xbh.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Myh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new ZHc(e):l}if(t.allVersions)return s;let u=new kHc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Hbh.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function qKa(e,t){let{version:r}=await e7c(e.toLowerCase(),t);return r}async function NJi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:qKa(e.packageName,{version:t?"prerelease":"latest"})}var Kbh=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],D_u=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ou.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new tdn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.49.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Rt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pM}failWithoutThrowing(t,r){this.didSucceed=!1,k4a({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await tra()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await cyh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1509
1509
|
`)||(r+=`
|
|
1510
1510
|
`),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=cnc(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.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 jKa(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 i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new pM}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await tra()).sendEvent(t)}logger=tve((t,...r)=>this.log(t,...r));stderr=tve((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Jbh(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Jbh(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Kbh[this.numTasks++%Kbh.length],o=Rt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Qw.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 i=t.filter(n=>kLt.indexOf(n.level)>=kLt.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Ou.Debug,stderr:r})}_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 NJi({cliEnvironment:this.environment,includePreReleases:t}),i=dY(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await p_u({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await wHc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Rt.yellow("?"),style:{answer:n=>Rt.cyan(n),message:n=>Rt.bold(n),highlight:n=>Rt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
1511
1511
|
Cancelled by user.`),new pM):i}}async getInput(t){return await mHc({message:t.message,default:t.default})}};function Jbh(e){return`[${e}]:`}var O8t=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};function B_u(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>B_u.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function $bh(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(d=>(c=d,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function Ybh(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var Xbh=Function.bind,Zbh=Xbh.bind(Xbh);function kbh(e,t,r){let i=Zbh(Ybh,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=Zbh($bh,null).apply(null,a)})}function n6D(){let e=Symbol("Singular"),t={registry:{}},r=B_u.bind(null,t,e);return kbh(r,t,e),r}function a6D(){let e={registry:{}},t=B_u.bind(null,e);return kbh(t,e),t}var evh={Singular:n6D,Collection:a6D};var o6D="0.0.0-development",u6D=`octokit-endpoint.js/${o6D} ${LN()}`,s6D={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":u6D},mediaType:{format:""}};function c6D(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function l6D(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function ivh(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{l6D(t[i])?i in e?r[i]=ivh(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function tvh(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function r7c(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=c6D(r.headers),tvh(r),tvh(r.headers);let i=ivh(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function f6D(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var d6D=/\{[^{}}]+\}/g;function p6D(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function _6D(e){let t=e.match(d6D);return t?t.map(p6D).reduce((r,i)=>r.concat(i),[]):[]}function rvh(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function nvh(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function eua(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function TKa(e,t,r){return t=e==="+"||e==="#"?nvh(t):eua(t),r?eua(r)+"="+t:t}function koa(e){return e!=null}function t7c(e){return e===";"||e==="&"||e==="?"}function h6D(e,t,r,i){var n=e[r],a=[];if(koa(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(TKa(t,n,t7c(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(koa).forEach(function(o){a.push(TKa(t,o,t7c(t)?r:""))}):Object.keys(n).forEach(function(o){koa(n[o])&&a.push(TKa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(koa).forEach(function(c){o.push(TKa(t,c))}):Object.keys(n).forEach(function(c){koa(n[c])&&(o.push(eua(c)),o.push(TKa(t,n[c].toString())))}),t7c(t)?a.push(eua(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?koa(n)&&a.push(eua(r)):n===""&&(t==="&"||t==="?")?a.push(eua(r)+"="):n===""&&a.push("");return a}function y6D(e){return{expand:b6D.bind(null,e)}}function b6D(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",d=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);d.push(h6D(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(d.length!==0?c:"")+d.join(o)}else return d.join(",")}else return nvh(a)}),e==="/"?e:e.replace(/\/$/,"")}function avh(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=rvh(e,["method","baseUrl","url","headers","request","mediaType"]),o=_6D(r);r=y6D(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=rvh(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(l=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${l}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=f6D(r,d):"data"in d?n=d.data:Object.keys(d).length&&(n=d),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function v6D(e,t,r){return avh(r7c(e,t,r))}function ovh(e,t){let r=r7c(e,t),i=v6D.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:ovh.bind(null,r),merge:r7c.bind(null,r),parse:avh})}var uvh=ovh(null,s6D);var pvh=ue(fvh(),1);var m8t=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var g6D="10.0.6",O6D={headers:{"user-agent":`octokit-request.js/${g6D} ${LN()}`}};function m6D(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function dvh(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=m6D(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([l,p])=>[l,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(l){let p="Unknown Error";if(l instanceof Error){if(l.name==="AbortError")throw l.status=500,l;p=l.message,l.name==="TypeError"&&"cause"in l&&(l.cause instanceof Error?p=l.cause.message:typeof l.cause=="string"&&(p=l.cause))}let _=new m8t(p,500,{request:e});throw _.cause=l,_}let c=o.status,d=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:d,status:c,headers:s,data:""};if("deprecation"in s){let l=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=l&&l.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new m8t(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await i7c(o),new m8t("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await i7c(o),new m8t(P6D(u.data),c,{response:u,request:e});return u.data=i?await i7c(o):o.body,u}async function i7c(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,pvh.safeParse)(t);if(A6D(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function A6D(e){return e.type==="application/json"||e.type==="application/scim+json"}function P6D(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function n7c(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return dvh(r.parse(o));let c=(d,s)=>dvh(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:n7c.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:n7c.bind(null,r)})}var Qm=n7c(uvh,O6D);var j6D="0.0.0-development";function w6D(e){return`Request failed due to following response errors:
|
|
@@ -1899,7 +1899,7 @@ ${i.map(a=>` ${a}`).join(`,
|
|
|
1899
1899
|
`)}
|
|
1900
1900
|
]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function e0u(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function EwB(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function t0u({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],o=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,u=o.get(s);if(o.set(s,c),u==null||u.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(u),p=c.isResponseStream?c:u,_=c.isResponseStream?u:c,h={id:Nt.V1.NodeId(`${n}:${_.endpointId}+${p.endpointId}`),type:"endpointPair",stream:p,nonStream:_};a[l]=h}),a}function CQh({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return t0u({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(o=>o.type==="apiPackage"?o.children.length>0:!0)}function Kca(e,t){if(t!=null)return Xf(e.absoluteFilePath,t)}function qQh({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:o,resolveIconFileId:c}){let d=Nt.V1.PageId(Kca(e,t.absolutePath)),s=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??cS(t.title)});return{id:i.get(d),type:"page",pageId:d,title:t.title,slug:s.get(),icon:c?c(t.icon):t.icon,hidden:o||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var r0u=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;openApiTags;apiDefinitionId;#e;#t=new Set;#r=new Set;#i=new Set;#n=new Set;#a=new Set;#o=new Map;#s=[];#u;#c;#f;disableEndpointPairs;collectedFileIds=new Map;#p;constructor(t,r,i,n,a,o,c,d,s,u,l,p,_,h){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=o,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=d,this.workspace=l,this.hideChildren=p,this.parentAvailability=_,this.openApiTags=h,this.#p=new Map,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Nt.V1.ApiDefinitionId(r.id),this.#e=yYi.create(r,a),this.collectedFileIds=u,this.#f=s,this.#u=this.apiSection.overviewAbsolutePath!=null?Nt.V1.PageId(Kca(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let y=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=i.apply({fullSlug:y?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??cS(this.apiSection.title)});let b=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#s=this.#d(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,b)),this.#s=this.#g(this.#s.map(v=>this.#m(v,b)),this.#A(this.#e.api.rootPackage,this.#c,b))}get(){let t=Nt.V1.followRedirects(this.#s),r=new aOn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#f).orUndefined();return{id:this.#f.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#u,paginated:this.apiSection.paginated,slug:this.#c.get(),icon:this.resolveIconFileId(this.apiSection.icon),hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability??this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#P(this.apiSection.playground),postmanCollectionUrl:this.apiSection.postman,authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}getTagDescriptionContent(){return this.#p}createTagDescriptionPageId(t){if(!this.apiSection.tagDescriptionPages||!this.openApiTags)return;let r=Z8t(t)?t.name:void 0;if(!r)return;let i=this.openApiTags[r];if(!i||!i.description)return;let n=`tag-${r}.md`,a=Sr.of(`/${n}`),o=Nt.V1.PageId(n),c=`# ${iOn(i.id.replace(/[_-]/g," "))}
|
|
1901
1901
|
|
|
1902
|
-
${i.description}`;return this.#p.set(a,c),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#d(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?yYi.getSubpackageId(r):void 0;return t.map(o=>otl(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:Nt.Url(c.url),target:c.target}),page:c=>this.#l(c,i,n),package:c=>this.#_(c,i,n),section:c=>this.#y(c,i,n),item:({value:c})=>this.#h(c,a,i,n),endpoint:c=>this.#O(c,a,i,n)})).filter(us)}#l(t,r,i){return qQh({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#_(t,r,i){let n=t.overviewAbsolutePath!=null?Nt.V1.PageId(Kca(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let d=yYi.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${d}`);this.#a.has(d)&&this.taskContext.logger.warn(e0u(t.package)),this.#a.add(d),this.#o.set(s,[d]);let u=t.slug??(Z8t(c)?c.urlSlug:this.apiSection.slug??cS(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:p,title:t.title??(Z8t(c)?c.displayName??iOn(c.name):this.apiSection.title),slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(kju(t.package,this.#e.subpackageLocators));let d=t.slug??cS(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),u=this.#d(t.contents,void 0,s,o);return{id:this.#f.get(n??`${this.apiDefinitionId}:${cS(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#y(t,r,i){let n=t.overviewAbsolutePath!=null?Nt.V1.PageId(Kca(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(n??a??r.get()),d=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?yYi.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(kju(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(us);this.#o.set(c,d.map(_=>_.subpackageId)),d.forEach(_=>{this.#a.has(_.subpackageId)&&this.taskContext.logger.error(e0u(_.locator)),this.#a.add(_.subpackageId)});let s=t.slug??cS(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??i,p=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#h(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(ou(t));if(a!=null){let o=yYi.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(e0u(t)),this.#a.add(o),this.#o.set(c,[o]);let d=Z8t(a)?a.urlSlug:"",s=i.apply({urlSlug:d});return{id:c,type:"apiPackage",children:[],title:Z8t(a)?a.displayName??iOn(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i,n)}#O(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.endpoints.get(C4.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let d=this.#e.getEndpointId(a);if(d==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(d)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${d}`),this.#t.add(d);let s=t.slug!=null?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"endpoint",method:a.method,endpointId:d,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Nt.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??xW(a.path.parts),slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#P(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.webSockets.get(C4.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let d=this.#e.getWebSocketId(o);if(d==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(d)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${d}`),this.#r.add(d),{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"webSocket",webSocketId:d,title:t.title??o.name??xW(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(o.availability)??n,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.webhooks.get(C4.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Nt.V1.WebhookId(t.endpoint));if(c!=null){let d=this.#e.getWebhookId(c);if(d==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#i.has(d)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${d}`),this.#i.add(d),{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"webhook",webhookId:d,method:c.method,title:t.title??c.name??(0,TQh.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:n,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#g(t,r){return CQh({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>xW(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t,r){return ctl({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(i,n,a)=>this.#v(i,n,a),mergeAndFilterChildren:this.#g.bind(this)})}#A(t,r,i){let n=[];return t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??xW(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??xW(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??xW(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(a.availability)??i,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#i.has(o)||n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??iOn(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:i,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#a.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=Z8t(o)?r.apply(o):r,d=this.#v(a,c,i);d.length>0&&n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:d,title:Z8t(o)?o.displayName??iOn(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(o),availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,d=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(d)})),n}#v(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(kju(t||"unknown",[])),[]):this.#A(n,r,i)}#P(t){return PQh(t)}mergeEndpointPairs(t){return t0u({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>xW(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};var RQh=ue(require("crypto"),1);function SwB(e){return RQh.default.createHash("sha256").update(e).digest("hex")}var i0u=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),SwB(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Nt.V1.NodeId(this.#i(t))}};function zQh(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}var n0u=class{selectors;constructor(t){this.selectors=t}matches(t,r){for(let i of this.selectors)if(this.pathMatches(t,i.path)&&(!i.method||i.method===r))return!0;return!1}pathMatches(t,r){if(t===r)return!0;let i=t.split("/").filter(a=>a.length>0),n=r.split("/").filter(a=>a.length>0);if(i.length!==n.length)return!1;for(let a=0;a<i.length;a++){let o=i[a],c=n[a];if(!o||!c)return!1;let d=o.startsWith("{")&&o.endsWith("}"),s=c.startsWith("{")&&c.endsWith("}");if(!(d&&s)&&o!==c)return!1}return!0}getMatchingPaths(t){let r=[];for(let[i,n]of Object.entries(t)){if(!n)continue;let a=["get","put","post","delete","options","head","patch","trace"];for(let o of a)if(n[o]&&this.matches(i,o)){r.includes(i)||r.push(i);break}}return r}};var a0u=class{document;schemas=new Set;parameters=new Set;responses=new Set;requestBodies=new Set;securitySchemes=new Set;headers=new Set;examples=new Set;links=new Set;callbacks=new Set;constructor(t){this.document=t}collectFromOperation(t){if(t.parameters)for(let r of t.parameters)this.collectParameter(r);if(t.requestBody&&this.collectFromRequestBody(t.requestBody),t.responses)for(let r of Object.values(t.responses))this.collectFromResponse(r);if(t.callbacks)for(let[r,i]of Object.entries(t.callbacks))if(this.isReference(i))this.callbacks.add(this.extractComponentName(i.$ref));else for(let n of Object.values(i))this.collectFromPathItem(n);if(t.security)for(let r of t.security)for(let i of Object.keys(r))this.securitySchemes.add(i)}collectFromPathItem(t){if(t.parameters)for(let i of t.parameters)this.collectParameter(i);let r=[t.get,t.put,t.post,t.delete,t.options,t.head,t.patch,t.trace];for(let i of r)i&&this.collectFromOperation(i)}collectParameter(t){if(this.isReference(t)){this.parameters.add(this.extractComponentName(t.$ref));let r=this.resolveParameter(t.$ref);r&&this.collectParameter(r)}else{if(t.schema&&this.collectFromSchema(t.schema),t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}}collectFromRequestBody(t){if(this.isReference(t)){this.requestBodies.add(this.extractComponentName(t.$ref));let r=this.resolveRequestBody(t.$ref);r&&this.collectFromRequestBody(r)}else if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r)}collectFromResponse(t){if(this.isReference(t)){this.responses.add(this.extractComponentName(t.$ref));let r=this.resolveResponse(t.$ref);r&&this.collectFromResponse(r)}else{if(t.headers)for(let[r,i]of Object.entries(t.headers))this.isReference(i)?this.headers.add(this.extractComponentName(i.$ref)):i.schema&&this.collectFromSchema(i.schema);if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.links)for(let[r,i]of Object.entries(t.links))this.isReference(i)&&this.links.add(this.extractComponentName(i.$ref))}}collectFromMediaType(t){if(t.schema&&this.collectFromSchema(t.schema),t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}collectFromSchema(t){if(this.isReference(t)){let r=this.extractComponentName(t.$ref);if(!this.schemas.has(r)){this.schemas.add(r);let i=this.resolveSchema(t.$ref);i&&this.collectFromSchema(i)}}else{if(t.properties)for(let r of Object.values(t.properties))this.collectFromSchema(r);if(t.additionalProperties&&typeof t.additionalProperties=="object"&&this.collectFromSchema(t.additionalProperties),"items"in t&&t.items)if(Array.isArray(t.items))for(let r of t.items)this.collectFromSchema(r);else this.collectFromSchema(t.items);if(t.allOf)for(let r of t.allOf)this.collectFromSchema(r);if(t.oneOf)for(let r of t.oneOf)this.collectFromSchema(r);if(t.anyOf)for(let r of t.anyOf)this.collectFromSchema(r);t.not&&this.collectFromSchema(t.not)}}resolveSchema(t){let r=this.extractComponentName(t);return this.document.components?.schemas?.[r]}resolveParameter(t){let r=this.extractComponentName(t);return this.document.components?.parameters?.[r]}resolveResponse(t){let r=this.extractComponentName(t);return this.document.components?.responses?.[r]}resolveRequestBody(t){let r=this.extractComponentName(t);return this.document.components?.requestBodies?.[r]}isReference(t){return t!=null&&typeof t=="object"&&"$ref"in t}extractComponentName(t){let r=t.split("/");return r[r.length-1]??t}getSchemas(){return this.schemas}getParameters(){return this.parameters}getResponses(){return this.responses}getRequestBodies(){return this.requestBodies}getSecuritySchemes(){return this.securitySchemes}getHeaders(){return this.headers}getExamples(){return this.examples}getLinks(){return this.links}getCallbacks(){return this.callbacks}};var JYa=class{matcher;document;constructor(t){this.matcher=new n0u(t.endpoints),this.document=JSON.parse(JSON.stringify(t.document))}prune(){let t=this.collectStatistics(),r=new a0u(this.document),i={},n=this.matcher.getMatchingPaths(this.document.paths);for(let c of n){let d=this.document.paths[c];if(!d)continue;let s={};d.summary&&(s.summary=d.summary),d.description&&(s.description=d.description),d.servers&&(s.servers=d.servers),d.parameters&&(s.parameters=d.parameters);let u=["get","put","post","delete","options","head","patch","trace"];for(let l of u){let p=d[l];p&&this.matcher.matches(c,l)&&(s[l]=p,r.collectFromOperation(p))}if(d.parameters)for(let l of d.parameters)r.collectParameter(l);i[c]=s}let a={openapi:this.document.openapi,info:this.document.info,paths:i};if(this.document.servers&&(a.servers=this.document.servers),this.document.externalDocs&&(a.externalDocs=this.document.externalDocs),this.document.tags){let c=new Set;for(let d of Object.values(i)){let s=["get","put","post","delete","options","head","patch","trace"];for(let u of s){let l=d?.[u];if(l?.tags)for(let p of l.tags)c.add(p)}}a.tags=this.document.tags.filter(d=>c.has(d.name))}if(this.document.security){a.security=this.document.security;for(let c of this.document.security)for(let d of Object.keys(c))r.getSecuritySchemes().add(d)}a.components=this.buildPrunedComponents(r);let o=this.collectPrunedStatistics(a);return{document:a,statistics:{originalEndpoints:t.originalEndpoints,prunedEndpoints:o.originalEndpoints,originalSchemas:t.originalSchemas,prunedSchemas:o.originalSchemas,originalParameters:t.originalParameters,prunedParameters:o.originalParameters,originalResponses:t.originalResponses,prunedResponses:o.originalResponses,originalRequestBodies:t.originalRequestBodies,prunedRequestBodies:o.originalRequestBodies,originalSecuritySchemes:t.originalSecuritySchemes,prunedSecuritySchemes:o.originalSecuritySchemes}}}buildPrunedComponents(t){if(!this.document.components)return;let r={};if(this.document.components.schemas&&t.getSchemas().size>0){r.schemas={};for(let i of t.getSchemas()){let n=this.document.components.schemas[i];n&&(r.schemas[i]=n)}}if(this.document.components.parameters&&t.getParameters().size>0){r.parameters={};for(let i of t.getParameters()){let n=this.document.components.parameters[i];n&&(r.parameters[i]=n)}}if(this.document.components.responses&&t.getResponses().size>0){r.responses={};for(let i of t.getResponses()){let n=this.document.components.responses[i];n&&(r.responses[i]=n)}}if(this.document.components.requestBodies&&t.getRequestBodies().size>0){r.requestBodies={};for(let i of t.getRequestBodies()){let n=this.document.components.requestBodies[i];n&&(r.requestBodies[i]=n)}}if(this.document.components.securitySchemes&&t.getSecuritySchemes().size>0){r.securitySchemes={};for(let i of t.getSecuritySchemes()){let n=this.document.components.securitySchemes[i];n&&(r.securitySchemes[i]=n)}}if(this.document.components.headers&&t.getHeaders().size>0){r.headers={};for(let i of t.getHeaders()){let n=this.document.components.headers[i];n&&(r.headers[i]=n)}}if(this.document.components.examples&&t.getExamples().size>0){r.examples={};for(let i of t.getExamples()){let n=this.document.components.examples[i];n&&(r.examples[i]=n)}}if(this.document.components.links&&t.getLinks().size>0){r.links={};for(let i of t.getLinks()){let n=this.document.components.links[i];n&&(r.links[i]=n)}}if(this.document.components.callbacks&&t.getCallbacks().size>0){r.callbacks={};for(let i of t.getCallbacks()){let n=this.document.components.callbacks[i];n&&(r.callbacks[i]=n)}}return Object.keys(r).length>0?r:void 0}collectStatistics(){let t=0;for(let r of Object.values(this.document.paths)){if(!r)continue;let i=["get","put","post","delete","options","head","patch","trace"];for(let n of i)r[n]&&t++}return{originalEndpoints:t,prunedEndpoints:0,originalSchemas:Object.keys(this.document.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(this.document.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(this.document.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(this.document.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(this.document.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}collectPrunedStatistics(t){let r=0;for(let i of Object.values(t.paths)){if(!i)continue;let n=["get","put","post","delete","options","head","patch","trace"];for(let a of n)i[a]&&r++}return{originalEndpoints:r,prunedEndpoints:0,originalSchemas:Object.keys(t.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(t.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(t.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(t.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(t.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}};var btl=require("fs/promises");function ftl(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e,r=Object.keys(t);if(r.length===0||r.length>2)return!1;let i="type"in t&&typeof t.type=="string",n="value"in t;return i&&r.length===1||i&&n&&r.length===2||n&&r.length===1}function bYi(e){if(e==null)return e;if(Array.isArray(e))return e.map(bYi);if(typeof e!="object")return e;let t=e;if(ftl(t))return"value"in t?bYi(t.value):void 0;let r={};for(let[i,n]of Object.entries(t)){let a=bYi(n);a!==void 0&&(r[i]=a)}return r}function dtl(e){return e==null?!0:typeof e!="object"?!1:Array.isArray(e)?e.length===0:Object.keys(e).length===0}function o0u(e,t,r,i){let n={},a={},o={};if(e==null||typeof e!="object"||Array.isArray(e))return{filteredBody:e,extractedPathParams:n,extractedQueryParams:a,extractedHeaders:o};let c=e,d={},s=new Set(Object.keys(t??{})),u=new Set(Object.keys(r??{})),l=new Set(Object.keys(i??{}));for(let[p,_]of Object.entries(c)){let h=p.toLowerCase().replace(/[-_]/g,""),y=!1,b=!1,v=!1;for(let g of s){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){y=!0,n[g]=_;break}}if(!y)for(let g of u){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){b=!0,a[g]=_;break}}if(!y&&!b)for(let g of l){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){v=!0,o[g]=_;break}}!y&&!b&&!v&&(d[p]=_)}return{filteredBody:d,extractedPathParams:n,extractedQueryParams:a,extractedHeaders:o}}var MwB=0,DwB=15e3,u0u=class{config;context;lambdaOrigin;venusOrigin;token;jwtPromise;organizationId;constructor(t,r,i,n){this.config={enabled:t.enabled,openaiApiKey:t.openaiApiKey,model:t.model??"gpt-4o-mini",maxRetries:t.maxRetries??MwB,requestTimeoutMs:t.requestTimeoutMs??DwB,styleInstructions:t.styleInstructions},this.context=r;let a="https://ykq45y6fvnszd35iv5yuuatkze0rpwuz.lambda-url.us-east-1.on.aws";if(!a)throw new Error("DEFAULT_FDR_LAMBDA_DOCS_ORIGIN environment variable is not set. AI example enhancement requires this to be configured.");this.lambdaOrigin=a,this.venusOrigin="https://venus.buildwithfern.com",this.token=i,this.organizationId=n}async getJwt(){return this.jwtPromise==null&&(this.jwtPromise=this.fetchJwtFromVenus()),this.jwtPromise}async fetchJwtFromVenus(){this.context.logger.debug("Fetching JWT from Venus for AI example enhancement"),this.context.logger.debug(`Token type: ${this.token.type}`),this.context.logger.debug(`Token value (first 10 chars): ${this.token.value.substring(0,10)}...`),this.context.logger.debug(`Token value starts with 'fern_': ${this.token.value.startsWith("fern_")}`),this.context.logger.debug(`Venus origin: ${this.venusOrigin}`),this.context.logger.debug(`Organization ID: ${this.organizationId}`);let t=await fetch(`${this.venusOrigin}/auth/jwt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token.value}`},body:JSON.stringify({organizationId:this.organizationId}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let i=await t.text();throw new Error(`Failed to fetch JWT from Venus: ${t.status} ${i||t.statusText}`)}let r=await t.json();return this.context.logger.debug(`Successfully obtained JWT from Venus (expires at ${r.expiresAt})`),r.token}async enhanceExample(t){if(!this.config.enabled)return{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};if(await Lgn(`${this.venusOrigin}/health`,this.context.logger))return this.context.logger.debug("Skipping AI example enhancement in air-gapped environment"),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};let i;try{i=await this.getJwt()}catch(o){return this.context.logger.warn(`Failed to obtain JWT from Venus: ${o}. AI example enhancement will be skipped.`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}let n,a=this.config.maxRetries+1;for(let o=1;o<=a;o++)try{this.context.logger.debug(`Enhancing example for ${t.method} ${t.endpointPath} via lambda (attempt ${o}/${a})`);let c={method:t.method,endpointPath:t.endpointPath,organizationId:t.organizationId,operationSummary:t.operationSummary,operationDescription:t.operationDescription,originalRequestExample:t.originalRequestExample,originalResponseExample:t.originalResponseExample,openApiSpec:t.openApiSpec,exampleStyleInstructions:t.exampleStyleInstructions??this.config.styleInstructions};this.context.logger.debug(`Sending to enhanceExamples: ${JSON.stringify({...c,openApiSpec:t.openApiSpec?`[OpenAPI spec present: ${t.openApiSpec.length} chars]`:"[No OpenAPI spec]"},null,2)}`);let d=await fetch(`${this.lambdaOrigin}/v2/registry/ai/enhance-example`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(c),signal:AbortSignal.timeout(this.config.requestTimeoutMs)});if(!d.ok){let u=await d.text();throw new Error(`Lambda returned ${d.status}: ${u||d.statusText}`)}let s=await d.json();return{enhancedRequestExample:s.enhancedRequestExample??t.originalRequestExample,enhancedResponseExample:s.enhancedResponseExample??t.originalResponseExample}}catch(c){if(n=c,this.context.logger.warn(`Attempt ${o} failed to enhance example: ${c}`),o<a){let d=Math.min(1e3*Math.pow(2,o-1),1e4);await new Promise(s=>setTimeout(s,d))}}return this.context.logger.error(`Failed to enhance example after ${a} attempts: ${n?.message}`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}};var Jca=class e{static instance;currentApiId;queue=[];progress=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}create(t,r,i){let n=`${t}-${Date.now()}-${Math.random()}`;return this.progress.set(n,{apiName:t,completed:0,total:r,endpointsSample:i}),this.queue.push(n),this.currentApiId||(this.currentApiId=n,this.updateSpinnerStatus()),n}update(t,r){let i=this.progress.get(t);i&&(i.completed=r,t===this.currentApiId&&this.updateSpinnerStatus())}finish(t){this.progress.delete(t);let r=this.queue.indexOf(t);r!==-1&&this.queue.splice(r,1),t===this.currentApiId&&(this.queue.length>0?(this.currentApiId=this.queue[0],this.updateSpinnerStatus()):(this.currentApiId=void 0,delete process.env.FERN_SPINNER_STATUS))}updateSpinnerStatus(){if(!this.currentApiId){delete process.env.FERN_SPINNER_STATUS;return}let t=this.progress.get(this.currentApiId);if(t){let r=`auto-generating examples for endpoints - ${t.apiName}`;t.endpointsSample&&(r+=` (${t.endpointsSample})`),r+=` - ${t.completed}/${t.total}`,process.env.FERN_SPINNER_STATUS=r}}};var s0u=require("fs/promises");async function BwB(e,t){let r=Sr.of(`${rn(e)}/ai_examples_override.yml`),i=[];try{let n=await(0,s0u.readFile)(r,"utf-8"),a=qi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,d]of Object.entries(o))if(d&&typeof d=="object"){for(let[s,u]of Object.entries(d))if(u&&typeof u=="object"&&"x-fern-examples"in u){let l=u["x-fern-examples"];if(Array.isArray(l)){for(let p of l)if(typeof p=="object"&&p!==null){let _=p;i.push({endpointPath:c,method:s.toUpperCase(),pathParameters:_["path-parameters"],queryParameters:_["query-parameters"],headers:_.headers,request:_.request,response:_.response})}}}}}t.logger.debug(`Parsed ${i.length} AI examples from ai_examples_override.yml`)}catch(n){t.logger.debug(`No existing ai_examples_override.yml found or error reading it: ${n}`)}return i}async function ptl({sourceFilePath:e,context:t}){let r=await BwB(e,t);if(r.length===0)return{validExamples:[],invalidExamples:[],totalExamples:0,validCount:0,invalidCount:0};let i;try{let s=await(0,s0u.readFile)(e,"utf-8");try{i=JSON.parse(s)}catch{i=qi.load(s)}}catch(s){return t.logger.warn(`Failed to read OpenAPI spec file: ${s}`),{validExamples:r,invalidExamples:[],totalExamples:r.length,validCount:r.length,invalidCount:0}}let n=new xEe({logger:t.logger}),a=new kUi({namespace:void 0,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:i,exampleGenerationArgs:{disabled:!1},errorCollector:n,enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,settings:R8t()}),o=new rvn({context:a}),{validExamples:c,invalidExamples:d}=o.validateAiExamples({aiExamples:r,spec:i});if(d.length>0){t.logger.info(`Found ${d.length} stale AI examples that need to be regenerated out of ${r.length} total`);for(let{example:s,validationResult:u}of d)t.logger.debug(`Stale AI example: ${s.method} ${s.endpointPath} - ${u.errors.map(l=>l.message).join(", ")}`)}return{validExamples:c,invalidExamples:d,totalExamples:r.length,validCount:c.length,invalidCount:d.length}}async function NQh({sourceFilePath:e,context:t}){let r=await ptl({sourceFilePath:e,context:t});if(r.invalidCount===0)return t.logger.debug("No invalid AI examples to remove"),{removedCount:0,remainingCount:r.totalExamples};let i=Sr.of(`${rn(e)}/ai_examples_override.yml`);try{let n=await(0,s0u.readFile)(i,"utf-8"),a=qi.load(n);if(!a||!a.paths)return{removedCount:0,remainingCount:r.totalExamples};let o=new Set(r.invalidExamples.map(({example:s})=>`${s.method.toLowerCase()}:${s.endpointPath}`));for(let[s,u]of Object.entries(a.paths))if(u&&typeof u=="object"){for(let l of Object.keys(u)){let p=`${l.toLowerCase()}:${s}`;o.has(p)&&delete u[l]}Object.keys(u).length===0&&delete a.paths[s]}let{writeFile:c}=await import("fs/promises"),d=qi.dump(a,{indent:2,lineWidth:-1,noRefs:!0});return await c(i,d,"utf-8"),t.logger.info(`Removed ${r.invalidCount} invalid AI examples from ai_examples_override.yml`),{removedCount:r.invalidCount,remainingCount:r.validCount}}catch(n){return t.logger.warn(`Failed to remove invalid AI examples: ${n}`),{removedCount:0,remainingCount:r.totalExamples}}}var $Ya=require("fs/promises");async function _tl(e,t){let r=Sr.of(`${rn(e)}/ai_examples_override.yml`),i=new Set;try{let n=await(0,$Ya.readFile)(r,"utf-8"),a=qi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,d]of Object.entries(o))if(d&&typeof d=="object")for(let s of Object.keys(d)){let u=`${s.toLowerCase()}:${c}`;i.add(u)}}t.logger.debug(`Loaded ${i.size} covered endpoints from ai_examples_override.yml`)}catch{t.logger.debug("No existing ai_examples_override.yml found or error reading it")}return i}async function c0u({enhancedExamples:e,sourceFilePath:t,context:r}){if(e.length===0){r.logger.debug("No enhanced examples to write");return}let i=new Map;for(let o of e){let c=i.get(o.endpoint)||[];c.push(o),i.set(o.endpoint,c)}let n={paths:{}};for(let[o,c]of i.entries()){let d=new Map;for(let s of c){let u=d.get(s.method.toLowerCase())||[];u.push(s),d.set(s.method.toLowerCase(),u)}n.paths[o]||(n.paths[o]={});for(let[s,u]of d.entries()){let l=u.map((_,h)=>{let y={},b={..._.pathParameters??{}},v={..._.queryParameters??{}},g={..._.headers??{}},m={...g};if(_.headerParameterNames)for(let B of _.headerParameterNames)B in m||(m[B]="");let O={};if(_.queryParameterNames)for(let B of _.queryParameterNames)O[B]=v[B]??"";let A={};if(_.pathParameterNames)for(let B of _.pathParameterNames)A[B]=b[B]??"";let j=_.requestBody;j!=null&&typeof j=="object"&&!Array.isArray(j)&&"body"in j&&(j=j.body);let M=bYi(j),w=M;if(M!==void 0){let{filteredBody:B,extractedPathParams:R,extractedQueryParams:T,extractedHeaders:q}=o0u(M,A,O,m);w=B;for(let[z,N]of Object.entries(R))N!=null&&N!==""&&(b[z]=N);for(let[z,N]of Object.entries(T))N!=null&&N!==""&&(v[z]=N);for(let[z,N]of Object.entries(q))N!=null&&N!==""&&(g[z]=N)}Object.keys(b).length>0&&(y["path-parameters"]=b),Object.keys(v).length>0&&(y["query-parameters"]=v),Object.keys(g).length>0&&(y.headers=g),w!==void 0&&!dtl(w)&&(y.request=w);let D=bYi(_.responseBody);return D!==void 0&&!dtl(D)&&(y.response={body:D}),y}),p=n.paths[o];p&&(p[s]={"x-fern-examples":l})}}let a=Sr.of(`${rn(t)}/ai_examples_override.yml`);try{let o={};try{let s=await(0,$Ya.readFile)(a,"utf-8"),u=qi.load(s);u&&typeof u=="object"&&(o=u)}catch{r.logger.debug("No existing ai_examples_override.yml found, creating new file")}let c={paths:{}};if(o.paths){for(let[s,u]of Object.entries(o.paths))if(u&&typeof u=="object"){c.paths[s]={};for(let[l,p]of Object.entries(u))p&&typeof p=="object"&&"x-fern-examples"in p&&(c.paths[s][l]={"x-fern-examples":p["x-fern-examples"]||[]})}}for(let[s,u]of Object.entries(n.paths)){c.paths[s]||(c.paths[s]={});for(let[l,p]of Object.entries(u))c.paths[s][l]?r.logger.debug(`Skipping ${l.toUpperCase()} ${s} - examples already exist in override file`):(c.paths[s][l]=p,r.logger.debug(`Adding new examples for ${l.toUpperCase()} ${s}`))}let d=qi.dump(c,{indent:2,lineWidth:-1,noRefs:!0});await(0,$Ya.writeFile)(a,d,"utf-8"),r.logger.debug(`AI enhanced examples written to: ${a}`)}catch(o){throw r.logger.warn(`Failed to write AI examples override file: ${o}`),o}}var htl=class{failureCount=0;failureThreshold=30;isOpen=!1;recordFailure(){this.failureCount++,this.failureCount>=this.failureThreshold&&(this.isOpen=!0)}recordSuccess(){this.failureCount=0,this.isOpen=!1}shouldSkip(){return this.isOpen}getFailureCount(){return this.failureCount}getThreshold(){return this.failureThreshold}},ytl=class{progressCallback;maxConcurrency;activeRequests=new Map;pendingQueue=[];results=new Map;stats={pending:0,active:0,completed:0,failed:0,totalStarted:0};completedSinceLastCallback=[];constructor(t,r){this.progressCallback=r,this.maxConcurrency=t}async processAll(t){for(this.pendingQueue=[...t],this.stats.pending=this.pendingQueue.length,this.stats.totalStarted=this.pendingQueue.length;this.pendingQueue.length>0&&this.activeRequests.size<this.maxConcurrency;)this.startNext();for(;this.activeRequests.size>0;){let r=Array.from(this.activeRequests.entries()).map(([a,o])=>o.promise.then(c=>({id:a,result:c}))),{id:i,result:n}=await Promise.race(r);await this.handleCompletion(i,n),this.pendingQueue.length>0&&this.startNext()}return this.results}startNext(){if(this.pendingQueue.length===0||this.activeRequests.size>=this.maxConcurrency)return;let t=this.pendingQueue.shift();if(!t)return;let r=`req-${Date.now()}-${Math.random()}`,i=t(),n={id:r,promise:i,startTime:Date.now()};this.activeRequests.set(r,n),this.stats.pending=this.pendingQueue.length,this.stats.active=this.activeRequests.size}async handleCompletion(t,r){this.activeRequests.get(t)&&this.activeRequests.delete(t),r.success?(this.stats.completed++,this.results.set(r.endpointKey,{enhancedReq:r.enhancedReq,enhancedRes:r.enhancedRes,extractedHeaders:r.extractedHeaders,extractedPathParams:r.extractedPathParams,extractedQueryParams:r.extractedQueryParams})):this.stats.failed++,this.stats.active=this.activeRequests.size,this.completedSinceLastCallback.push(r),this.progressCallback&&(this.progressCallback({...this.stats},[...this.completedSinceLastCallback]),this.completedSinceLastCallback=[])}getStats(){return{...this.stats}}};function IwB(e){try{try{let t=JSON.parse(e);return!!(t.openapi||t.swagger)}catch{let t=rZn(e);return!!(t?.openapi||t?.swagger)}}catch{return!1}}function UQh(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}function vtl(e,t,r,i){try{let n=JSON.parse(e);if(!n.paths)return[];let a=Object.keys(n.paths),o=UQh(t,a);if(!o)return[];let c=n.paths[o];if(!c)return[];let d=c[r.toLowerCase()];if(!d)return[];let s=[],u=[...c.parameters??[],...d.parameters??[]];for(let l of u)"$ref"in l||l.in===i&&s.push(l.name);return s}catch{return[]}}function CwB(e,t,r){return vtl(e,t,r,"header")}function qwB(e,t,r){return vtl(e,t,r,"query")}function TwB(e,t,r){return vtl(e,t,r,"path")}async function RwB(e,t,r){try{let i;try{i=JSON.parse(e)}catch{i=rZn(e)}if(!i.openapi||!i.paths){r.logger.debug("Invalid OpenAPI spec structure, skipping pruning");return}let n=Object.keys(i.paths);r.logger.debug(`OpenAPI spec contains ${n.length} paths`);let a=[];for(let l of t){let p=UQh(l.path,n);p?(a.push({path:p,method:l.method.toLowerCase()}),r.logger.debug(`Mapped ${l.path} to OpenAPI path: ${p}`)):r.logger.debug(`No matching OpenAPI path found for ${l.path}`)}if(a.length===0){r.logger.debug("No endpoints matched in OpenAPI spec");return}let c=new JYa({document:i,endpoints:a}).prune();r.logger.debug(`Pruned OpenAPI spec for batch: ${c.statistics.originalEndpoints} \u2192 ${c.statistics.prunedEndpoints} endpoints, ${c.statistics.originalSchemas} \u2192 ${c.statistics.prunedSchemas} schemas`);let d=JSON.stringify(c.document,null,2);if(d.length>15e5){r.logger.debug(`Pruned OpenAPI spec still too large (${d.length} characters), skipping spec context for AI enhancement`);return}r.logger.debug(`Pruned spec size: ${d.length} characters (within limit)`);let s=a.map(l=>`${(l.method||"unknown").toUpperCase()}_${l.path.replace(/\//g,"_").replace(/[{}]/g,"")}`),u=`batch_${a.length}endpoints_${s.join("_").substring(0,100)}_pruned_spec.yaml`;return d}catch(i){return r.logger.debug(`Failed to prune OpenAPI spec: ${i}. Using original spec.`),e}}async function Yca(e,t,r,i,n,a,o){if(!t.enabled)return r.logger.debug("AI example enhancement is disabled"),e;try{return await zwB(e,t,r,i,n,a,o)}catch(c){return r.logger.debug(`AI example enhancement failed with error: ${c}. Continuing with original API definition to prevent CLI crash.`),r.logger.debug(`Full AI enhancement error stack: ${c instanceof Error?c.stack:String(c)}`),e}}async function zwB(e,t,r,i,n,a,o){let c=new u0u(t,r,i,n),d=new htl,s,u=new Set;if(a!=null)try{let b=await(0,btl.readFile)(a,"utf-8");if(!IwB(b))return r.logger.debug("Non-OpenAPI spec detected, skipping AI example enhancement"),e;s=b,r.logger.debug(`Loaded OpenAPI spec (${b.length} characters) for AI enhancement`);let v=await _tl(a,r);try{let g=await ptl({sourceFilePath:a,context:r});if(g.invalidCount>0){for(let{example:O}of g.invalidExamples){let A=`${O.method.toLowerCase()}:${O.endpointPath}`;u.add(A)}let m=await NQh({sourceFilePath:a,context:r});r.logger.info(`Removed ${m.removedCount} stale AI examples, ${u.size} endpoints will be regenerated`)}else r.logger.debug("No stale AI examples found to remove")}catch(g){r.logger.debug(`Failed to clean up stale AI examples: ${g}`)}}catch(b){r.logger.debug(`Failed to read OpenAPI spec file: ${b}`)}let l=new Set;if(a!=null){let b=await _tl(a,r);for(let v of b)u.has(v)||l.add(v);u.size>0&&r.logger.debug(`Coverage adjusted: ${b.size} total, ${l.size} preserved, ${u.size} marked for regeneration`)}let p={count:0,total:0},_=[],h=await NwB(e,c,r,n,p,_,l,u,s,a,o,d);if(_.length>0&&a!=null)try{await c0u({enhancedExamples:_,sourceFilePath:a,context:r})}catch(b){r.logger.debug(`Failed to write AI examples override file: ${b}`)}let y=LQh(h);return r.logger.debug(`AI Enhancement Summary - Total endpoints in API: ${y}, Enhanced: ${p.count}/${p.total}, Covered: ${l.size}`),h}async function NwB(e,t,r,i,n,a,o,c,d,s,u,l){let p=[];for(let[A,j]of Object.entries(e.subpackages)){let M=FQh(j,o,c,r);p.push(...M.map(w=>({...w,packageId:A})))}let _=FQh(e.rootPackage,o,c,r);p.push(..._.map(A=>({...A,packageId:"root"})));let h=LQh(e);n.total+=p.length,r.logger.debug(`AI Examples Enhancement: ${p.length} endpoints need enhancement out of ${h} total endpoints (${o.size} already covered)`),r.logger.debug(`Collected ${p.length} work items across all packages`);let y=Jca.getInstance(),b=y.create(u||"API",p.length),v={count:0,total:p.length},g=await FwB(p,t,r,i,n,a,d,s,b,v,l);y.finish(b);let m={};for(let[A,j]of Object.entries(e.subpackages)){let M=QQh(j,g);m[A]=M}let O=QQh(e.rootPackage,g);return r.logger.debug(`AI Examples Enhancement Complete: ${v?.count||0}/${p.length} endpoints enhanced successfully (${h} total endpoints in API)`),{...e,subpackages:m,rootPackage:O}}function LQh(e){let t=0;t+=e.rootPackage.endpoints.length;for(let r of Object.values(e.subpackages))t+=r.endpoints.length;return t}function FQh(e,t,r,i){let n=[],a=new Set,o={totalEndpoints:e.endpoints.length,alreadyCovered:0,notAutogenerated:0,noExistingExamples:0,alreadyProcessed:0,noExamples:0,processed:0};for(let c of e.endpoints){let d=c;if(!LwB(d))for(let u of d.examples){let l=`${d.method.toLowerCase()}:${u.path}`;if(a.has(l)){o.alreadyProcessed++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: already processed in this run`);continue}let p=r?.has(l);if(!p&&t.has(l)){o.alreadyCovered++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: already covered (has AI-enhanced examples)`);continue}if(!p&&!UwB(u,i,l)){o.notAutogenerated++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: has human-written examples (not auto-generated)`);continue}let _=$ca(u.requestBodyV3),h=$ca(u.responseBodyV3);if(!p&&!_&&!h){o.noExistingExamples++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: no existing request/response examples to enhance`);continue}n.push({endpoint:d,example:u,endpointKey:l}),o.processed++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} selected for AI enhancement`),a.add(l);break}}return i&&(i.logger.debug(`Endpoint Filtering Results: ${o.processed}/${o.totalEndpoints} endpoints selected for AI enhancement`),i.logger.debug(`Filtering breakdown - Already covered: ${o.alreadyCovered}, Not auto-generated: ${o.notAutogenerated}, No existing examples: ${o.noExistingExamples}, No examples at all: ${o.noExamples}, Already processed: ${o.alreadyProcessed}, Selected: ${o.processed}`)),n}async function FwB(e,t,r,i,n,a,o,c,d,s,u){let l=parseInt(process.env.FERN_AI_MAX_CONCURRENT||"25",10);if(r.logger.debug(`Processing ${e.length} endpoints with max ${l} concurrent Lambda calls using rolling window queue`),u?.shouldSkip())return r.logger.debug(`Circuit breaker is open after ${u.getFailureCount()} failures (threshold: ${u.getThreshold()}). Skipping AI enhancement for remaining endpoints.`),new Map;let p=0,_=0,h=Math.max(10,Math.floor(e.length/20)),y=(O,A)=>{if(d&&s&&Jca.getInstance().update(d,O.completed),u?.shouldSkip()){r.logger.debug(`Circuit breaker opened during processing. Processed ${O.completed} endpoints.`);return}c&&a.length>0&&O.completed-_>=h&&(c0u({enhancedExamples:a,sourceFilePath:c,context:r}).then(()=>{r.logger.debug(`Saved ${a.length} examples after ${O.completed} completions`)}).catch(M=>{r.logger.debug(`Failed to save incremental results: ${M}`)}),_=O.completed)},b=e.map((O,A)=>async()=>{try{if(u?.shouldSkip())return{endpointKey:O.endpointKey,success:!1,error:"Circuit breaker is open"};let j=await QwB(O,t,r,i,n,a,o,c,d,s,A+1,u);return j?{endpointKey:j.endpointKey,enhancedReq:j.enhancedReq,enhancedRes:j.enhancedRes,extractedHeaders:j.extractedHeaders,extractedPathParams:j.extractedPathParams,extractedQueryParams:j.extractedQueryParams,success:!0}:{endpointKey:O.endpointKey,success:!1,error:"processEndpoint returned null"}}catch(j){return r.logger.debug(`Work item factory error for ${O.endpointKey}: ${j}`),{endpointKey:O.endpointKey,success:!1,error:String(j)}}}),v=new ytl(l,y),g=await v.processAll(b);if(c&&a.length>0)try{await c0u({enhancedExamples:a,sourceFilePath:c,context:r}),r.logger.debug(`Final save: ${a.length} examples saved`)}catch(O){r.logger.debug(`Failed to save final results: ${O}`)}let m=v.getStats();return r.logger.debug(`Completed processing: ${m.completed} succeeded, ${m.failed} failed`),g}async function QwB(e,t,r,i,n,a,o,c,d,s,u,l){let p=e.endpointKey;r.logger.debug(`Processing endpoint ${u}: ${e.endpoint.method} ${e.example.path}`);let _;o&&(_=await RwB(o,[{path:e.example.path,method:e.endpoint.method}],r));let h={method:e.endpoint.method,endpointPath:e.example.path,organizationId:i,operationSummary:e.endpoint.summary,operationDescription:e.endpoint.description,originalRequestExample:$ca(e.example.requestBodyV3),originalResponseExample:$ca(e.example.responseBodyV3),pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,openApiSpec:_};try{let y=await t.enhanceExample(h);l?.recordSuccess();let b=y.enhancedRequestExample!==h.originalRequestExample,v=y.enhancedResponseExample!==h.originalResponseExample;if(b||v){let g=_?CwB(_,e.example.path,e.endpoint.method):[],m=_?qwB(_,e.example.path,e.endpoint.method):[],O=_?TwB(_,e.example.path,e.endpoint.method):[],A={...e.example.headers??{}};if(g.length>0)for(let $ of g)$ in A||(A[$]="");let j={};for(let $ of m)j[$]=e.example.queryParameters?.[$]??"";let M={};for(let $ of O)M[$]=e.example.pathParameters?.[$]??"";let w=bYi(y.enhancedRequestExample),{filteredBody:D,extractedPathParams:B,extractedQueryParams:R,extractedHeaders:T}=o0u(w,M,j,A),q={...e.example.headers??{}};for(let[$,de]of Object.entries(T))de!=null&&de!==""&&(q[$]=de);let z={...e.example.pathParameters??{}};for(let[$,de]of Object.entries(B))de!=null&&de!==""&&(z[$]=de);let N={...e.example.queryParameters??{}};for(let[$,de]of Object.entries(R))de!=null&&de!==""&&(N[$]=de);let H={endpoint:e.example.path,method:e.endpoint.method,pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,requestBody:b?y.enhancedRequestExample:void 0,responseBody:v?y.enhancedResponseExample:void 0,headerParameterNames:g.length>0?g:void 0,queryParameterNames:m.length>0?m:void 0,pathParameterNames:O.length>0?O:void 0};return a.push(H),n.count++,s&&s.count++,r.logger.debug(`Successfully enhanced ${e.endpoint.method} ${e.example.path}`),d&&s&&Jca.getInstance().update(d,s.count),{endpointKey:p,enhancedReq:D,enhancedRes:y.enhancedResponseExample,extractedHeaders:Object.keys(q).length>0?q:void 0,extractedPathParams:Object.keys(z).length>0?z:void 0,extractedQueryParams:Object.keys(N).length>0?N:void 0}}return r.logger.debug(`No changes needed for ${e.endpoint.method} ${e.example.path}`),{endpointKey:p,enhancedReq:y.enhancedRequestExample,enhancedRes:y.enhancedResponseExample}}catch(y){l?.recordFailure(),r.logger.debug(`Endpoint ${e.endpoint.method} ${e.example.path} failed: ${y}`)}return r.logger.debug(`Failed to enhance ${e.endpoint.method} ${e.example.path}`),null}function QQh(e,t){let r=e.endpoints.map(i=>{let n=i,a=n.examples.map(o=>{let c=`${n.method.toLowerCase()}:${o.path}`,d=t.get(c);if(d){let s={...o};if(d.enhancedReq!==void 0)if(s.requestBody=d.enhancedReq,o.requestBodyV3)if(typeof o.requestBodyV3.value=="object"&&o.requestBodyV3.value!==null&&!Array.isArray(o.requestBodyV3.value)&&Object.values(o.requestBodyV3.value).some(l=>ftl(l))){let l=d.enhancedReq,p=o.requestBodyV3.value,_={};for(let[h,y]of Object.entries(p))h in l?_[h]={...y,value:l[h]}:_[h]=y;s.requestBodyV3={...o.requestBodyV3,value:_}}else s.requestBodyV3={...o.requestBodyV3,value:d.enhancedReq};else s.requestBodyV3={type:"json",value:d.enhancedReq};return d.enhancedRes!==void 0&&(s.responseBody=d.enhancedRes,s.responseBodyV3=o.responseBodyV3?{...o.responseBodyV3,value:d.enhancedRes}:{type:"json",value:d.enhancedRes}),d.extractedHeaders!==void 0&&(s.headers={...o.headers??{},...d.extractedHeaders}),d.extractedPathParams!==void 0&&(s.pathParameters={...o.pathParameters??{},...d.extractedPathParams}),d.extractedQueryParams!==void 0&&(s.queryParameters={...o.queryParameters??{},...d.extractedQueryParams}),s}return o});return{...i,examples:a}});return{...e,endpoints:r}}function UwB(e,t,r){let n=$ca(e.requestBodyV3),a=$ca(e.responseBodyV3),o=l0u(n,t,`${r}:request`),c=l0u(a,t,`${r}:response`),d=o.total+c.total,s=o.autogenerated+c.autogenerated;if(d===0)return!0;let u=s/d,l=u>=.3;return t&&r&&(l?t.logger.debug(`Endpoint ${r} considered auto-generated: ${s}/${d} (${(u*100).toFixed(1)}%) values are generic`):t.logger.debug(`Endpoint ${r} flagged as human-written: only ${s}/${d} (${(u*100).toFixed(1)}%) values are generic (threshold: ${.3*100}%)`)),l}function l0u(e,t,r){if(e==null)return{autogenerated:0,total:0};if(typeof e=="string"){let i=e===xn.STRING||e===xn.BASE64||e===xn.DATE||e===xn.DATE_TIME||e===xn.UUID||e===xn.BIG_INTEGER||xn.SAMPLE_STRINGS.includes(e)||e==="";return!i&&t&&r&&t.logger.debug(`Non-generic string found at ${r}: "${e}"`),{autogenerated:i?1:0,total:1}}if(typeof e=="number"){let i=e===xn.DOUBLE||e===xn.FLOAT||e===xn.INT||e===xn.INT64||e===xn.UINT||e===xn.UINT64||e===0;return!i&&t&&r&&t.logger.debug(`Non-generic number found at ${r}: ${e}`),{autogenerated:i?1:0,total:1}}if(typeof e=="boolean"){let i=e===xn.BOOLEAN;return!i&&t&&r&&t.logger.debug(`Non-generic boolean found at ${r}: ${e}`),{autogenerated:i?1:0,total:1}}if(Array.isArray(e)){if(e.length===0)return{autogenerated:0,total:0};let i=0,n=0;return e.forEach((a,o)=>{let c=l0u(a,t,r?`${r}[${o}]`:void 0);i+=c.autogenerated,n+=c.total}),{autogenerated:i,total:n}}if(typeof e=="object"){let i=0,n=0;return Object.entries(e).forEach(([a,o])=>{let c=l0u(o,t,r?`${r}.${a}`:void 0);i+=c.autogenerated,n+=c.total}),{autogenerated:i,total:n}}return t&&r&&t.logger.debug(`Unknown type at ${r}: ${typeof e} = ${e}`),{autogenerated:0,total:1}}function LwB(e){try{let t=e;if(t.v2Examples?.userSpecifiedExamples&&typeof t.v2Examples.userSpecifiedExamples=="object"){let r=t.v2Examples.userSpecifiedExamples;return Object.keys(r).length>0}if(t.v2Responses?.responses){for(let r of t.v2Responses.responses)if(r.body?.v2Examples?.userSpecifiedExamples&&typeof r.body.v2Examples.userSpecifiedExamples=="object"){let i=r.body.v2Examples.userSpecifiedExamples;if(Object.keys(i).length>0)return!0}}return!1}catch{return!1}}function $ca(e){if(e)switch(e.type){case"json":case"stream":case"sse":return e.value;case"filename":return;default:return e.value}}function VQh({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];return WQh({scheme:i,playgroundConfig:t,context:r})}}function WQh({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:e.password.originalName,usernameName:e.username.originalName,description:e.docs,passwordAlwaysEmpty:void 0};case"bearer":return{type:"bearerAuth",tokenName:e.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:e.name.wireValue,nameOverride:e.name.name.originalName,prefix:e.prefix,description:e.docs};case"oauth":{let i=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(n=>n.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:ni.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:ni.JqString(i),headerName:e.configuration.tokenHeader,tokenPrefix:e.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let i=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(i)return i.responseProperty.propertyPath!=null&&i.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:i.responseProperty.property.name.wireValue,description:e.docs};let n=e.tokenEndpoint.authenticatedRequestHeaders[0];return n?{type:"header",headerWireValue:n.headerName,prefix:n.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:vt(e)}}function GQh({auth:e,playgroundConfig:t,context:r}){let i={};for(let n of e.schemes){let a=WQh({scheme:n,playgroundConfig:t,context:r});a!=null&&(i[ni.AuthSchemeId(n.key)]=a)}return i}function HQh(e){return e._visit({alias:t=>({type:"alias",value:ib(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:RM(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>ni.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:ni.PropertyKey(r.name.wireValue),valueType:ib(r.valueType),availability:RM(r.availability),propertyAccess:r.propertyAccess})),extraProperties:KwB(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),availability:RM(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?RM(i.availability):void 0,additionalProperties:Ar.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[ni.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:ni.PropertyKey(n.name.wireValue),valueType:ib(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:ib(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName??r.type.name.originalName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function ib(e){return e._visit({container:t=>Ar.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:ib(r),minItems:void 0,maxItems:void 0}),map:({keyType:r,valueType:i})=>({type:"map",keyType:ib(r),valueType:ib(i),minProperties:void 0,maxProperties:void 0}),optional:r=>({type:"optional",itemType:ib(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:ib(r)}),set:r=>({type:"set",itemType:ib(r),minItems:void 0,maxItems:void 0}),literal:r=>Ar.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:ni.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Ar.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>WwB(t.v2),float:()=>xQh(t.v2),double:()=>xQh(t.v2),string:()=>VwB(t.v2),long:()=>GwB(t.v2),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>xwB(t.v2),uint64:()=>HwB(t.v2),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function VwB(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function WwB(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="integer"?e.default:void 0}}function xQh(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="double"?e.default:void 0}}function GwB(e){let t=e!=null&&e.type==="long"?e.validation:void 0;return{type:"long",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="long"?e.default:void 0}}function xwB(e){let t=e!=null&&e.type==="uint"?e.validation:void 0;return{type:"uint",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint"?e.default:void 0}}function HwB(e){let t=e!=null&&e.type==="uint64"?e.validation:void 0;return{type:"uint64",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint64"?e.default:void 0}}function KwB(e){return typeof e=="boolean"?e?ii.unknown():void 0:typeof e=="string"?{type:"id",value:ni.TypeId(e),default:void 0}:ib(e)}function mtl(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?$wB(r,t):[],webhooks:i!=null?JwB(i):[],websockets:n!=null?[YwB(n,t)]:[],types:e.types.map(a=>ni.TypeId(a)),subpackages:e.subpackages.map(a=>ni.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?ni.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0,graphqlOperations:void 0}}function JwB(e){return e.map(t=>{let r=[];if(t.v2Examples!=null){for(let[i,n]of Object.entries(t.v2Examples.userSpecifiedExamples))r.push({name:n.name??i,payload:n.payload});for(let[i,n]of Object.entries(t.v2Examples.autogeneratedExamples))r.push({name:n.name??i,payload:n.payload})}else r.push(...t.examples?.map(i=>({name:i.name?.originalName,payload:i.payload.jsonExample}))??[]);return{description:t.docs??void 0,id:ni.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Rfn(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:ib(i.valueType),availability:RM(i.availability)})),payload:aEB(t.payload,t.fileUploadPayload),examples:r,responses:t.responses?.map(Otl).filter(us)}})}function $wB(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,u=Object.values(d).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(d))c=JQh({shouldUseExampleName:_.displayName!=null||u,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(s))c=JQh({shouldUseExampleName:l,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>gtl({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(us));else if(n!=null){let c=gtl({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=joa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=gtl({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:RM(i.availability??e.availability),auth:i.auth,authV2:XwB(i.security),multiAuth:ZwB(i.security),description:i.docs??void 0,method:rEB(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?ni.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?kwB({environmentsConfig:t.environments,endpoint:i}):void 0,id:ni.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Rfn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:ni.PropertyKey(c.name.originalName),type:ib(c.valueType),availability:void 0,explode:c.explode})),parts:[...Xca(i.basePath),...Xca(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:ni.PropertyKey(c.name.originalName),type:ib(c.valueType),availability:void 0,explode:c.explode})),parts:[...t.basePath!=null?Xca(t.basePath):[],...Xca(e.basePath),...Xca(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability),explode:c.explode})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability)})),responseHeaders:i.responseHeaders?.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability)})),request:i.requestBody!=null?KQh(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(KQh).filter(us)},response:i.response!=null?Otl(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(Otl).filter(us)},errors:void 0,errorsV2:iEB(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground};r.push(o)}return r}function YwB(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.entries(e.v2Examples.userSpecifiedExamples),n=Object.entries(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];if(a!=null){let[o,c]=a;r.push({name:o,description:"",path:c.baseUrl??"",pathParameters:c.pathParameters??{},queryParameters:c.queryParameters??{},headers:c.headers??{},messages:c.messages?.map(d=>({type:ni.api.v1.WebSocketMessageId(d.type),body:d.body}))??[]})}}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[ni.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:ni.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:RM(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?ni.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?eEB({environmentsConfig:t.environments,channel:e}):[],id:ni.WebSocketId(e.name.originalName),name:e.displayName??Rfn(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:ni.PropertyKey(i.name.originalName),type:ib(i.valueType),availability:void 0,explode:i.explode})),parts:Xca(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:ib(i.valueType),description:i.docs,availability:RM(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:ib(i.valueType),availability:RM(i.availability),explode:i.explode})),messages:e.messages.map(i=>({type:ni.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:uEB(i.body),description:i.docs,availability:RM(i.availability)})),examples:r}}function XwB(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>ni.AuthSchemeId(r))}function ZwB(e){if(e!=null)return e.length===0?[]:e.map(t=>({schemes:Object.keys(t).map(r=>ni.AuthSchemeId(r))}))}function RM(e){if(e!=null)switch(e.status){case"DEPRECATED":return ni.Availability.Deprecated;case"PRE_RELEASE":return ni.Availability.Beta;case"GENERAL_AVAILABILITY":return ni.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return ni.Availability.Beta;default:vt(e.status)}}function kwB({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:ni.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(o=>r.environments.map(c=>{let d=c.urls[o];if(d==null)throw new Error(`Encountered undefined server name "${o}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${c.id} to contain url for ${o}`);return{id:ni.EnvironmentId(o),baseUrl:d}})).filter((o,c,d)=>c===d.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[i];if(o==null)throw new Error(`Encountered undefined server name "${i}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${i}`);return{id:ni.EnvironmentId(a.id),baseUrl:o}});default:vt(r)}}function eEB({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ni.EnvironmentId(n.id),baseUrl:tEB(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${n.id} to contain url for ${i}`);return{id:ni.EnvironmentId(n.id),baseUrl:a}});default:vt(r)}}function tEB(e,t){return e.replace(/^[^:]+/,t)}function rEB(e){return Ar.http.HttpMethod._visit(e,{get:()=>ni.HttpMethod.Get,post:()=>ni.HttpMethod.Post,put:()=>ni.HttpMethod.Put,patch:()=>ni.HttpMethod.Patch,delete:()=>ni.HttpMethod.Delete,head:()=>ni.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function Xca(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:ni.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function KQh(e){let t=Ar.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??tm.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>ni.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),availability:RM(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??tm.APPLICATION_JSON,shape:{type:"reference",value:ib(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:o=>({type:"file",key:ni.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:ni.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:ni.PropertyKey(n.name.wireValue),valueType:ib(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:RM(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(us)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function Otl(e){let t=e.docs,r;return e.body!=null&&(r=Ar.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:ib(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:ib(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:ib(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function iEB(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:ib(n.type)},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:sEB(n,t),headers:n.headers!=null&&n.headers.length>0?n.headers.map(a=>({description:a.docs??void 0,key:a.name.wireValue,type:ib(a.valueType),availability:RM(a.availability)})):void 0})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:ni.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:ni.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:ib(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs})),headers:n.headers!=null&&n.headers.length>0?n.headers.map(o=>({description:o.docs??void 0,key:o.name.wireValue,type:ib(o.valueType),availability:RM(o.availability)})):void 0})}}return r}function JQh({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i,irService:n,ir:a}){if(r==null)return;let o=s=>{if(s.valueType.type==="container"&&s.valueType.container.type==="literal")return s.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}});if(s.valueType.type==="container"&&s.valueType.container.type==="optional"&&s.valueType.container.optional.type==="container"&&s.valueType.container.optional.container.type==="literal")return s.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})},c={};a.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),n.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),i.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)});let d=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let u={...r.request?.headers??{}};for(let[l,p]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=p);return u})(),requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if(yl(r.request.requestBody)){let l=r.request.requestBody;for(let p of s.properties)p._visit({file:_=>{let h=l[_.key.wireValue];if(_.type==="file")u[_.key.wireValue]={type:"filename",value:typeof h=="string"?h:"<file1>"};else if(_.type==="fileArray"){let y=(Array.isArray(h)?h:[h]).filter(b=>typeof b=="string");u[_.key.wireValue]={type:"filenames",value:y}}},bodyProperty:_=>{if(_.style==="exploded"){let h=l[_.name.wireValue];u[_.name.wireValue]={type:"exploded",value:Array.isArray(h)?h:[h]}}else u[_.name.wireValue]={type:"json",value:l[_.name.wireValue]}},_other:kje})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:d??void 0,responseBodyV3:d!=null?r.response?.body?._visit({json:s=>({type:"json",value:s}),stream:s=>Array.isArray(s)&&s.length>0&&s.every(nEB)?{type:"sse",value:s}:{type:"stream",value:s},error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(s=>({name:s.name,description:s.docs??void 0,install:void 0,language:s.language,code:s.code})).filter(us)}}function nEB(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function gtl({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?d=c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(d=c.valueType.container.optional.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}})),d!=null)return{name:c.name,value:{jsonExample:d,shape:Ar.ExampleTypeReferenceShape.primitive(Ar.ExamplePrimitive.string({original:d}))}}}).filter(us),a=e?.example??t?.example;if(a==null)return;let{codeSamples:o}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[ni.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let d={};if(yl(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let p=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof p=="string"?p:"<file1>"};else if(l.type==="fileArray"){let _=(Array.isArray(p)?p:[p]).filter(h=>typeof h=="string");d[l.key.wireValue]={type:"filenames",value:_}}},bodyProperty:l=>{if(l.style==="exploded"){let p=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(p)?p:[p]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:kje})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Ar.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:u})=>({event:s,data:u.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:o?.map(c=>Yve._visit(c,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(us)}}function aEB(e,t){return t!=null?{type:{type:"formData",name:t.name.originalName,description:t.docs??void 0,availability:void 0,properties:t.properties.map(r=>r._visit({file:i=>{let n=i._visit({file:a=>({type:"file",key:ni.PropertyKey(a.key.wireValue),isOptional:a.isOptional,contentType:a.contentType,description:a.docs??void 0,availability:void 0}),fileArray:a=>({type:"fileArray",key:ni.PropertyKey(a.key.wireValue),isOptional:a.isOptional,contentType:a.contentType,description:a.docs??void 0,availability:void 0}),_other:()=>{}});if(n!=null)return{type:"file",value:n}},bodyProperty:i=>({type:"bodyProperty",key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),contentType:i.contentType,description:i.docs??void 0,availability:RM(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(us)},description:t.docs??void 0}:oEB(e)}function oEB(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>ni.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ni.PropertyKey(t.name.wireValue),valueType:ib(t.valueType),availability:RM(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:ib(e.payloadType)},description:e.docs};default:vt(e)}}function uEB(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>ni.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ni.PropertyKey(t.name.wireValue),valueType:ib(t.valueType),availability:RM(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:ib(e.bodyType)};default:vt(e)}}function sEB(e,t){let r=e.v2Examples?.userSpecifiedExamples,i=e.v2Examples?.autogeneratedExamples,n=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(i!=null&&Object.keys(i).length>0)return Object.entries(i).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(n.length>0)return n.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}));let a=cEB(e,t);return a!=null?[a]:[]}function cEB(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,i=t.types[r];if(i==null||i.shape.type!=="object")return;let n={},a=!1;for(let o of i.shape.properties){let c=o.name.wireValue,d=o.v2Examples;if(d?.userSpecifiedExamples!=null){let s=Object.values(d.userSpecifiedExamples);if(s.length>0){n[c]=s[0],a=!0;continue}}if(d?.autogeneratedExamples!=null){let s=Object.values(d.autogeneratedExamples);if(s.length>0){n[c]=s[0];continue}}}if(a)return{name:void 0,responseBody:{type:"json",value:n},description:void 0}}function Tx({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:mtl(e.rootPackage,e),apiName:e.apiName.originalName,auth:VQh({auth:e.auth,playgroundConfig:r,context:i}),authSchemes:GQh({auth:e.auth,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:RM(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:ib(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))n.types[ni.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:HQh(o.shape),availability:RM(o.availability),displayName:o.name.displayName};for(let[a,o]of Object.entries(e.subpackages)){let c=o.service!=null?e.services[o.service]:void 0;n.subpackages[ni.api.v1.SubpackageId(a)]={subpackageId:ni.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...mtl(o,e)}}return n}async function Atl({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:o,aiEnhancerConfig:c}){let d=ES({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new wS(r,t)}),s=B3t({token:i.value}),u=Tx({ir:d,snippetsConfig:a,playgroundConfig:o,context:r});if(c){let h=t.getSources().find(y=>y.type==="openapi")?.absoluteFilePath;u=await Yca(u,c,r,i,e,h,d.apiName.originalName)}let l=await s.api.v1.register.registerApiDefinition({orgId:ni.OrgId(e),apiId:ni.ApiId(d.apiName.originalName),definition:u});if(l.ok)return r.logger.debug(`Registered API Definition ${l.body.apiDefinitionId}`),{id:l.body.apiDefinitionId,ir:d};switch(l.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",l.error)}}var lEB=new s6o({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function YYa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return c6o(o6o(Tx({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,context:i}),C4.ApiDefinitionId(t),lEB))}var $Qh=ue(require("path"),1);async function Sge({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&$Qh.default.isAbsolute(e)&&t.add(e)}async function YQh({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Ptl({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await Sge({iconPath:n.icon,filepaths:t}),n.rightIcon&&await Sge({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await Sge({iconPath:i.icon,filepaths:t}),i.rightIcon&&await Sge({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async i=>{i.icon!=null&&await Sge({iconPath:i.icon,filepaths:t})})),t}async function Ptl({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>Zca({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await Sge({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>Zca({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(Sge({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>Zca({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await Zca({item:r.landingPage,filepaths:t}),(await Ptl({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await Sge({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await Zca({item:r.landingPage,filepaths:t}),(await Ptl({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function Zca({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>Zca({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"pythonDocsSection":break}}async function XQh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){dEB(e)?await Promise.all(e.map(async n=>{pEB(n)?await Promise.all(n.layout.map(async a=>{await f0u({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):_EB(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await f0u({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await f0u({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function f0u({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await nVt(e,{alphabetized:It,api:It,apiName:It,audiences:It,displayErrors:It,tagDescriptionPages:It,snippets:It,summary:It,title:It,layout:It,collapsed:It,icon:It,slug:It,hidden:It,skipSlug:It,paginated:It,playground:It,flattened:It,path:It,page:It,featureFlag:It,openrpc:It,postman:It,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await f0u({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:It,orphaned:It,availability:It}),fEB(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function fEB(e){return e.api!=null}function dEB(e){return e[0]?.tab!=null}function pEB(e){return"layout"in e&&Array.isArray(e.layout)}function _EB(e){return"variants"in e&&Array.isArray(e.variants)}function Rx(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}kQh.default.extend(eUh.default);var hEB=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),ZQh=0,yEB=async({ir:e})=>(ZQh++,`${e.apiName.snakeCase.unsafeName}-${ZQh}`),k8t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=hEB,registerApi:d=yEB,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=d,this.targetAudiences=s}#e=i0u.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return R5a(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return R5a(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await F0c({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[He.of(x)]=Ee;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let x=performance.now();await XQh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:se})=>{(await se.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(Fe=>{let ae=Xf(this.docsWorkspace.absoluteFilePath,Fe.absoluteFilepath);this.parsedDocsConfig.pages[ae]=Fe.contents,this.rawMarkdownFiles[He.of(ae)]=Fe.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let Ee=performance.now()-x;this.taskContext.logger.debug(`Visited navigation AST in ${Ee.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let d=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-d;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),l=new Set;for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages)){let se=await Bju({markdown:Ee,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(x),context:this.taskContext});for(let Fe of se.referencedFiles)l.has(Fe.absoluteFilePath)||(l.add(Fe.absoluteFilePath),this.referencedMarkdownFiles.push(Fe));let Oe=await Hel({markdown:se.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(x),context:this.taskContext});this.parsedDocsConfig.pages[He.of(x)]=Oe}let p=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${p.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let _=performance.now(),h=await YQh({parsedDocsConfig:this.parsedDocsConfig}),y=performance.now()-_;this.taskContext.logger.debug(`Collected ${h.size} files in ${y.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let b=performance.now();for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:se,markdown:Oe}=$gn(Ee,{absolutePathToMarkdownFile:this.resolveFilepath(x),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[He.of(x)]=Oe;for(let Fe of se)h.add(Fe)}catch(se){throw this.taskContext.logger.error(`Failed to parse ${x}: ${se instanceof Error?se.message:String(se)}`),se}let v=performance.now()-b;this.taskContext.logger.debug(`Parsed image paths in ${v.toFixed(0)}ms`);let g=Array.from(h).map(x=>({absoluteFilePath:x,relativeFilePath:this.toRelativeFilepath(x)}));this.taskContext.logger.info(`Uploading ${g.length} files...`);let m=performance.now(),O=await this.uploadFiles(g),A=performance.now()-m;this.taskContext.logger.info(`Uploaded ${O.length} files in ${A.toFixed(0)}ms`),O.forEach(x=>{this.collectedFileIds.set(x.absoluteFilePath,x.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let j=performance.now(),M=await this.toRootNode(),w=performance.now()-j;this.taskContext.logger.debug(`Built navigation tree in ${w.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let D=performance.now(),B=await this.getMarkdownFilesToFullyQualifiedPathNames(M),R=performance.now()-D;this.taskContext.logger.debug(`Got path names in ${R.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let T=performance.now();for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[He.of(x)]=xel(Ee,this.collectedFileIds,B,{absolutePathToMarkdownFile:this.resolveFilepath(x),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let q=performance.now()-T;this.taskContext.logger.debug(`Replaced image paths in ${q.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let z={};Object.entries(this.parsedDocsConfig.pages).forEach(([x,Ee])=>{let{url:se,launch:Oe}=bEB(this.editThisPage,x),Fe=this.rawMarkdownFiles[He.of(x)];z[RG.PageId(x)]={markdown:Ee,editThisPageUrl:se?RG.Url(se):void 0,editThisPageLaunch:Oe,rawMarkdown:Fe}}),this.taskContext.logger.debug("Converting docs configuration...");let N=performance.now(),H=await this.convertDocsConfiguration(M),$=performance.now()-N;this.taskContext.logger.debug(`Converted docs configuration in ${$.toFixed(0)}ms`);let de={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let x=performance.now(),Ee=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async Oe=>{let Fe=Xu(this.docsWorkspace.absoluteFilePath,Oe);(await(0,d0u.stat)(Fe)).isDirectory()?(await m4(Fe,"{js,ts,jsx,tsx,md,mdx}")).forEach(Ge=>{Ee.add(Ge)}):Fe.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&Ee.add(Fe)})),de=Object.fromEntries(await Promise.all([...Ee].map(async Oe=>{let Fe=this.toRelativeFilepath(Oe),ae=(await(0,d0u.readFile)(Oe)).toString();return[Fe,ae]})));let se=performance.now()-x;this.taskContext.logger.debug(`Processed ${Ee.size} MDX component files in ${se.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let x of this.referencedMarkdownFiles)de[x.relativeFilePath]=x.content}let be=performance.now()-t,W=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${be.toFixed(0)}ms, Memory delta: RSS=${((W.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:H,pages:z,jsFiles:de}}resolveFilepath(t){if(t!=null)return Xu(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Xf(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,tUh.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let u=o.trim();Wel(u)?this.markdownFilesToFullSlugs.set(a,u):this.taskContext.logger.warn(`Ignoring absolute URL slug "${u}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let d=n.data.noindex;typeof d=="boolean"&&this.markdownFilesToNoIndex.set(a,d);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(u=>u.trim()).filter(u=>u.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s)}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=Nt.migrate.FernNavigationV1ToLatest.create().root(t);return Nt.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!Nt.isPage(a))return;let c=Nt.getPageId(a);if(c==null)return;let d=Tt(this.docsWorkspace.absoluteFilePath,He.of(c));r[d]=o}),r}getDocsBasePath(){return new URL(Rx(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?RG.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:RG.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:RG.Url(i.url)}:{...i,url:RG.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:RG.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch??"github",pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:void 0,footer:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
1902
|
+
${i.description}`;return this.#p.set(a,c),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#d(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?yYi.getSubpackageId(r):void 0;return t.map(o=>otl(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:Nt.Url(c.url),target:c.target}),page:c=>this.#l(c,i,n),package:c=>this.#_(c,i,n),section:c=>this.#y(c,i,n),item:({value:c})=>this.#h(c,a,i,n),endpoint:c=>this.#O(c,a,i,n)})).filter(us)}#l(t,r,i){return qQh({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#_(t,r,i){let n=t.overviewAbsolutePath!=null?Nt.V1.PageId(Kca(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let d=yYi.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${d}`);this.#a.has(d)&&this.taskContext.logger.warn(e0u(t.package)),this.#a.add(d),this.#o.set(s,[d]);let u=t.slug??(Z8t(c)?c.urlSlug:this.apiSection.slug??cS(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:p,title:t.title??(Z8t(c)?c.displayName??iOn(c.name):this.apiSection.title),slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(kju(t.package,this.#e.subpackageLocators));let d=t.slug??cS(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),u=this.#d(t.contents,void 0,s,o);return{id:this.#f.get(n??`${this.apiDefinitionId}:${cS(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#y(t,r,i){let n=t.overviewAbsolutePath!=null?Nt.V1.PageId(Kca(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(n??a??r.get()),d=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?yYi.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(kju(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(us);this.#o.set(c,d.map(_=>_.subpackageId)),d.forEach(_=>{this.#a.has(_.subpackageId)&&this.taskContext.logger.error(e0u(_.locator)),this.#a.add(_.subpackageId)});let s=t.slug??cS(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??i,p=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#h(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(ou(t));if(a!=null){let o=yYi.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(e0u(t)),this.#a.add(o),this.#o.set(c,[o]);let d=Z8t(a)?a.urlSlug:"",s=i.apply({urlSlug:d});return{id:c,type:"apiPackage",children:[],title:Z8t(a)?a.displayName??iOn(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i,n)}#O(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.endpoints.get(C4.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let d=this.#e.getEndpointId(a);if(d==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(d)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${d}`),this.#t.add(d);let s=t.slug!=null?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"endpoint",method:a.method,endpointId:d,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Nt.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??xW(a.path.parts),slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#P(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.webSockets.get(C4.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let d=this.#e.getWebSocketId(o);if(d==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(d)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${d}`),this.#r.add(d),{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"webSocket",webSocketId:d,title:t.title??o.name??xW(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(o.availability)??n,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(C4.SubpackageId(r))?.webhooks.get(C4.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Nt.V1.WebhookId(t.endpoint));if(c!=null){let d=this.#e.getWebhookId(c);if(d==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#i.has(d)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${d}`),this.#i.add(d),{id:this.#f.get(`${this.apiDefinitionId}:${d}`),type:"webhook",webhookId:d,method:c.method,title:t.title??c.name??(0,TQh.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:n,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#g(t,r){return CQh({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>xW(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t,r){return ctl({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(i,n,a)=>this.#v(i,n,a),mergeAndFilterChildren:this.#g.bind(this)})}#A(t,r,i){let n=[];return t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??xW(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Zju(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??xW(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??xW(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Nt.V1.convertAvailability(a.availability)??i,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#i.has(o)||n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??iOn(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:i,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#a.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=Z8t(o)?r.apply(o):r,d=this.#v(a,c,i);d.length>0&&n.push({id:Nt.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:d,title:Z8t(o)?o.displayName??iOn(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(o),availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,d=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(d)})),n}#v(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(kju(t||"unknown",[])),[]):this.#A(n,r,i)}#P(t){return PQh(t)}mergeEndpointPairs(t){return t0u({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>xW(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};var RQh=ue(require("crypto"),1);function SwB(e){return RQh.default.createHash("sha256").update(e).digest("hex")}var i0u=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),SwB(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Nt.V1.NodeId(this.#i(t))}};function zQh(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}var n0u=class{selectors;constructor(t){this.selectors=t}matches(t,r){for(let i of this.selectors)if(this.pathMatches(t,i.path)&&(!i.method||i.method===r))return!0;return!1}pathMatches(t,r){if(t===r)return!0;let i=t.split("/").filter(a=>a.length>0),n=r.split("/").filter(a=>a.length>0);if(i.length!==n.length)return!1;for(let a=0;a<i.length;a++){let o=i[a],c=n[a];if(!o||!c)return!1;let d=o.startsWith("{")&&o.endsWith("}"),s=c.startsWith("{")&&c.endsWith("}");if(!(d&&s)&&o!==c)return!1}return!0}getMatchingPaths(t){let r=[];for(let[i,n]of Object.entries(t)){if(!n)continue;let a=["get","put","post","delete","options","head","patch","trace"];for(let o of a)if(n[o]&&this.matches(i,o)){r.includes(i)||r.push(i);break}}return r}};var a0u=class{document;schemas=new Set;parameters=new Set;responses=new Set;requestBodies=new Set;securitySchemes=new Set;headers=new Set;examples=new Set;links=new Set;callbacks=new Set;constructor(t){this.document=t}collectFromOperation(t){if(t.parameters)for(let r of t.parameters)this.collectParameter(r);if(t.requestBody&&this.collectFromRequestBody(t.requestBody),t.responses)for(let r of Object.values(t.responses))this.collectFromResponse(r);if(t.callbacks)for(let[r,i]of Object.entries(t.callbacks))if(this.isReference(i))this.callbacks.add(this.extractComponentName(i.$ref));else for(let n of Object.values(i))this.collectFromPathItem(n);if(t.security)for(let r of t.security)for(let i of Object.keys(r))this.securitySchemes.add(i)}collectFromPathItem(t){if(t.parameters)for(let i of t.parameters)this.collectParameter(i);let r=[t.get,t.put,t.post,t.delete,t.options,t.head,t.patch,t.trace];for(let i of r)i&&this.collectFromOperation(i)}collectParameter(t){if(this.isReference(t)){this.parameters.add(this.extractComponentName(t.$ref));let r=this.resolveParameter(t.$ref);r&&this.collectParameter(r)}else{if(t.schema&&this.collectFromSchema(t.schema),t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}}collectFromRequestBody(t){if(this.isReference(t)){this.requestBodies.add(this.extractComponentName(t.$ref));let r=this.resolveRequestBody(t.$ref);r&&this.collectFromRequestBody(r)}else if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r)}collectFromResponse(t){if(this.isReference(t)){this.responses.add(this.extractComponentName(t.$ref));let r=this.resolveResponse(t.$ref);r&&this.collectFromResponse(r)}else{if(t.headers)for(let[r,i]of Object.entries(t.headers))this.isReference(i)?this.headers.add(this.extractComponentName(i.$ref)):i.schema&&this.collectFromSchema(i.schema);if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.links)for(let[r,i]of Object.entries(t.links))this.isReference(i)&&this.links.add(this.extractComponentName(i.$ref))}}collectFromMediaType(t){if(t.schema&&this.collectFromSchema(t.schema),t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}collectFromSchema(t){if(this.isReference(t)){let r=this.extractComponentName(t.$ref);if(!this.schemas.has(r)){this.schemas.add(r);let i=this.resolveSchema(t.$ref);i&&this.collectFromSchema(i)}}else{if(t.properties)for(let r of Object.values(t.properties))this.collectFromSchema(r);if(t.additionalProperties&&typeof t.additionalProperties=="object"&&this.collectFromSchema(t.additionalProperties),"items"in t&&t.items)if(Array.isArray(t.items))for(let r of t.items)this.collectFromSchema(r);else this.collectFromSchema(t.items);if(t.allOf)for(let r of t.allOf)this.collectFromSchema(r);if(t.oneOf)for(let r of t.oneOf)this.collectFromSchema(r);if(t.anyOf)for(let r of t.anyOf)this.collectFromSchema(r);t.not&&this.collectFromSchema(t.not)}}resolveSchema(t){let r=this.extractComponentName(t);return this.document.components?.schemas?.[r]}resolveParameter(t){let r=this.extractComponentName(t);return this.document.components?.parameters?.[r]}resolveResponse(t){let r=this.extractComponentName(t);return this.document.components?.responses?.[r]}resolveRequestBody(t){let r=this.extractComponentName(t);return this.document.components?.requestBodies?.[r]}isReference(t){return t!=null&&typeof t=="object"&&"$ref"in t}extractComponentName(t){let r=t.split("/");return r[r.length-1]??t}getSchemas(){return this.schemas}getParameters(){return this.parameters}getResponses(){return this.responses}getRequestBodies(){return this.requestBodies}getSecuritySchemes(){return this.securitySchemes}getHeaders(){return this.headers}getExamples(){return this.examples}getLinks(){return this.links}getCallbacks(){return this.callbacks}};var JYa=class{matcher;document;constructor(t){this.matcher=new n0u(t.endpoints),this.document=JSON.parse(JSON.stringify(t.document))}prune(){let t=this.collectStatistics(),r=new a0u(this.document),i={},n=this.matcher.getMatchingPaths(this.document.paths);for(let c of n){let d=this.document.paths[c];if(!d)continue;let s={};d.summary&&(s.summary=d.summary),d.description&&(s.description=d.description),d.servers&&(s.servers=d.servers),d.parameters&&(s.parameters=d.parameters);let u=["get","put","post","delete","options","head","patch","trace"];for(let l of u){let p=d[l];p&&this.matcher.matches(c,l)&&(s[l]=p,r.collectFromOperation(p))}if(d.parameters)for(let l of d.parameters)r.collectParameter(l);i[c]=s}let a={openapi:this.document.openapi,info:this.document.info,paths:i};if(this.document.servers&&(a.servers=this.document.servers),this.document.externalDocs&&(a.externalDocs=this.document.externalDocs),this.document.tags){let c=new Set;for(let d of Object.values(i)){let s=["get","put","post","delete","options","head","patch","trace"];for(let u of s){let l=d?.[u];if(l?.tags)for(let p of l.tags)c.add(p)}}a.tags=this.document.tags.filter(d=>c.has(d.name))}if(this.document.security){a.security=this.document.security;for(let c of this.document.security)for(let d of Object.keys(c))r.getSecuritySchemes().add(d)}a.components=this.buildPrunedComponents(r);let o=this.collectPrunedStatistics(a);return{document:a,statistics:{originalEndpoints:t.originalEndpoints,prunedEndpoints:o.originalEndpoints,originalSchemas:t.originalSchemas,prunedSchemas:o.originalSchemas,originalParameters:t.originalParameters,prunedParameters:o.originalParameters,originalResponses:t.originalResponses,prunedResponses:o.originalResponses,originalRequestBodies:t.originalRequestBodies,prunedRequestBodies:o.originalRequestBodies,originalSecuritySchemes:t.originalSecuritySchemes,prunedSecuritySchemes:o.originalSecuritySchemes}}}buildPrunedComponents(t){if(!this.document.components)return;let r={};if(this.document.components.schemas&&t.getSchemas().size>0){r.schemas={};for(let i of t.getSchemas()){let n=this.document.components.schemas[i];n&&(r.schemas[i]=n)}}if(this.document.components.parameters&&t.getParameters().size>0){r.parameters={};for(let i of t.getParameters()){let n=this.document.components.parameters[i];n&&(r.parameters[i]=n)}}if(this.document.components.responses&&t.getResponses().size>0){r.responses={};for(let i of t.getResponses()){let n=this.document.components.responses[i];n&&(r.responses[i]=n)}}if(this.document.components.requestBodies&&t.getRequestBodies().size>0){r.requestBodies={};for(let i of t.getRequestBodies()){let n=this.document.components.requestBodies[i];n&&(r.requestBodies[i]=n)}}if(this.document.components.securitySchemes&&t.getSecuritySchemes().size>0){r.securitySchemes={};for(let i of t.getSecuritySchemes()){let n=this.document.components.securitySchemes[i];n&&(r.securitySchemes[i]=n)}}if(this.document.components.headers&&t.getHeaders().size>0){r.headers={};for(let i of t.getHeaders()){let n=this.document.components.headers[i];n&&(r.headers[i]=n)}}if(this.document.components.examples&&t.getExamples().size>0){r.examples={};for(let i of t.getExamples()){let n=this.document.components.examples[i];n&&(r.examples[i]=n)}}if(this.document.components.links&&t.getLinks().size>0){r.links={};for(let i of t.getLinks()){let n=this.document.components.links[i];n&&(r.links[i]=n)}}if(this.document.components.callbacks&&t.getCallbacks().size>0){r.callbacks={};for(let i of t.getCallbacks()){let n=this.document.components.callbacks[i];n&&(r.callbacks[i]=n)}}return Object.keys(r).length>0?r:void 0}collectStatistics(){let t=0;for(let r of Object.values(this.document.paths)){if(!r)continue;let i=["get","put","post","delete","options","head","patch","trace"];for(let n of i)r[n]&&t++}return{originalEndpoints:t,prunedEndpoints:0,originalSchemas:Object.keys(this.document.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(this.document.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(this.document.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(this.document.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(this.document.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}collectPrunedStatistics(t){let r=0;for(let i of Object.values(t.paths)){if(!i)continue;let n=["get","put","post","delete","options","head","patch","trace"];for(let a of n)i[a]&&r++}return{originalEndpoints:r,prunedEndpoints:0,originalSchemas:Object.keys(t.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(t.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(t.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(t.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(t.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}};var btl=require("fs/promises");function ftl(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e,r=Object.keys(t);if(r.length===0||r.length>2)return!1;let i="type"in t&&typeof t.type=="string",n="value"in t;return i&&r.length===1||i&&n&&r.length===2||n&&r.length===1}function bYi(e){if(e==null)return e;if(Array.isArray(e))return e.map(bYi);if(typeof e!="object")return e;let t=e;if(ftl(t))return"value"in t?bYi(t.value):void 0;let r={};for(let[i,n]of Object.entries(t)){let a=bYi(n);a!==void 0&&(r[i]=a)}return r}function dtl(e){return e==null?!0:typeof e!="object"?!1:Array.isArray(e)?e.length===0:Object.keys(e).length===0}function o0u(e,t,r,i){let n={},a={},o={};if(e==null||typeof e!="object"||Array.isArray(e))return{filteredBody:e,extractedPathParams:n,extractedQueryParams:a,extractedHeaders:o};let c=e,d={},s=new Set(Object.keys(t??{})),u=new Set(Object.keys(r??{})),l=new Set(Object.keys(i??{}));for(let[p,_]of Object.entries(c)){let h=p.toLowerCase().replace(/[-_]/g,""),y=!1,b=!1,v=!1;for(let g of s){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){y=!0,n[g]=_;break}}if(!y)for(let g of u){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){b=!0,a[g]=_;break}}if(!y&&!b)for(let g of l){let m=g.toLowerCase().replace(/[-_]/g,"");if(h===m){v=!0,o[g]=_;break}}!y&&!b&&!v&&(d[p]=_)}return{filteredBody:d,extractedPathParams:n,extractedQueryParams:a,extractedHeaders:o}}var MwB=0,DwB=15e3,u0u=class{config;context;lambdaOrigin;venusOrigin;token;jwtPromise;organizationId;constructor(t,r,i,n){this.config={enabled:t.enabled,openaiApiKey:t.openaiApiKey,model:t.model??"gpt-4o-mini",maxRetries:t.maxRetries??MwB,requestTimeoutMs:t.requestTimeoutMs??DwB,styleInstructions:t.styleInstructions},this.context=r;let a="https://ykq45y6fvnszd35iv5yuuatkze0rpwuz.lambda-url.us-east-1.on.aws";if(!a)throw new Error("DEFAULT_FDR_LAMBDA_DOCS_ORIGIN environment variable is not set. AI example enhancement requires this to be configured.");this.lambdaOrigin=a,this.venusOrigin="https://venus.buildwithfern.com",this.token=i,this.organizationId=n}async getJwt(){return this.jwtPromise==null&&(this.jwtPromise=this.fetchJwtFromVenus()),this.jwtPromise}async fetchJwtFromVenus(){this.context.logger.debug("Fetching JWT from Venus for AI example enhancement"),this.context.logger.debug(`Token type: ${this.token.type}`),this.context.logger.debug(`Token value (first 10 chars): ${this.token.value.substring(0,10)}...`),this.context.logger.debug(`Token value starts with 'fern_': ${this.token.value.startsWith("fern_")}`),this.context.logger.debug(`Venus origin: ${this.venusOrigin}`),this.context.logger.debug(`Organization ID: ${this.organizationId}`);let t=await fetch(`${this.venusOrigin}/auth/jwt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token.value}`},body:JSON.stringify({organizationId:this.organizationId}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let i=await t.text();throw new Error(`Failed to fetch JWT from Venus: ${t.status} ${i||t.statusText}`)}let r=await t.json();return this.context.logger.debug(`Successfully obtained JWT from Venus (expires at ${r.expiresAt})`),r.token}async enhanceExample(t){if(!this.config.enabled)return{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};if(await Lgn(`${this.venusOrigin}/health`,this.context.logger))return this.context.logger.debug("Skipping AI example enhancement in air-gapped environment"),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};let i;try{i=await this.getJwt()}catch(o){return this.context.logger.warn(`Failed to obtain JWT from Venus: ${o}. AI example enhancement will be skipped.`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}let n,a=this.config.maxRetries+1;for(let o=1;o<=a;o++)try{this.context.logger.debug(`Enhancing example for ${t.method} ${t.endpointPath} via lambda (attempt ${o}/${a})`);let c={method:t.method,endpointPath:t.endpointPath,organizationId:t.organizationId,operationSummary:t.operationSummary,operationDescription:t.operationDescription,originalRequestExample:t.originalRequestExample,originalResponseExample:t.originalResponseExample,openApiSpec:t.openApiSpec,exampleStyleInstructions:t.exampleStyleInstructions??this.config.styleInstructions};this.context.logger.debug(`Sending to enhanceExamples: ${JSON.stringify({...c,openApiSpec:t.openApiSpec?`[OpenAPI spec present: ${t.openApiSpec.length} chars]`:"[No OpenAPI spec]"},null,2)}`);let d=await fetch(`${this.lambdaOrigin}/v2/registry/ai/enhance-example`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(c),signal:AbortSignal.timeout(this.config.requestTimeoutMs)});if(!d.ok){let u=await d.text();throw new Error(`Lambda returned ${d.status}: ${u||d.statusText}`)}let s=await d.json();return{enhancedRequestExample:s.enhancedRequestExample??t.originalRequestExample,enhancedResponseExample:s.enhancedResponseExample??t.originalResponseExample}}catch(c){if(n=c,this.context.logger.warn(`Attempt ${o} failed to enhance example: ${c}`),o<a){let d=Math.min(1e3*Math.pow(2,o-1),1e4);await new Promise(s=>setTimeout(s,d))}}return this.context.logger.error(`Failed to enhance example after ${a} attempts: ${n?.message}`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}};var Jca=class e{static instance;currentApiId;queue=[];progress=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}create(t,r,i){let n=`${t}-${Date.now()}-${Math.random()}`;return this.progress.set(n,{apiName:t,completed:0,total:r,endpointsSample:i}),this.queue.push(n),this.currentApiId||(this.currentApiId=n,this.updateSpinnerStatus()),n}update(t,r){let i=this.progress.get(t);i&&(i.completed=r,t===this.currentApiId&&this.updateSpinnerStatus())}finish(t){this.progress.delete(t);let r=this.queue.indexOf(t);r!==-1&&this.queue.splice(r,1),t===this.currentApiId&&(this.queue.length>0?(this.currentApiId=this.queue[0],this.updateSpinnerStatus()):(this.currentApiId=void 0,delete process.env.FERN_SPINNER_STATUS))}updateSpinnerStatus(){if(!this.currentApiId){delete process.env.FERN_SPINNER_STATUS;return}let t=this.progress.get(this.currentApiId);if(t){let r=`auto-generating examples for endpoints - ${t.apiName}`;t.endpointsSample&&(r+=` (${t.endpointsSample})`),r+=` - ${t.completed}/${t.total}`,process.env.FERN_SPINNER_STATUS=r}}};var s0u=require("fs/promises");async function BwB(e,t){let r=Sr.of(`${rn(e)}/ai_examples_override.yml`),i=[];try{let n=await(0,s0u.readFile)(r,"utf-8"),a=qi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,d]of Object.entries(o))if(d&&typeof d=="object"){for(let[s,u]of Object.entries(d))if(u&&typeof u=="object"&&"x-fern-examples"in u){let l=u["x-fern-examples"];if(Array.isArray(l)){for(let p of l)if(typeof p=="object"&&p!==null){let _=p;i.push({endpointPath:c,method:s.toUpperCase(),pathParameters:_["path-parameters"],queryParameters:_["query-parameters"],headers:_.headers,request:_.request,response:_.response})}}}}}t.logger.debug(`Parsed ${i.length} AI examples from ai_examples_override.yml`)}catch(n){t.logger.debug(`No existing ai_examples_override.yml found or error reading it: ${n}`)}return i}async function ptl({sourceFilePath:e,context:t}){let r=await BwB(e,t);if(r.length===0)return{validExamples:[],invalidExamples:[],totalExamples:0,validCount:0,invalidCount:0};let i;try{let s=await(0,s0u.readFile)(e,"utf-8");try{i=JSON.parse(s)}catch{i=qi.load(s)}}catch(s){return t.logger.warn(`Failed to read OpenAPI spec file: ${s}`),{validExamples:r,invalidExamples:[],totalExamples:r.length,validCount:r.length,invalidCount:0}}let n=new xEe({logger:t.logger}),a=new kUi({namespace:void 0,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:i,exampleGenerationArgs:{disabled:!1},errorCollector:n,enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,settings:R8t()}),o=new rvn({context:a}),{validExamples:c,invalidExamples:d}=o.validateAiExamples({aiExamples:r,spec:i});if(d.length>0){t.logger.info(`Found ${d.length} stale AI examples that need to be regenerated out of ${r.length} total`);for(let{example:s,validationResult:u}of d)t.logger.debug(`Stale AI example: ${s.method} ${s.endpointPath} - ${u.errors.map(l=>l.message).join(", ")}`)}return{validExamples:c,invalidExamples:d,totalExamples:r.length,validCount:c.length,invalidCount:d.length}}async function NQh({sourceFilePath:e,context:t}){let r=await ptl({sourceFilePath:e,context:t});if(r.invalidCount===0)return t.logger.debug("No invalid AI examples to remove"),{removedCount:0,remainingCount:r.totalExamples};let i=Sr.of(`${rn(e)}/ai_examples_override.yml`);try{let n=await(0,s0u.readFile)(i,"utf-8"),a=qi.load(n);if(!a||!a.paths)return{removedCount:0,remainingCount:r.totalExamples};let o=new Set(r.invalidExamples.map(({example:s})=>`${s.method.toLowerCase()}:${s.endpointPath}`));for(let[s,u]of Object.entries(a.paths))if(u&&typeof u=="object"){for(let l of Object.keys(u)){let p=`${l.toLowerCase()}:${s}`;o.has(p)&&delete u[l]}Object.keys(u).length===0&&delete a.paths[s]}let{writeFile:c}=await import("fs/promises"),d=qi.dump(a,{indent:2,lineWidth:-1,noRefs:!0});return await c(i,d,"utf-8"),t.logger.info(`Removed ${r.invalidCount} invalid AI examples from ai_examples_override.yml`),{removedCount:r.invalidCount,remainingCount:r.validCount}}catch(n){return t.logger.warn(`Failed to remove invalid AI examples: ${n}`),{removedCount:0,remainingCount:r.totalExamples}}}var $Ya=require("fs/promises");async function _tl(e,t){let r=Sr.of(`${rn(e)}/ai_examples_override.yml`),i=new Set;try{let n=await(0,$Ya.readFile)(r,"utf-8"),a=qi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,d]of Object.entries(o))if(d&&typeof d=="object")for(let s of Object.keys(d)){let u=`${s.toLowerCase()}:${c}`;i.add(u)}}t.logger.debug(`Loaded ${i.size} covered endpoints from ai_examples_override.yml`)}catch{t.logger.debug("No existing ai_examples_override.yml found or error reading it")}return i}async function c0u({enhancedExamples:e,sourceFilePath:t,context:r}){if(e.length===0){r.logger.debug("No enhanced examples to write");return}let i=new Map;for(let o of e){let c=i.get(o.endpoint)||[];c.push(o),i.set(o.endpoint,c)}let n={paths:{}};for(let[o,c]of i.entries()){let d=new Map;for(let s of c){let u=d.get(s.method.toLowerCase())||[];u.push(s),d.set(s.method.toLowerCase(),u)}n.paths[o]||(n.paths[o]={});for(let[s,u]of d.entries()){let l=u.map((_,h)=>{let y={},b={..._.pathParameters??{}},v={..._.queryParameters??{}},g={..._.headers??{}},m={...g};if(_.headerParameterNames)for(let B of _.headerParameterNames)B in m||(m[B]="");let O={};if(_.queryParameterNames)for(let B of _.queryParameterNames)O[B]=v[B]??"";let A={};if(_.pathParameterNames)for(let B of _.pathParameterNames)A[B]=b[B]??"";let j=_.requestBody;j!=null&&typeof j=="object"&&!Array.isArray(j)&&"body"in j&&(j=j.body);let M=bYi(j),w=M;if(M!==void 0){let{filteredBody:B,extractedPathParams:R,extractedQueryParams:T,extractedHeaders:q}=o0u(M,A,O,m);w=B;for(let[z,N]of Object.entries(R))N!=null&&N!==""&&(b[z]=N);for(let[z,N]of Object.entries(T))N!=null&&N!==""&&(v[z]=N);for(let[z,N]of Object.entries(q))N!=null&&N!==""&&(g[z]=N)}Object.keys(b).length>0&&(y["path-parameters"]=b),Object.keys(v).length>0&&(y["query-parameters"]=v),Object.keys(g).length>0&&(y.headers=g),w!==void 0&&!dtl(w)&&(y.request=w);let D=bYi(_.responseBody);return D!==void 0&&!dtl(D)&&(y.response={body:D}),y}),p=n.paths[o];p&&(p[s]={"x-fern-examples":l})}}let a=Sr.of(`${rn(t)}/ai_examples_override.yml`);try{let o={};try{let s=await(0,$Ya.readFile)(a,"utf-8"),u=qi.load(s);u&&typeof u=="object"&&(o=u)}catch{r.logger.debug("No existing ai_examples_override.yml found, creating new file")}let c={paths:{}};if(o.paths){for(let[s,u]of Object.entries(o.paths))if(u&&typeof u=="object"){c.paths[s]={};for(let[l,p]of Object.entries(u))p&&typeof p=="object"&&"x-fern-examples"in p&&(c.paths[s][l]={"x-fern-examples":p["x-fern-examples"]||[]})}}for(let[s,u]of Object.entries(n.paths)){c.paths[s]||(c.paths[s]={});for(let[l,p]of Object.entries(u))c.paths[s][l]?r.logger.debug(`Skipping ${l.toUpperCase()} ${s} - examples already exist in override file`):(c.paths[s][l]=p,r.logger.debug(`Adding new examples for ${l.toUpperCase()} ${s}`))}let d=qi.dump(c,{indent:2,lineWidth:-1,noRefs:!0});await(0,$Ya.writeFile)(a,d,"utf-8"),r.logger.debug(`AI enhanced examples written to: ${a}`)}catch(o){throw r.logger.warn(`Failed to write AI examples override file: ${o}`),o}}var htl=class{failureCount=0;failureThreshold=30;isOpen=!1;recordFailure(){this.failureCount++,this.failureCount>=this.failureThreshold&&(this.isOpen=!0)}recordSuccess(){this.failureCount=0,this.isOpen=!1}shouldSkip(){return this.isOpen}getFailureCount(){return this.failureCount}getThreshold(){return this.failureThreshold}},ytl=class{progressCallback;maxConcurrency;activeRequests=new Map;pendingQueue=[];results=new Map;stats={pending:0,active:0,completed:0,failed:0,totalStarted:0};completedSinceLastCallback=[];constructor(t,r){this.progressCallback=r,this.maxConcurrency=t}async processAll(t){for(this.pendingQueue=[...t],this.stats.pending=this.pendingQueue.length,this.stats.totalStarted=this.pendingQueue.length;this.pendingQueue.length>0&&this.activeRequests.size<this.maxConcurrency;)this.startNext();for(;this.activeRequests.size>0;){let r=Array.from(this.activeRequests.entries()).map(([a,o])=>o.promise.then(c=>({id:a,result:c}))),{id:i,result:n}=await Promise.race(r);await this.handleCompletion(i,n),this.pendingQueue.length>0&&this.startNext()}return this.results}startNext(){if(this.pendingQueue.length===0||this.activeRequests.size>=this.maxConcurrency)return;let t=this.pendingQueue.shift();if(!t)return;let r=`req-${Date.now()}-${Math.random()}`,i=t(),n={id:r,promise:i,startTime:Date.now()};this.activeRequests.set(r,n),this.stats.pending=this.pendingQueue.length,this.stats.active=this.activeRequests.size}async handleCompletion(t,r){this.activeRequests.get(t)&&this.activeRequests.delete(t),r.success?(this.stats.completed++,this.results.set(r.endpointKey,{enhancedReq:r.enhancedReq,enhancedRes:r.enhancedRes,extractedHeaders:r.extractedHeaders,extractedPathParams:r.extractedPathParams,extractedQueryParams:r.extractedQueryParams})):this.stats.failed++,this.stats.active=this.activeRequests.size,this.completedSinceLastCallback.push(r),this.progressCallback&&(this.progressCallback({...this.stats},[...this.completedSinceLastCallback]),this.completedSinceLastCallback=[])}getStats(){return{...this.stats}}};function IwB(e){try{try{let t=JSON.parse(e);return!!(t.openapi||t.swagger)}catch{let t=rZn(e);return!!(t?.openapi||t?.swagger)}}catch{return!1}}function UQh(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}function vtl(e,t,r,i){try{let n=JSON.parse(e);if(!n.paths)return[];let a=Object.keys(n.paths),o=UQh(t,a);if(!o)return[];let c=n.paths[o];if(!c)return[];let d=c[r.toLowerCase()];if(!d)return[];let s=[],u=[...c.parameters??[],...d.parameters??[]];for(let l of u)"$ref"in l||l.in===i&&s.push(l.name);return s}catch{return[]}}function CwB(e,t,r){return vtl(e,t,r,"header")}function qwB(e,t,r){return vtl(e,t,r,"query")}function TwB(e,t,r){return vtl(e,t,r,"path")}async function RwB(e,t,r){try{let i;try{i=JSON.parse(e)}catch{i=rZn(e)}if(!i.openapi||!i.paths){r.logger.debug("Invalid OpenAPI spec structure, skipping pruning");return}let n=Object.keys(i.paths);r.logger.debug(`OpenAPI spec contains ${n.length} paths`);let a=[];for(let l of t){let p=UQh(l.path,n);p?(a.push({path:p,method:l.method.toLowerCase()}),r.logger.debug(`Mapped ${l.path} to OpenAPI path: ${p}`)):r.logger.debug(`No matching OpenAPI path found for ${l.path}`)}if(a.length===0){r.logger.debug("No endpoints matched in OpenAPI spec");return}let c=new JYa({document:i,endpoints:a}).prune();r.logger.debug(`Pruned OpenAPI spec for batch: ${c.statistics.originalEndpoints} \u2192 ${c.statistics.prunedEndpoints} endpoints, ${c.statistics.originalSchemas} \u2192 ${c.statistics.prunedSchemas} schemas`);let d=JSON.stringify(c.document,null,2);if(d.length>15e5){r.logger.debug(`Pruned OpenAPI spec still too large (${d.length} characters), skipping spec context for AI enhancement`);return}r.logger.debug(`Pruned spec size: ${d.length} characters (within limit)`);let s=a.map(l=>`${(l.method||"unknown").toUpperCase()}_${l.path.replace(/\//g,"_").replace(/[{}]/g,"")}`),u=`batch_${a.length}endpoints_${s.join("_").substring(0,100)}_pruned_spec.yaml`;return d}catch(i){return r.logger.debug(`Failed to prune OpenAPI spec: ${i}. Using original spec.`),e}}async function Yca(e,t,r,i,n,a,o){if(!t.enabled)return r.logger.debug("AI example enhancement is disabled"),e;try{return await zwB(e,t,r,i,n,a,o)}catch(c){return r.logger.debug(`AI example enhancement failed with error: ${c}. Continuing with original API definition to prevent CLI crash.`),r.logger.debug(`Full AI enhancement error stack: ${c instanceof Error?c.stack:String(c)}`),e}}async function zwB(e,t,r,i,n,a,o){let c=new u0u(t,r,i,n),d=new htl,s,u=new Set;if(a!=null)try{let b=await(0,btl.readFile)(a,"utf-8");if(!IwB(b))return r.logger.debug("Non-OpenAPI spec detected, skipping AI example enhancement"),e;s=b,r.logger.debug(`Loaded OpenAPI spec (${b.length} characters) for AI enhancement`);let v=await _tl(a,r);try{let g=await ptl({sourceFilePath:a,context:r});if(g.invalidCount>0){for(let{example:O}of g.invalidExamples){let A=`${O.method.toLowerCase()}:${O.endpointPath}`;u.add(A)}let m=await NQh({sourceFilePath:a,context:r});r.logger.info(`Removed ${m.removedCount} stale AI examples, ${u.size} endpoints will be regenerated`)}else r.logger.debug("No stale AI examples found to remove")}catch(g){r.logger.debug(`Failed to clean up stale AI examples: ${g}`)}}catch(b){r.logger.debug(`Failed to read OpenAPI spec file: ${b}`)}let l=new Set;if(a!=null){let b=await _tl(a,r);for(let v of b)u.has(v)||l.add(v);u.size>0&&r.logger.debug(`Coverage adjusted: ${b.size} total, ${l.size} preserved, ${u.size} marked for regeneration`)}let p={count:0,total:0},_=[],h=await NwB(e,c,r,n,p,_,l,u,s,a,o,d);if(_.length>0&&a!=null)try{await c0u({enhancedExamples:_,sourceFilePath:a,context:r})}catch(b){r.logger.debug(`Failed to write AI examples override file: ${b}`)}let y=LQh(h);return r.logger.debug(`AI Enhancement Summary - Total endpoints in API: ${y}, Enhanced: ${p.count}/${p.total}, Covered: ${l.size}`),h}async function NwB(e,t,r,i,n,a,o,c,d,s,u,l){let p=[];for(let[A,j]of Object.entries(e.subpackages)){let M=FQh(j,o,c,r);p.push(...M.map(w=>({...w,packageId:A})))}let _=FQh(e.rootPackage,o,c,r);p.push(..._.map(A=>({...A,packageId:"root"})));let h=LQh(e);n.total+=p.length,r.logger.debug(`AI Examples Enhancement: ${p.length} endpoints need enhancement out of ${h} total endpoints (${o.size} already covered)`),r.logger.debug(`Collected ${p.length} work items across all packages`);let y=Jca.getInstance(),b=y.create(u||"API",p.length),v={count:0,total:p.length},g=await FwB(p,t,r,i,n,a,d,s,b,v,l);y.finish(b);let m={};for(let[A,j]of Object.entries(e.subpackages)){let M=QQh(j,g);m[A]=M}let O=QQh(e.rootPackage,g);return r.logger.debug(`AI Examples Enhancement Complete: ${v?.count||0}/${p.length} endpoints enhanced successfully (${h} total endpoints in API)`),{...e,subpackages:m,rootPackage:O}}function LQh(e){let t=0;t+=e.rootPackage.endpoints.length;for(let r of Object.values(e.subpackages))t+=r.endpoints.length;return t}function FQh(e,t,r,i){let n=[],a=new Set,o={totalEndpoints:e.endpoints.length,alreadyCovered:0,notAutogenerated:0,noExistingExamples:0,alreadyProcessed:0,noExamples:0,processed:0};for(let c of e.endpoints){let d=c;if(!LwB(d))for(let u of d.examples){let l=`${d.method.toLowerCase()}:${u.path}`;if(a.has(l)){o.alreadyProcessed++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: already processed in this run`);continue}let p=r?.has(l);if(!p&&t.has(l)){o.alreadyCovered++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: already covered (has AI-enhanced examples)`);continue}if(!p&&!UwB(u,i,l)){o.notAutogenerated++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: has human-written examples (not auto-generated)`);continue}let _=$ca(u.requestBodyV3),h=$ca(u.responseBodyV3);if(!p&&!_&&!h){o.noExistingExamples++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} skipped: no existing request/response examples to enhance`);continue}n.push({endpoint:d,example:u,endpointKey:l}),o.processed++,i?.logger.debug(`Endpoint ${d.method.toUpperCase()} ${u.path} selected for AI enhancement`),a.add(l);break}}return i&&(i.logger.debug(`Endpoint Filtering Results: ${o.processed}/${o.totalEndpoints} endpoints selected for AI enhancement`),i.logger.debug(`Filtering breakdown - Already covered: ${o.alreadyCovered}, Not auto-generated: ${o.notAutogenerated}, No existing examples: ${o.noExistingExamples}, No examples at all: ${o.noExamples}, Already processed: ${o.alreadyProcessed}, Selected: ${o.processed}`)),n}async function FwB(e,t,r,i,n,a,o,c,d,s,u){let l=parseInt(process.env.FERN_AI_MAX_CONCURRENT||"25",10);if(r.logger.debug(`Processing ${e.length} endpoints with max ${l} concurrent Lambda calls using rolling window queue`),u?.shouldSkip())return r.logger.debug(`Circuit breaker is open after ${u.getFailureCount()} failures (threshold: ${u.getThreshold()}). Skipping AI enhancement for remaining endpoints.`),new Map;let p=0,_=0,h=Math.max(10,Math.floor(e.length/20)),y=(O,A)=>{if(d&&s&&Jca.getInstance().update(d,O.completed),u?.shouldSkip()){r.logger.debug(`Circuit breaker opened during processing. Processed ${O.completed} endpoints.`);return}c&&a.length>0&&O.completed-_>=h&&(c0u({enhancedExamples:a,sourceFilePath:c,context:r}).then(()=>{r.logger.debug(`Saved ${a.length} examples after ${O.completed} completions`)}).catch(M=>{r.logger.debug(`Failed to save incremental results: ${M}`)}),_=O.completed)},b=e.map((O,A)=>async()=>{try{if(u?.shouldSkip())return{endpointKey:O.endpointKey,success:!1,error:"Circuit breaker is open"};let j=await QwB(O,t,r,i,n,a,o,c,d,s,A+1,u);return j?{endpointKey:j.endpointKey,enhancedReq:j.enhancedReq,enhancedRes:j.enhancedRes,extractedHeaders:j.extractedHeaders,extractedPathParams:j.extractedPathParams,extractedQueryParams:j.extractedQueryParams,success:!0}:{endpointKey:O.endpointKey,success:!1,error:"processEndpoint returned null"}}catch(j){return r.logger.debug(`Work item factory error for ${O.endpointKey}: ${j}`),{endpointKey:O.endpointKey,success:!1,error:String(j)}}}),v=new ytl(l,y),g=await v.processAll(b);if(c&&a.length>0)try{await c0u({enhancedExamples:a,sourceFilePath:c,context:r}),r.logger.debug(`Final save: ${a.length} examples saved`)}catch(O){r.logger.debug(`Failed to save final results: ${O}`)}let m=v.getStats();return r.logger.debug(`Completed processing: ${m.completed} succeeded, ${m.failed} failed`),g}async function QwB(e,t,r,i,n,a,o,c,d,s,u,l){let p=e.endpointKey;r.logger.debug(`Processing endpoint ${u}: ${e.endpoint.method} ${e.example.path}`);let _;o&&(_=await RwB(o,[{path:e.example.path,method:e.endpoint.method}],r));let h={method:e.endpoint.method,endpointPath:e.example.path,organizationId:i,operationSummary:e.endpoint.summary,operationDescription:e.endpoint.description,originalRequestExample:$ca(e.example.requestBodyV3),originalResponseExample:$ca(e.example.responseBodyV3),pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,openApiSpec:_};try{let y=await t.enhanceExample(h);l?.recordSuccess();let b=y.enhancedRequestExample!==h.originalRequestExample,v=y.enhancedResponseExample!==h.originalResponseExample;if(b||v){let g=_?CwB(_,e.example.path,e.endpoint.method):[],m=_?qwB(_,e.example.path,e.endpoint.method):[],O=_?TwB(_,e.example.path,e.endpoint.method):[],A={...e.example.headers??{}};if(g.length>0)for(let $ of g)$ in A||(A[$]="");let j={};for(let $ of m)j[$]=e.example.queryParameters?.[$]??"";let M={};for(let $ of O)M[$]=e.example.pathParameters?.[$]??"";let w=bYi(y.enhancedRequestExample),{filteredBody:D,extractedPathParams:B,extractedQueryParams:R,extractedHeaders:T}=o0u(w,M,j,A),q={...e.example.headers??{}};for(let[$,de]of Object.entries(T))de!=null&&de!==""&&(q[$]=de);let z={...e.example.pathParameters??{}};for(let[$,de]of Object.entries(B))de!=null&&de!==""&&(z[$]=de);let N={...e.example.queryParameters??{}};for(let[$,de]of Object.entries(R))de!=null&&de!==""&&(N[$]=de);let H={endpoint:e.example.path,method:e.endpoint.method,pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,requestBody:b?y.enhancedRequestExample:void 0,responseBody:v?y.enhancedResponseExample:void 0,headerParameterNames:g.length>0?g:void 0,queryParameterNames:m.length>0?m:void 0,pathParameterNames:O.length>0?O:void 0};return a.push(H),n.count++,s&&s.count++,r.logger.debug(`Successfully enhanced ${e.endpoint.method} ${e.example.path}`),d&&s&&Jca.getInstance().update(d,s.count),{endpointKey:p,enhancedReq:D,enhancedRes:y.enhancedResponseExample,extractedHeaders:Object.keys(q).length>0?q:void 0,extractedPathParams:Object.keys(z).length>0?z:void 0,extractedQueryParams:Object.keys(N).length>0?N:void 0}}return r.logger.debug(`No changes needed for ${e.endpoint.method} ${e.example.path}`),{endpointKey:p,enhancedReq:y.enhancedRequestExample,enhancedRes:y.enhancedResponseExample}}catch(y){l?.recordFailure(),r.logger.debug(`Endpoint ${e.endpoint.method} ${e.example.path} failed: ${y}`)}return r.logger.debug(`Failed to enhance ${e.endpoint.method} ${e.example.path}`),null}function QQh(e,t){let r=e.endpoints.map(i=>{let n=i,a=n.examples.map(o=>{let c=`${n.method.toLowerCase()}:${o.path}`,d=t.get(c);if(d){let s={...o};if(d.enhancedReq!==void 0)if(s.requestBody=d.enhancedReq,o.requestBodyV3)if(typeof o.requestBodyV3.value=="object"&&o.requestBodyV3.value!==null&&!Array.isArray(o.requestBodyV3.value)&&Object.values(o.requestBodyV3.value).some(l=>ftl(l))){let l=d.enhancedReq,p=o.requestBodyV3.value,_={};for(let[h,y]of Object.entries(p))h in l?_[h]={...y,value:l[h]}:_[h]=y;s.requestBodyV3={...o.requestBodyV3,value:_}}else s.requestBodyV3={...o.requestBodyV3,value:d.enhancedReq};else s.requestBodyV3={type:"json",value:d.enhancedReq};return d.enhancedRes!==void 0&&(s.responseBody=d.enhancedRes,s.responseBodyV3=o.responseBodyV3?{...o.responseBodyV3,value:d.enhancedRes}:{type:"json",value:d.enhancedRes}),d.extractedHeaders!==void 0&&(s.headers={...o.headers??{},...d.extractedHeaders}),d.extractedPathParams!==void 0&&(s.pathParameters={...o.pathParameters??{},...d.extractedPathParams}),d.extractedQueryParams!==void 0&&(s.queryParameters={...o.queryParameters??{},...d.extractedQueryParams}),s}return o});return{...i,examples:a}});return{...e,endpoints:r}}function UwB(e,t,r){let n=$ca(e.requestBodyV3),a=$ca(e.responseBodyV3),o=l0u(n,t,`${r}:request`),c=l0u(a,t,`${r}:response`),d=o.total+c.total,s=o.autogenerated+c.autogenerated;if(d===0)return!0;let u=s/d,l=u>=.3;return t&&r&&(l?t.logger.debug(`Endpoint ${r} considered auto-generated: ${s}/${d} (${(u*100).toFixed(1)}%) values are generic`):t.logger.debug(`Endpoint ${r} flagged as human-written: only ${s}/${d} (${(u*100).toFixed(1)}%) values are generic (threshold: ${.3*100}%)`)),l}function l0u(e,t,r){if(e==null)return{autogenerated:0,total:0};if(typeof e=="string"){let i=e===xn.STRING||e===xn.BASE64||e===xn.DATE||e===xn.DATE_TIME||e===xn.UUID||e===xn.BIG_INTEGER||xn.SAMPLE_STRINGS.includes(e)||e==="";return!i&&t&&r&&t.logger.debug(`Non-generic string found at ${r}: "${e}"`),{autogenerated:i?1:0,total:1}}if(typeof e=="number"){let i=e===xn.DOUBLE||e===xn.FLOAT||e===xn.INT||e===xn.INT64||e===xn.UINT||e===xn.UINT64||e===0;return!i&&t&&r&&t.logger.debug(`Non-generic number found at ${r}: ${e}`),{autogenerated:i?1:0,total:1}}if(typeof e=="boolean"){let i=e===xn.BOOLEAN;return!i&&t&&r&&t.logger.debug(`Non-generic boolean found at ${r}: ${e}`),{autogenerated:i?1:0,total:1}}if(Array.isArray(e)){if(e.length===0)return{autogenerated:0,total:0};let i=0,n=0;return e.forEach((a,o)=>{let c=l0u(a,t,r?`${r}[${o}]`:void 0);i+=c.autogenerated,n+=c.total}),{autogenerated:i,total:n}}if(typeof e=="object"){let i=0,n=0;return Object.entries(e).forEach(([a,o])=>{let c=l0u(o,t,r?`${r}.${a}`:void 0);i+=c.autogenerated,n+=c.total}),{autogenerated:i,total:n}}return t&&r&&t.logger.debug(`Unknown type at ${r}: ${typeof e} = ${e}`),{autogenerated:0,total:1}}function LwB(e){try{let t=e;if(t.v2Examples?.userSpecifiedExamples&&typeof t.v2Examples.userSpecifiedExamples=="object"){let r=t.v2Examples.userSpecifiedExamples;return Object.keys(r).length>0}if(t.v2Responses?.responses){for(let r of t.v2Responses.responses)if(r.body?.v2Examples?.userSpecifiedExamples&&typeof r.body.v2Examples.userSpecifiedExamples=="object"){let i=r.body.v2Examples.userSpecifiedExamples;if(Object.keys(i).length>0)return!0}}return!1}catch{return!1}}function $ca(e){if(e)switch(e.type){case"json":case"stream":case"sse":return e.value;case"filename":return;default:return e.value}}function VQh({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];return WQh({scheme:i,playgroundConfig:t,context:r})}}function WQh({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:e.password.originalName,usernameName:e.username.originalName,description:e.docs,passwordAlwaysEmpty:e.passwordOmit};case"bearer":return{type:"bearerAuth",tokenName:e.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:e.name.wireValue,nameOverride:e.name.name.originalName,prefix:e.prefix,description:e.docs};case"oauth":{let i=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(n=>n.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:ni.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:ni.JqString(i),headerName:e.configuration.tokenHeader,tokenPrefix:e.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let i=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(i)return i.responseProperty.propertyPath!=null&&i.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:i.responseProperty.property.name.wireValue,description:e.docs};let n=e.tokenEndpoint.authenticatedRequestHeaders[0];return n?{type:"header",headerWireValue:n.headerName,prefix:n.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:vt(e)}}function GQh({auth:e,playgroundConfig:t,context:r}){let i={};for(let n of e.schemes){let a=WQh({scheme:n,playgroundConfig:t,context:r});a!=null&&(i[ni.AuthSchemeId(n.key)]=a)}return i}function HQh(e){return e._visit({alias:t=>({type:"alias",value:ib(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:RM(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>ni.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:ni.PropertyKey(r.name.wireValue),valueType:ib(r.valueType),availability:RM(r.availability),propertyAccess:r.propertyAccess})),extraProperties:KwB(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),availability:RM(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?RM(i.availability):void 0,additionalProperties:Ar.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[ni.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:ni.PropertyKey(n.name.wireValue),valueType:ib(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:ib(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName??r.type.name.originalName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function ib(e){return e._visit({container:t=>Ar.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:ib(r),minItems:void 0,maxItems:void 0}),map:({keyType:r,valueType:i})=>({type:"map",keyType:ib(r),valueType:ib(i),minProperties:void 0,maxProperties:void 0}),optional:r=>({type:"optional",itemType:ib(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:ib(r)}),set:r=>({type:"set",itemType:ib(r),minItems:void 0,maxItems:void 0}),literal:r=>Ar.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:ni.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Ar.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>WwB(t.v2),float:()=>xQh(t.v2),double:()=>xQh(t.v2),string:()=>VwB(t.v2),long:()=>GwB(t.v2),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>xwB(t.v2),uint64:()=>HwB(t.v2),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function VwB(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function WwB(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="integer"?e.default:void 0}}function xQh(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="double"?e.default:void 0}}function GwB(e){let t=e!=null&&e.type==="long"?e.validation:void 0;return{type:"long",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="long"?e.default:void 0}}function xwB(e){let t=e!=null&&e.type==="uint"?e.validation:void 0;return{type:"uint",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint"?e.default:void 0}}function HwB(e){let t=e!=null&&e.type==="uint64"?e.validation:void 0;return{type:"uint64",minimum:t?.exclusiveMin===!0?void 0:t?.min,maximum:t?.exclusiveMax===!0?void 0:t?.max,exclusiveMinimum:t?.exclusiveMin===!0?t?.min:void 0,exclusiveMaximum:t?.exclusiveMax===!0?t?.max:void 0,multipleOf:t?.multipleOf,default:e!=null&&e.type==="uint64"?e.default:void 0}}function KwB(e){return typeof e=="boolean"?e?ii.unknown():void 0:typeof e=="string"?{type:"id",value:ni.TypeId(e),default:void 0}:ib(e)}function mtl(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?$wB(r,t):[],webhooks:i!=null?JwB(i):[],websockets:n!=null?[YwB(n,t)]:[],types:e.types.map(a=>ni.TypeId(a)),subpackages:e.subpackages.map(a=>ni.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?ni.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0,graphqlOperations:void 0}}function JwB(e){return e.map(t=>{let r=[];if(t.v2Examples!=null){for(let[i,n]of Object.entries(t.v2Examples.userSpecifiedExamples))r.push({name:n.name??i,payload:n.payload});for(let[i,n]of Object.entries(t.v2Examples.autogeneratedExamples))r.push({name:n.name??i,payload:n.payload})}else r.push(...t.examples?.map(i=>({name:i.name?.originalName,payload:i.payload.jsonExample}))??[]);return{description:t.docs??void 0,id:ni.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Rfn(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:ib(i.valueType),availability:RM(i.availability)})),payload:aEB(t.payload,t.fileUploadPayload),examples:r,responses:t.responses?.map(Otl).filter(us)}})}function $wB(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,u=Object.values(d).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(d))c=JQh({shouldUseExampleName:_.displayName!=null||u,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(s))c=JQh({shouldUseExampleName:l,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>gtl({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(us));else if(n!=null){let c=gtl({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=joa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=gtl({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:RM(i.availability??e.availability),auth:i.auth,authV2:XwB(i.security),multiAuth:ZwB(i.security),description:i.docs??void 0,method:rEB(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?ni.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?kwB({environmentsConfig:t.environments,endpoint:i}):void 0,id:ni.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Rfn(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:ni.PropertyKey(c.name.originalName),type:ib(c.valueType),availability:void 0,explode:c.explode})),parts:[...Xca(i.basePath),...Xca(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:ni.PropertyKey(c.name.originalName),type:ib(c.valueType),availability:void 0,explode:c.explode})),parts:[...t.basePath!=null?Xca(t.basePath):[],...Xca(e.basePath),...Xca(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability),explode:c.explode})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability)})),responseHeaders:i.responseHeaders?.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:ib(c.valueType),availability:RM(c.availability)})),request:i.requestBody!=null?KQh(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(KQh).filter(us)},response:i.response!=null?Otl(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(Otl).filter(us)},errors:void 0,errorsV2:iEB(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground};r.push(o)}return r}function YwB(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.entries(e.v2Examples.userSpecifiedExamples),n=Object.entries(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];if(a!=null){let[o,c]=a;r.push({name:o,description:"",path:c.baseUrl??"",pathParameters:c.pathParameters??{},queryParameters:c.queryParameters??{},headers:c.headers??{},messages:c.messages?.map(d=>({type:ni.api.v1.WebSocketMessageId(d.type),body:d.body}))??[]})}}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[ni.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:ni.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:RM(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?ni.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?eEB({environmentsConfig:t.environments,channel:e}):[],id:ni.WebSocketId(e.name.originalName),name:e.displayName??Rfn(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:ni.PropertyKey(i.name.originalName),type:ib(i.valueType),availability:void 0,explode:i.explode})),parts:Xca(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:ib(i.valueType),description:i.docs,availability:RM(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:ib(i.valueType),availability:RM(i.availability),explode:i.explode})),messages:e.messages.map(i=>({type:ni.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:uEB(i.body),description:i.docs,availability:RM(i.availability)})),examples:r}}function XwB(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>ni.AuthSchemeId(r))}function ZwB(e){if(e!=null)return e.length===0?[]:e.map(t=>({schemes:Object.keys(t).map(r=>ni.AuthSchemeId(r))}))}function RM(e){if(e!=null)switch(e.status){case"DEPRECATED":return ni.Availability.Deprecated;case"PRE_RELEASE":return ni.Availability.Beta;case"GENERAL_AVAILABILITY":return ni.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return ni.Availability.Beta;default:vt(e.status)}}function kwB({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:ni.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(o=>r.environments.map(c=>{let d=c.urls[o];if(d==null)throw new Error(`Encountered undefined server name "${o}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${c.id} to contain url for ${o}`);return{id:ni.EnvironmentId(o),baseUrl:d}})).filter((o,c,d)=>c===d.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[i];if(o==null)throw new Error(`Encountered undefined server name "${i}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${i}`);return{id:ni.EnvironmentId(a.id),baseUrl:o}});default:vt(r)}}function eEB({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ni.EnvironmentId(n.id),baseUrl:tEB(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${n.id} to contain url for ${i}`);return{id:ni.EnvironmentId(n.id),baseUrl:a}});default:vt(r)}}function tEB(e,t){return e.replace(/^[^:]+/,t)}function rEB(e){return Ar.http.HttpMethod._visit(e,{get:()=>ni.HttpMethod.Get,post:()=>ni.HttpMethod.Post,put:()=>ni.HttpMethod.Put,patch:()=>ni.HttpMethod.Patch,delete:()=>ni.HttpMethod.Delete,head:()=>ni.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function Xca(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:ni.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function KQh(e){let t=Ar.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??tm.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>ni.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),availability:RM(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??tm.APPLICATION_JSON,shape:{type:"reference",value:ib(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:o=>({type:"file",key:ni.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:ni.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:ni.PropertyKey(n.name.wireValue),valueType:ib(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:RM(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(us)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function Otl(e){let t=e.docs,r;return e.body!=null&&(r=Ar.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:ib(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:ib(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:ib(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function iEB(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:ib(n.type)},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:sEB(n,t),headers:n.headers!=null&&n.headers.length>0?n.headers.map(a=>({description:a.docs??void 0,key:a.name.wireValue,type:ib(a.valueType),availability:RM(a.availability)})):void 0})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:ni.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:ni.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:ib(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs})),headers:n.headers!=null&&n.headers.length>0?n.headers.map(o=>({description:o.docs??void 0,key:o.name.wireValue,type:ib(o.valueType),availability:RM(o.availability)})):void 0})}}return r}function JQh({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i,irService:n,ir:a}){if(r==null)return;let o=s=>{if(s.valueType.type==="container"&&s.valueType.container.type==="literal")return s.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}});if(s.valueType.type==="container"&&s.valueType.container.type==="optional"&&s.valueType.container.optional.type==="container"&&s.valueType.container.optional.container.type==="literal")return s.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})},c={};a.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),n.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),i.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)});let d=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let u={...r.request?.headers??{}};for(let[l,p]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=p);return u})(),requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if(yl(r.request.requestBody)){let l=r.request.requestBody;for(let p of s.properties)p._visit({file:_=>{let h=l[_.key.wireValue];if(_.type==="file")u[_.key.wireValue]={type:"filename",value:typeof h=="string"?h:"<file1>"};else if(_.type==="fileArray"){let y=(Array.isArray(h)?h:[h]).filter(b=>typeof b=="string");u[_.key.wireValue]={type:"filenames",value:y}}},bodyProperty:_=>{if(_.style==="exploded"){let h=l[_.name.wireValue];u[_.name.wireValue]={type:"exploded",value:Array.isArray(h)?h:[h]}}else u[_.name.wireValue]={type:"json",value:l[_.name.wireValue]}},_other:kje})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:d??void 0,responseBodyV3:d!=null?r.response?.body?._visit({json:s=>({type:"json",value:s}),stream:s=>Array.isArray(s)&&s.length>0&&s.every(nEB)?{type:"sse",value:s}:{type:"stream",value:s},error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(s=>({name:s.name,description:s.docs??void 0,install:void 0,language:s.language,code:s.code})).filter(us)}}function nEB(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function gtl({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?d=c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(d=c.valueType.container.optional.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}})),d!=null)return{name:c.name,value:{jsonExample:d,shape:Ar.ExampleTypeReferenceShape.primitive(Ar.ExamplePrimitive.string({original:d}))}}}).filter(us),a=e?.example??t?.example;if(a==null)return;let{codeSamples:o}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[ni.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let d={};if(yl(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let p=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof p=="string"?p:"<file1>"};else if(l.type==="fileArray"){let _=(Array.isArray(p)?p:[p]).filter(h=>typeof h=="string");d[l.key.wireValue]={type:"filenames",value:_}}},bodyProperty:l=>{if(l.style==="exploded"){let p=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(p)?p:[p]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:kje})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Ar.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:u})=>({event:s,data:u.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:o?.map(c=>Yve._visit(c,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(us)}}function aEB(e,t){return t!=null?{type:{type:"formData",name:t.name.originalName,description:t.docs??void 0,availability:void 0,properties:t.properties.map(r=>r._visit({file:i=>{let n=i._visit({file:a=>({type:"file",key:ni.PropertyKey(a.key.wireValue),isOptional:a.isOptional,contentType:a.contentType,description:a.docs??void 0,availability:void 0}),fileArray:a=>({type:"fileArray",key:ni.PropertyKey(a.key.wireValue),isOptional:a.isOptional,contentType:a.contentType,description:a.docs??void 0,availability:void 0}),_other:()=>{}});if(n!=null)return{type:"file",value:n}},bodyProperty:i=>({type:"bodyProperty",key:ni.PropertyKey(i.name.wireValue),valueType:ib(i.valueType),contentType:i.contentType,description:i.docs??void 0,availability:RM(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(us)},description:t.docs??void 0}:oEB(e)}function oEB(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>ni.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ni.PropertyKey(t.name.wireValue),valueType:ib(t.valueType),availability:RM(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:ib(e.payloadType)},description:e.docs};default:vt(e)}}function uEB(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>ni.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ni.PropertyKey(t.name.wireValue),valueType:ib(t.valueType),availability:RM(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:ib(e.bodyType)};default:vt(e)}}function sEB(e,t){let r=e.v2Examples?.userSpecifiedExamples,i=e.v2Examples?.autogeneratedExamples,n=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(i!=null&&Object.keys(i).length>0)return Object.entries(i).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(n.length>0)return n.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}));let a=cEB(e,t);return a!=null?[a]:[]}function cEB(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,i=t.types[r];if(i==null||i.shape.type!=="object")return;let n={},a=!1;for(let o of i.shape.properties){let c=o.name.wireValue,d=o.v2Examples;if(d?.userSpecifiedExamples!=null){let s=Object.values(d.userSpecifiedExamples);if(s.length>0){n[c]=s[0],a=!0;continue}}if(d?.autogeneratedExamples!=null){let s=Object.values(d.autogeneratedExamples);if(s.length>0){n[c]=s[0];continue}}}if(a)return{name:void 0,responseBody:{type:"json",value:n},description:void 0}}function Tx({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:mtl(e.rootPackage,e),apiName:e.apiName.originalName,auth:VQh({auth:e.auth,playgroundConfig:r,context:i}),authSchemes:GQh({auth:e.auth,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:RM(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:ib(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))n.types[ni.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:HQh(o.shape),availability:RM(o.availability),displayName:o.name.displayName};for(let[a,o]of Object.entries(e.subpackages)){let c=o.service!=null?e.services[o.service]:void 0;n.subpackages[ni.api.v1.SubpackageId(a)]={subpackageId:ni.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...mtl(o,e)}}return n}async function Atl({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:o,aiEnhancerConfig:c}){let d=ES({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new wS(r,t)}),s=B3t({token:i.value}),u=Tx({ir:d,snippetsConfig:a,playgroundConfig:o,context:r});if(c){let h=t.getSources().find(y=>y.type==="openapi")?.absoluteFilePath;u=await Yca(u,c,r,i,e,h,d.apiName.originalName)}let l=await s.api.v1.register.registerApiDefinition({orgId:ni.OrgId(e),apiId:ni.ApiId(d.apiName.originalName),definition:u});if(l.ok)return r.logger.debug(`Registered API Definition ${l.body.apiDefinitionId}`),{id:l.body.apiDefinitionId,ir:d};switch(l.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",l.error)}}var lEB=new s6o({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function YYa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return c6o(o6o(Tx({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,context:i}),C4.ApiDefinitionId(t),lEB))}var $Qh=ue(require("path"),1);async function Sge({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&$Qh.default.isAbsolute(e)&&t.add(e)}async function YQh({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Ptl({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await Sge({iconPath:n.icon,filepaths:t}),n.rightIcon&&await Sge({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await Sge({iconPath:i.icon,filepaths:t}),i.rightIcon&&await Sge({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async i=>{i.icon!=null&&await Sge({iconPath:i.icon,filepaths:t})})),t}async function Ptl({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>Zca({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await Sge({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>Zca({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(Sge({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>Zca({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await Zca({item:r.landingPage,filepaths:t}),(await Ptl({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await Sge({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await Zca({item:r.landingPage,filepaths:t}),(await Ptl({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function Zca({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>Zca({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await Sge({iconPath:e.icon,filepaths:t});break;case"pythonDocsSection":break}}async function XQh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){dEB(e)?await Promise.all(e.map(async n=>{pEB(n)?await Promise.all(n.layout.map(async a=>{await f0u({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):_EB(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await f0u({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await f0u({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function f0u({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await nVt(e,{alphabetized:It,api:It,apiName:It,audiences:It,displayErrors:It,tagDescriptionPages:It,snippets:It,summary:It,title:It,layout:It,collapsed:It,icon:It,slug:It,hidden:It,skipSlug:It,paginated:It,playground:It,flattened:It,path:It,page:It,featureFlag:It,openrpc:It,postman:It,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await f0u({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:It,orphaned:It,availability:It}),fEB(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function fEB(e){return e.api!=null}function dEB(e){return e[0]?.tab!=null}function pEB(e){return"layout"in e&&Array.isArray(e.layout)}function _EB(e){return"variants"in e&&Array.isArray(e.variants)}function Rx(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}kQh.default.extend(eUh.default);var hEB=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),ZQh=0,yEB=async({ir:e})=>(ZQh++,`${e.apiName.snakeCase.unsafeName}-${ZQh}`),k8t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=hEB,registerApi:d=yEB,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=d,this.targetAudiences=s}#e=i0u.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return R5a(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return R5a(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await F0c({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[He.of(x)]=Ee;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let x=performance.now();await XQh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:se})=>{(await se.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(Fe=>{let ae=Xf(this.docsWorkspace.absoluteFilePath,Fe.absoluteFilepath);this.parsedDocsConfig.pages[ae]=Fe.contents,this.rawMarkdownFiles[He.of(ae)]=Fe.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let Ee=performance.now()-x;this.taskContext.logger.debug(`Visited navigation AST in ${Ee.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let d=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-d;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),l=new Set;for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages)){let se=await Bju({markdown:Ee,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(x),context:this.taskContext});for(let Fe of se.referencedFiles)l.has(Fe.absoluteFilePath)||(l.add(Fe.absoluteFilePath),this.referencedMarkdownFiles.push(Fe));let Oe=await Hel({markdown:se.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(x),context:this.taskContext});this.parsedDocsConfig.pages[He.of(x)]=Oe}let p=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${p.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let _=performance.now(),h=await YQh({parsedDocsConfig:this.parsedDocsConfig}),y=performance.now()-_;this.taskContext.logger.debug(`Collected ${h.size} files in ${y.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let b=performance.now();for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:se,markdown:Oe}=$gn(Ee,{absolutePathToMarkdownFile:this.resolveFilepath(x),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[He.of(x)]=Oe;for(let Fe of se)h.add(Fe)}catch(se){throw this.taskContext.logger.error(`Failed to parse ${x}: ${se instanceof Error?se.message:String(se)}`),se}let v=performance.now()-b;this.taskContext.logger.debug(`Parsed image paths in ${v.toFixed(0)}ms`);let g=Array.from(h).map(x=>({absoluteFilePath:x,relativeFilePath:this.toRelativeFilepath(x)}));this.taskContext.logger.info(`Uploading ${g.length} files...`);let m=performance.now(),O=await this.uploadFiles(g),A=performance.now()-m;this.taskContext.logger.info(`Uploaded ${O.length} files in ${A.toFixed(0)}ms`),O.forEach(x=>{this.collectedFileIds.set(x.absoluteFilePath,x.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let j=performance.now(),M=await this.toRootNode(),w=performance.now()-j;this.taskContext.logger.debug(`Built navigation tree in ${w.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let D=performance.now(),B=await this.getMarkdownFilesToFullyQualifiedPathNames(M),R=performance.now()-D;this.taskContext.logger.debug(`Got path names in ${R.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let T=performance.now();for(let[x,Ee]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[He.of(x)]=xel(Ee,this.collectedFileIds,B,{absolutePathToMarkdownFile:this.resolveFilepath(x),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let q=performance.now()-T;this.taskContext.logger.debug(`Replaced image paths in ${q.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let z={};Object.entries(this.parsedDocsConfig.pages).forEach(([x,Ee])=>{let{url:se,launch:Oe}=bEB(this.editThisPage,x),Fe=this.rawMarkdownFiles[He.of(x)];z[RG.PageId(x)]={markdown:Ee,editThisPageUrl:se?RG.Url(se):void 0,editThisPageLaunch:Oe,rawMarkdown:Fe}}),this.taskContext.logger.debug("Converting docs configuration...");let N=performance.now(),H=await this.convertDocsConfiguration(M),$=performance.now()-N;this.taskContext.logger.debug(`Converted docs configuration in ${$.toFixed(0)}ms`);let de={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let x=performance.now(),Ee=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async Oe=>{let Fe=Xu(this.docsWorkspace.absoluteFilePath,Oe);(await(0,d0u.stat)(Fe)).isDirectory()?(await m4(Fe,"{js,ts,jsx,tsx,md,mdx}")).forEach(Ge=>{Ee.add(Ge)}):Fe.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&Ee.add(Fe)})),de=Object.fromEntries(await Promise.all([...Ee].map(async Oe=>{let Fe=this.toRelativeFilepath(Oe),ae=(await(0,d0u.readFile)(Oe)).toString();return[Fe,ae]})));let se=performance.now()-x;this.taskContext.logger.debug(`Processed ${Ee.size} MDX component files in ${se.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let x of this.referencedMarkdownFiles)de[x.relativeFilePath]=x.content}let be=performance.now()-t,W=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${be.toFixed(0)}ms, Memory delta: RSS=${((W.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:H,pages:z,jsFiles:de}}resolveFilepath(t){if(t!=null)return Xu(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Xf(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,tUh.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let u=o.trim();Wel(u)?this.markdownFilesToFullSlugs.set(a,u):this.taskContext.logger.warn(`Ignoring absolute URL slug "${u}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let d=n.data.noindex;typeof d=="boolean"&&this.markdownFilesToNoIndex.set(a,d);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(u=>u.trim()).filter(u=>u.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s)}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=Nt.migrate.FernNavigationV1ToLatest.create().root(t);return Nt.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!Nt.isPage(a))return;let c=Nt.getPageId(a);if(c==null)return;let d=Tt(this.docsWorkspace.absoluteFilePath,He.of(c));r[d]=o}),r}getDocsBasePath(){return new URL(Rx(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?RG.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:RG.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:RG.Url(i.url)}:{...i,url:RG.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:RG.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch??"github",pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:void 0,footer:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
1903
1903
|
A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
1904
1904
|
Learn more about project structure:
|
|
1905
1905
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
@@ -1946,7 +1946,7 @@ The generated documentation will replace this placeholder page with complete API
|
|
|
1946
1946
|
- Class and function references
|
|
1947
1947
|
- Type annotations and signatures
|
|
1948
1948
|
- Docstring content
|
|
1949
|
-
`;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Nt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??cS(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Nt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??cS(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Kfn(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new aOn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Nt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??cS(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??cS(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):RG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(us),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:RG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Kfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:RG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function bEB(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${Rx(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function vEB(e){switch(e){case"beta":return Nt.V1.NavigationV1Availability.Beta;case"deprecated":return Nt.V1.NavigationV1Availability.Deprecated;case"ga":return Nt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Nt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function BL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof jS?t:null))).filter(us)}async function jtl(e,t,r){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return Tx({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var uc={};Yt(uc,{AlgoliaSearchIndex:()=>rUh,ApiDefinitionId:()=>PUh,ApiId:()=>SUh,Availability:()=>VUh,DocsConfigId:()=>MUh,EndpointId:()=>BUh,EndpointPathLiteral:()=>UUh,EnvironmentId:()=>DUh,FileId:()=>RUh,HttpMethod:()=>LUh,IndexSegmentId:()=>iUh,JqString:()=>NUh,OrgId:()=>wUh,PageId:()=>TUh,PayloadLocation:()=>h4h,PropertyKey:()=>FUh,PullRequestState:()=>l4h,RoleId:()=>QUh,TokenId:()=>EUh,TypeId:()=>qUh,Url:()=>zUh,VersionId:()=>jUh,WebSocketId:()=>IUh,WebhookId:()=>CUh,algolia:()=>wtl,api:()=>Rtl,commons:()=>ztl,diff:()=>WUh,docs:()=>xtl,generators:()=>Ktl,git:()=>Jtl,navigation:()=>Xtl,sdks:()=>ktl,snippets:()=>p4h,snippetsFactory:()=>_4h,templates:()=>erl,tokens:()=>y4h});var wtl={};Yt(wtl,{AlgoliaSearchIndex:()=>rUh,IndexSegmentId:()=>iUh});function rUh(e){return e}function iUh(e){return e}var Rtl={};Yt(Rtl,{latest:()=>Mtl,v1:()=>Ttl});var Mtl={};Yt(Mtl,{AuthSchemeId:()=>nUh,WebhookHttpMethod:()=>sUh,auth:()=>Etl,commons:()=>aUh,endpoint:()=>oUh,type_:()=>uUh,webhook:()=>Stl,websocket:()=>cUh});var Etl={};Yt(Etl,{AuthSchemeId:()=>nUh});function nUh(e){return e}var aUh={};var oUh={};var uUh={};var Stl={};Yt(Stl,{WebhookHttpMethod:()=>sUh});var sUh={Get:"GET",Post:"POST"};var cUh={};var Ttl={};Yt(Ttl,{SubpackageId:()=>gUh,WebSocketMessageId:()=>OUh,WebSocketMessageOrigin:()=>mUh,WebhookHttpMethod:()=>AUh,commons:()=>qtl,db:()=>Dtl,read:()=>Itl,register:()=>Ctl});var Dtl={};Yt(Dtl,{endpoint:()=>lUh});var lUh={};var Itl={};Yt(Itl,{SupportedLanguage:()=>fUh,endpoint:()=>Btl,type_:()=>dUh,webhook:()=>pUh,websocket:()=>_Uh});var Btl={};Yt(Btl,{SupportedLanguage:()=>fUh});var fUh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var dUh={};var pUh={};var _Uh={};var Ctl={};Yt(Ctl,{SourceId:()=>gEB,endpoint:()=>hUh,type_:()=>yUh,webhook:()=>bUh,websocket:()=>vUh});var hUh={};var yUh={};var bUh={};var vUh={};function gEB(e){return e}var qtl={};Yt(qtl,{SubpackageId:()=>gUh,WebSocketMessageId:()=>OUh,WebSocketMessageOrigin:()=>mUh,WebhookHttpMethod:()=>AUh});function gUh(e){return e}function OUh(e){return e}var mUh={Client:"client",Server:"server"};var AUh={Get:"GET",Post:"POST"};var ztl={};Yt(ztl,{ApiDefinitionId:()=>PUh,ApiId:()=>SUh,Availability:()=>VUh,DocsConfigId:()=>MUh,EndpointId:()=>BUh,EndpointPathLiteral:()=>UUh,EnvironmentId:()=>DUh,FileId:()=>RUh,HttpMethod:()=>LUh,JqString:()=>NUh,OrgId:()=>wUh,PageId:()=>TUh,PropertyKey:()=>FUh,RoleId:()=>QUh,TokenId:()=>EUh,TypeId:()=>qUh,Url:()=>zUh,VersionId:()=>jUh,WebSocketId:()=>IUh,WebhookId:()=>CUh});function PUh(e){return e}function jUh(e){return e}function wUh(e){return e}function EUh(e){return e}function SUh(e){return e}function MUh(e){return e}function DUh(e){return e}function BUh(e){return e}function IUh(e){return e}function CUh(e){return e}function qUh(e){return e}function TUh(e){return e}function RUh(e){return e}function zUh(e){return e}function NUh(e){return e}function FUh(e){return e}function QUh(e){return e}function UUh(e){return e}var LUh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var VUh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var WUh={};var xtl={};Yt(xtl,{latest:()=>Qtl,v1:()=>Wtl,v2:()=>Gtl});var Qtl={};Yt(Qtl,{Layout:()=>xUh,MdxEngine:()=>OEB,TwitterCardSetting:()=>HUh,commons:()=>GUh,frontmatter:()=>Ntl,seo:()=>Ftl});var OEB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var GUh={};var Ntl={};Yt(Ntl,{Layout:()=>xUh});var xUh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Ftl={};Yt(Ftl,{TwitterCardSetting:()=>HUh});var HUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wtl={};Yt(Wtl,{commons:()=>Vtl,db:()=>KUh,read:()=>JUh,write:()=>Utl});var KUh={};var JUh={};var Utl={};Yt(Utl,{DocsRegistrationId:()=>AEB,FilePath:()=>mEB});function mEB(e){return e}function AEB(e){return e}var Vtl={};Yt(Vtl,{ContentAlignment:()=>ZUh,FontDisplay:()=>i4h,FontStyle:()=>r4h,HeaderPosition:()=>kUh,JsScriptStrategy:()=>t4h,ProgrammingLanguage:()=>$Uh,SearchbarPlacement:()=>YUh,TabsPlacement:()=>XUh,TwitterCardSetting:()=>e4h,commons:()=>Ltl});var Ltl={};Yt(Ltl,{ContentAlignment:()=>ZUh,FontDisplay:()=>i4h,FontStyle:()=>r4h,HeaderPosition:()=>kUh,JsScriptStrategy:()=>t4h,ProgrammingLanguage:()=>$Uh,SearchbarPlacement:()=>YUh,TabsPlacement:()=>XUh,TwitterCardSetting:()=>e4h});var $Uh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var YUh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var XUh={Header:"HEADER",Sidebar:"SIDEBAR"};var ZUh={Center:"CENTER",Left:"LEFT"};var kUh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var e4h={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var t4h={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var r4h={Normal:"normal",Italic:"italic"};var i4h={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Gtl={};Yt(Gtl,{read:()=>n4h,write:()=>a4h});var n4h={};var a4h={};var Ktl={};Yt(Ktl,{ChangelogEntryType:()=>u4h,GeneratorId:()=>PEB,GeneratorLanguage:()=>jEB,ReleaseType:()=>s4h,cli:()=>o4h,commons:()=>Htl,versions:()=>c4h});var o4h={};var Htl={};Yt(Htl,{ChangelogEntryType:()=>u4h,ReleaseType:()=>s4h});var u4h={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var s4h={Ga:"GA",Rc:"RC"};var c4h={};function PEB(e){return e}var jEB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Jtl={};Yt(Jtl,{PullRequestState:()=>l4h});var l4h={Open:"open",Closed:"closed",Merged:"merged"};var Xtl={};Yt(Xtl,{latest:()=>$tl,v1:()=>Ytl});var $tl={};Yt($tl,{NodeId:()=>SEB,ProductId:()=>MEB,Slug:()=>wEB,TabId:()=>EEB});function wEB(e){return e}function EEB(e){return e}function SEB(e){return e}function MEB(e){return e}var Ytl={};Yt(Ytl,{NavigationV1Availability:()=>qEB,NodeId:()=>IEB,ProductId:()=>CEB,Slug:()=>DEB,TabId:()=>BEB});function DEB(e){return e}function BEB(e){return e}function IEB(e){return e}function CEB(e){return e}var qEB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var ktl={};Yt(ktl,{Language:()=>f4h,VersionBump:()=>d4h,versions:()=>Ztl});var Ztl={};Yt(Ztl,{Language:()=>f4h,VersionBump:()=>d4h});var f4h={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var d4h={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var p4h={};var _4h={};var erl={};Yt(erl,{PayloadLocation:()=>h4h});var h4h={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var y4h={};var p0u=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Ho(e){return e!=null}var v4h=ue(m4a(),1);var b4h=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function wXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,v4h.default)(e,{special:b4h}).replace(/V\s(\d)/g,"V$1")}function g4h({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=uc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:wXt(a)},n.push(a)})}),r}var _0u=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function O4h(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var mo=class extends _0u{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${O4h(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},IC=class extends mo{},CY=class extends IC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var m4h="x-fern-base-path",A4h="x-fern-availability",h0u="x-fern-sdk-group-name",P4h="x-fern-global-headers",j4h="x-fern-sdk-method-name";var w4h="x-fern-webhook",E4h="x-fern-access-token-locator",S4h="x-fern-basic",M4h="x-fern-username-variable-name",D4h="x-fern-password-variable-name",B4h="x-fern-bearer",I4h="x-fern-token-variable-name",C4h="x-fern-header",q4h="x-fern-header-variable-name",T4h="x-fern-server-name",R4h="x-fern-examples";var y0u=class extends mo{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[T4h]}convert(){if(this.serverName!=null)return this.serverName}};var b0u=class extends mo{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uc.EnvironmentId(t),baseUrl:this.url}}};function vYi(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new b0u({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function tg(e){return typeof e=="object"&&Ho(e)&&"$ref"in e&&typeof e.$ref=="string"}function IL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(tg(n)&&(n=IL(n,t,r)),n)}function v0u(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return tg(r)?IL(r,t,void 0):r}var ELh=ue(bM());var g0u=class extends mo{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[S4h];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var O0u=class extends mo{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[D4h]}convert(){return this.passwordVariableName}};var m0u=class extends mo{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[M4h]}convert(){return this.usernameVariableName}};var A0u=class extends mo{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[B4h];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var P0u=class extends mo{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[I4h]}convert(){return this.tokenVariableName}};function z4h(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var N4h="x-bearer-format",F4h="x-code-samples",Q4h="x-codeSamples";var j0u=class extends mo{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[N4h]}convert(){return this.bearerFormat}};var w0u=class extends mo{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[C4h];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var E0u=class extends mo{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[q4h]}convert(){return this.headerVariableName}};function U4h(e){return e.type==="apiKey"}var kca=class extends mo{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){U4h(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new w0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new E0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new j0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function S0u(e){return e}function M0u(e){return e==="__proto__"}function D0u(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function ela(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function XYa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(XYa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function B0u(e){if(Array.isArray(e))return e.map(ela);if(typeof e=="symbol")return[e];e=XYa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function ZYa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(M0u(t))return r;let i=e[t];return i===void 0?D0u(t)?ZYa(e,B0u(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=ela(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return TEB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),M0u(t))return r;let i=e[t];return i===void 0?r:i}}}function TEB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||M0u(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function L4h(e){return function(t){return ZYa(t,e)}}function V4h(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function I0u(e){return e==null||typeof e!="object"&&typeof e!="function"}function trl(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function irl(e,t,r){return typeof r!="function"?irl(e,t,()=>{}):rrl(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:rrl(n,a,i,s)},new Map)}function rrl(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return REB(e,t,r,i);case"function":return Object.keys(t).length>0?rrl(e,{...t},r,i):trl(e,t);default:return V4h(e)?typeof t=="string"?t==="":!0:trl(e,t)}}function REB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return W4h(e,t,r,i);if(t instanceof Map)return zEB(e,t,r,i);if(t instanceof Set)return NEB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!I0u(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function zEB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function W4h(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function NEB(e,t,r,i){return t.size===0?!0:e instanceof Set?W4h([...e],[...t],r,i):!1}function C0u(e,t){return irl(e,t,()=>{})}function G4h(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function q0u(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var x4h="[object RegExp]",T0u="[object String]",R0u="[object Number]",z0u="[object Boolean]",N0u="[object Arguments]",H4h="[object Symbol]",K4h="[object Date]",J4h="[object Map]",$4h="[object Set]",Y4h="[object Array]";var X4h="[object ArrayBuffer]",Z4h="[object Object]";var k4h="[object DataView]",eLh="[object Uint8Array]",tLh="[object Uint8ClampedArray]",rLh="[object Uint16Array]",iLh="[object Uint32Array]";var nLh="[object Int8Array]",aLh="[object Int16Array]",oLh="[object Int32Array]";var uLh="[object Float32Array]",sLh="[object Float64Array]";function cLh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lLh(e,t){return gYi(e,void 0,e,new Map,t)}function gYi(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(I0u(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=gYi(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,gYi(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(gYi(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(cLh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=gYi(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,eWt(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof e=="object"&&FEB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),eWt(o,e,r,i,n),o}return e}function eWt(e,t,r=e,i,n){let a=[...Object.keys(t),...G4h(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=gYi(t[c],c,r,i,n))}}function FEB(e){switch(q0u(e)){case N0u:case Y4h:case X4h:case k4h:case z0u:case K4h:case uLh:case sLh:case nLh:case aLh:case oLh:case J4h:case R0u:case Z4h:case x4h:case $4h:case T0u:case H4h:case eLh:case tLh:case rLh:case iLh:return!0;default:return!1}}function fLh(e){return gYi(e,void 0,e,new Map,void 0)}function dLh(e){return e=fLh(e),t=>C0u(t,e)}function pLh(e,t){return lLh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case R0u:case T0u:case z0u:{let c=new e.constructor(e?.valueOf());return eWt(c,e),c}case N0u:{let c={};return eWt(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function _Lh(e){return pLh(e)}var QEB=/^(?:0|[1-9]\d*)$/;function hLh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return QEB.test(e)}}function yLh(e){return e!==null&&typeof e=="object"&&q0u(e)==="[object Arguments]"}function bLh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&D0u(t)&&e?.[t]==null?r=B0u(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||yLh(i))&&hLh(a)&&a<i.length))return!1;i=i[a]}return!0}function vLh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=ela(e);break}}return t=_Lh(t),function(r){let i=ZYa(r,e);return i===void 0?bLh(r,e):t===void 0?i===void 0:C0u(i,t)}}function gLh(e){if(e==null)return S0u;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?vLh(e[0],e[1]):dLh(e);case"string":case"symbol":case"number":return L4h(e)}}function OLh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function F0u(e,t=S0u){return e==null?{}:OLh(e,gLh(t))}function mLh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var UEB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function ALh(e){return Array.from(e.match(UEB)??[])}function PLh(e){let t=ALh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>mLh(n)).join("")}`}function jLh(e){return typeof e!="string"&&(e=XYa(e)),e.replace(/['\u2019]/g,"")}function tWt(e){return PLh(jLh(e))}function ij(e){if(e!=null)return Array.isArray(e)?e:[e]}function Q0u({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${LEB(o)}${VEB(e)}.${WEB(i,n,a,c)}`}function LEB(e){return e?"webhook_":"endpoint_"}function VEB(e){return e!=null?ij(e)?.map(t=>tWt(t)).join("/"):""}function WEB(e,t,r,i){return e||t||tWt(r??"")||tWt(i??"")}function wLh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var U0u=class extends mo{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[E4h],this.accessTokenLocator!=null&&(wLh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var L0u=class extends mo{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new kca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new U0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Q0u({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uc.EndpointId(r),accessTokenLocator:uc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var tla=class extends mo{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new g0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new m0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new O0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new A0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new P0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{z4h(this.input)?(this.authScheme="header",this.headerAuthNode=new kca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new L0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new ELh.UnreachableCaseError(this.authScheme);return}}};var rla=class extends mo{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=v0u(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new tla({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Ho))}};var V0u=class extends mo{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[m4h],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function SLh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function MLh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function ila(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>ij(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!SLh(n))&&(o=MLh(o,o.type==="enum"?o.default:void 0)),{key:uc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Ho)).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function W0u(e,t){return tg(e)?IL(e,t,void 0):e}function OYi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function DLh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function BLh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var ILh=ue(bM());var nrl=["decimal","decimal128","double-int","double","float","sf-decimal"],arl=["int16","int32","int64","int8","sf-integer","uint8"],orl=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],url=["beta","pre-release","in-development","generally-available","deprecated"];function CC(e,t){return tg(e)?IL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ESe=class extends mo{availability;constructor(t){super(t),this.safeParse()}parse(){if(CC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[A4h];r!=null&&(url.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${url.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uc.Availability.Beta;case"in-development":return uc.Availability.InDevelopment;case"generally-available":return uc.Availability.GenerallyAvailable;case"deprecated":return uc.Availability.Deprecated;case void 0:return;default:new ILh.UnreachableCaseError(this.availability);return}}};var x0u=ue(bM());function CLh(e){return typeof e=="object"&&e!=null&&"language"in e}function qLh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function TLh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function RLh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function G0u(e){return typeof e=="object"&&e!=null&&"event"in e}function srl(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(G0u)}function mYi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zLh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var H0u=class extends mo{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[R4h]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return mYi(o)?[n,{type:"filenameWithData",filename:o.filename,data:uc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>mYi(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:uc.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new x0u.UnreachableCaseError(a.multipartType);return}}).filter(Ho))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=zLh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new x0u.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{TLh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{srl(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!srl(r.response)&&RLh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new x0u.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{CLh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):qLh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[uc.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var kYa=class extends mo{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[h0u]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uc.api.v1.SubpackageId(tWt(r)))}};var K0u=class extends mo{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[j4h]}convert(){return this.sdkMethodName}};var J0u=class extends mo{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[w4h]}convert(){return this.isWebhook}};var $0u=class extends mo{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[F4h]??[],...this.input[Q4h]??[]],this.codeSamples.forEach(t=>{[...Object.values(uc.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var oOn=ue(bM());function crl(e,t){return tg(e)?IL(e,t,void 0):e}function NLh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var TF="",EXt=class extends mo{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(mYi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>mYi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new oOn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=crl(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=crl(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(G0u)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return mYi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>mYi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uc.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new oOn.UnreachableCaseError(i.multipartType);return}}).filter(Ho))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new oOn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Ho));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Ho));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:NLh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?wXt(this.name):this.summary!=null?wXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function FLh(e,t){return tg(e)?IL(e,t,void 0):e}var XLh=ue(bM());var QLh="#/components/schemas/";function nla(e){if(e.$ref.startsWith(QLh))return e.$ref.replace(QLh,"")}function p4i(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function AYi(e){return typeof e.type=="string"&&e.type==="array"}function ULh(e){return e.type==="boolean"}function LLh(e){return e.type==="integer"}function PYi(e){return!Array.isArray(e.type)&&!AYi(e)}function VLh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||PYi(t)||AYi(t))}function WLh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function GLh(e){return e.type==="null"}function xLh(e){return e.type==="number"}function lrl(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function HLh(e){return e.type==="string"}var Y0u=class extends CY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new hw({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return ij(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var X0u=class extends IC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Z0u=class extends CY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Ho)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>ij(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Ho).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(p4i).filter(Ho):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function k0u(e){return e!=null&&e.length>0?e:[void 0]}var ala=class extends CY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new hw({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(tg(t))return nla(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new hw({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Ho))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return ila(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:ij(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Ho)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>k0u(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=CC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new hw({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var ewu=class extends CY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>CC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>CC(t,this.context.document)?.type!=="null"?new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Ho);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=CC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new hw({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Ho);return this.isNullable&&n!=null?n.map(p4i).filter(Ho):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>ij(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??wXt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Ho)).filter(Ho)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>ij(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?wXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?wXt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Ho)).filter(Ho)}:void 0,i=this.isNullable?p4i(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var twu=class extends IC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var jYi=class extends IC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(tg(r)){let n=CC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Ho),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var KLh=ue(bM());function GEB(e){return arl.includes(e)}var rwu=class extends IC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(GEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${arl.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new KLh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var iwu=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return p4i({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var JLh=ue(bM());function xEB(e){return nrl.includes(e)}var nwu=class extends IC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(xEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${nrl.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new JLh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var $Lh=ue(bM());function HEB(e){return orl.includes(e)}var awu=class extends IC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new $Lh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(HEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${orl.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new jYi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var YLh=ue(bM());var owu=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,YLh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var uOn=class extends CY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=nla(this.input);let t=CC(this.input,this.context.document);t?.enum!=null&&PYi(t)&&(this.maybeEnumConverterNode=new jYi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=CC(this.input,this.context.document);if(r!=null)return new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var hw=class e extends CY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),PYi(this.input)&&WLh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),tg(this.input)){let t=nla(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new uOn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new X0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(VLh(this.input))this.typeShapeNode=new Z0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new ewu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(lrl(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ala({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYi(this.input)&&this.input.enum!=null)this.typeShapeNode=new jYi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":lrl(this.input)&&(this.typeShapeNode=new ala({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":AYi(this.input)&&(this.typeShapeNode=new Y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":ULh(this.input)&&(this.typeShapeNode=new twu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":LLh(this.input)&&(this.typeShapeNode=new rwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":xLh(this.input)&&(this.typeShapeNode=new nwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":HLh(this.input)&&(this.typeShapeNode=new awu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":GLh(this.input)&&(this.typeShapeNode=new iwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new XLh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new ala({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new owu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!tg(this.input)&&(!AYi(this.input)&&this.input==null||AYi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=ij(t)?.map(i=>this.nullable?p4i(i):i).filter(Ho);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function wYi(e){if(e!=null)return ila(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Ho))}var SXt=class extends IC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;tg(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new ESe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=FLh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ZLh(e,t){return tg(e)?IL(e,t,void 0):e}var frl=ue(bM());function uwu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var kLh=ue(vnc(),1),ola=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=kLh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function KEB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var swu=class extends mo{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),KEB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(tg(r)?n=v0u(r.$ref,this.context.document):n=r,n!=null)return[t,new tla({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Ho)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uc.api.latest.AuthSchemeId(t),i]}).filter(Ho)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=ij(r.convert());return n==null?[t,void 0]:[uc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Ho(r))):void 0}}};var cwu=class extends hw{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=CC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${tg(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=CC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var lwu=class extends mo{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=CC(this.input.schema,this.context.document);this.availability=new ESe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=tg(this.input.schema)?new uOn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=ola.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new cwu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Ho))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[TF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[TF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:ij(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=tWt([this.method,this.path,this.contentType,"request"].join("_"));return uwu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new frl.UnreachableCaseError(n);return}}).filter(Ho)}convert(){if(this.schema instanceof uOn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=ij(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:uc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new frl.UnreachableCaseError(n.multipartType),[]}}).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var fwu=class extends mo{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ZLh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new lwu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>ij(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Ho)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>ij(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Ho)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var eVh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function tVh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var dwu=ue(bM());var rVh="application/json";var iVh="application/octet-stream";function nVh(e,t){return e===t||t===TF||e===TF}var eXa=class extends mo{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)nVh(c,a)&&(i.add(c),this.examples?.push(new EXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,OYi(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new EXt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,OYi(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new EXt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,OYi(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new EXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,OYi(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[TF];if(a!=null)for(let o of a)this.examples?.push(new EXt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,OYi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=ola.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=rVh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=iVh,this.contentSubtype=CC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=F0u(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]=[{value:this.input.example}]);let i=CC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=F0u(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[TF]??=[],r[TF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==TF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Ho(d)&&c!==TF);Object.keys(r).every(c=>c===TF)||this.matchExamplesByIndex(a,o),!n.has(TF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return ij(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new dwu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return ij(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=tWt([this.method,this.path,this.statusCode,"response"].join("_"));return uwu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new dwu.UnreachableCaseError(i);return}}).filter(Ho)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new dwu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var tXa=class extends mo{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=tVh(this.input,this.context.document);if(r==null){this.context.errors.error({message:tg(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new SXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new eXa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new eXa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Ho)}};var pwu=class extends mo{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new tXa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new tXa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return k0u(wYi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(Ho))})))}).filter(Ho)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=ij(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??eVh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Ho)})).filter(Ho)})).filter(Ho)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var EYi=class extends mo{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new EXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,OYi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=vYi(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new J0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(tg(i)){let a=W0u(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new $0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new fwu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new pwu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new rla({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new kYa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new kYa({input:{[h0u]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new K0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Q0u({namespace:ij(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Ho),this.xFernExamplesNode=new H0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Ho)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uc.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(Ho),n=BLh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:DLh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:wYi(this.queryParameters)?.flat(),headers:wYi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Ho)}}).filter(Ho);let a=this.servers?.map(u=>u.convert()).filter(Ho),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(Ho);return this.endpointIds.map((u,l)=>({id:uc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>uc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>uc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:wYi(this.pathParameters)?.flat(),queryParameters:wYi(this.queryParameters)?.flat(),requestHeaders:wYi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var ula=class extends mo{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=vYi(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new EYi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new EYi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new EYi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new EYi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new EYi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Ho)}};function _wu(e){return"payloads"in e}var hwu=class extends mo{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new ula({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:vYi(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Ho)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{_wu(a)?r[uc.WebhookId(a.id)]=a:t[uc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var ywu=class extends mo{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[P4h]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||W0u(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new SXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return ila(this.globalHeaders,this.requiredProperties)?.flat()}};function aVh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var bwu=class extends mo{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=aVh(a,this.context.document);if(o!=null)return new ula({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Ho)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{_wu(i)&&(t[uc.WebhookId(i.id)]=i)}),t),{})}};var vwu=class extends mo{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=vYi(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new rla({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new V0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new hwu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new bwu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new swu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new ywu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=zve(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=g4h({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:uc.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function drl(e,t){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let r=new W8t(e.absoluteFilePath),i=await bSe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i,loadAiExamples:!0}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new p0u,generatedTypes:{}},d=new vwu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=m$n(a,d.convert())}return a}var PKh=ue(hrl(),1),jKh=ue(oEu(),1),BSu=require("fs/promises"),wKh=ue(require("http"),1),EKh=ue(require("path"),1);var c6h=require("events"),fEu=ue(require("fs"),1),bOn=ue(require("path"),1);var x5h=ue(require("os"),1),H5h=300,qYi=20,jXa=1e7,K5h=x5h.default.platform();var h1B=K5h==="darwin",Ril=K5h==="win32",TYi=h1B||Ril,J5h=3e3,$5h=2e4,zil=1250;var IXt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(IXt||(IXt={}));var yOn;(function(e){e.CHANGE="change",e.RENAME="rename"})(yOn||(yOn={}));var wXa;(function(e){e.CHANGE="change",e.ERROR="error"})(wXa||(wXa={}));var rf;(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"})(rf||(rf={}));var Fx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Fx||(Fx={}));var y1B=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let O=Date.now(),A=O-d,j=O-s,M=A>=t||j>=a;return[O,M]},l=O=>{if(s=O,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{g(0)},_=()=>{c&&(p(),l(Date.now()))},h=O=>{if(s=O,i)return l(O)},y=O=>{if(n&&o)return l(O);o=void 0},b=()=>{c=void 0;let[O,A]=u();return A?y(O):v(O)},v=O=>{let A=O-d,j=O-s,M=t-A,w=a-j,D=Math.min(M,w);return g(D)},g=O=>{c&&clearTimeout(c),!(O<=0)&&(c=setTimeout(b,O))},m=(...O)=>{let[A,j]=u(),M=!!c;if(o=O,d=A,(j||!c)&&g(t),j)return M?l(A):h(A)};return m.cancel=p,m.flush=_,m},uEu=y1B;var Uil=ue(require("fs"),1),cEu=ue(require("path"),1);var dm=ue(require("fs"),1),CL=require("util");var h4i=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},CXt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var Nil=ue(require("process"),1),Y5h=Nil.default.getuid?!Nil.default.getuid():!1,X5h=1e4,zY=()=>{};var EXa={isChangeErrorOk:e=>{if(!EXa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Y5h&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!EXa.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(!EXa.isNodeError(e))throw e;if(!EXa.isChangeErrorOk(e))throw e}},qC=EXa;var Fil=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=X5h,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(i),i=()=>t(r);this.add(i)}),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()}}}}},Z5h=new Fil;var y4i=(e,t)=>function(i){return function n(...a){return Z5h.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},b4i=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var b1B={attempt:{chmod:h4i((0,CL.promisify)(dm.default.chmod),qC.onChangeError),chown:h4i((0,CL.promisify)(dm.default.chown),qC.onChangeError),close:h4i((0,CL.promisify)(dm.default.close),zY),fsync:h4i((0,CL.promisify)(dm.default.fsync),zY),mkdir:h4i((0,CL.promisify)(dm.default.mkdir),zY),realpath:h4i((0,CL.promisify)(dm.default.realpath),zY),stat:h4i((0,CL.promisify)(dm.default.stat),zY),unlink:h4i((0,CL.promisify)(dm.default.unlink),zY),chmodSync:CXt(dm.default.chmodSync,qC.onChangeError),chownSync:CXt(dm.default.chownSync,qC.onChangeError),closeSync:CXt(dm.default.closeSync,zY),existsSync:CXt(dm.default.existsSync,zY),fsyncSync:CXt(dm.default.fsync,zY),mkdirSync:CXt(dm.default.mkdirSync,zY),realpathSync:CXt(dm.default.realpathSync,zY),statSync:CXt(dm.default.statSync,zY),unlinkSync:CXt(dm.default.unlinkSync,zY)},retry:{close:y4i((0,CL.promisify)(dm.default.close),qC.isRetriableError),fsync:y4i((0,CL.promisify)(dm.default.fsync),qC.isRetriableError),open:y4i((0,CL.promisify)(dm.default.open),qC.isRetriableError),readFile:y4i((0,CL.promisify)(dm.default.readFile),qC.isRetriableError),rename:y4i((0,CL.promisify)(dm.default.rename),qC.isRetriableError),stat:y4i((0,CL.promisify)(dm.default.stat),qC.isRetriableError),write:y4i((0,CL.promisify)(dm.default.write),qC.isRetriableError),writeFile:y4i((0,CL.promisify)(dm.default.writeFile),qC.isRetriableError),closeSync:b4i(dm.default.closeSync,qC.isRetriableError),fsyncSync:b4i(dm.default.fsyncSync,qC.isRetriableError),openSync:b4i(dm.default.openSync,qC.isRetriableError),readFileSync:b4i(dm.default.readFileSync,qC.isRetriableError),renameSync:b4i(dm.default.renameSync,qC.isRetriableError),statSync:b4i(dm.default.statSync,qC.isRetriableError),writeSync:b4i(dm.default.writeSync,qC.isRetriableError),writeFileSync:b4i(dm.default.writeFileSync,qC.isRetriableError)}},k5h=b1B;var sEu=ue(require("fs"),1),SXa=ue(require("path"),1);var Qil=()=>{};var v1B=()=>{let e=Qil,t=Qil,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},e6h=v1B;var g1B=()=>{let{promise:e,resolve:t,isPending:r}=e6h(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},t6h=g1B;var r6h={then:e=>{e()}};var i6h=e=>Array.isArray(e)?e:[e],n6h=e=>typeof e=="function";var O1B=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=i6h(a).map(W=>n6h(W)?W:x=>W.test(x)),c=W=>o.some(x=>x(W)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,g={},m={},O=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:g,map:m},{promise:M,increment:w,decrement:D}=t6h(),B=0,R=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.directories.push(x),W.directoriesNames.add(Ee),u.push(x),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),O.add(x),!(se>=i)&&(B>=n||$(x,se+1)))},T=(W,x,Ee)=>{O.has(x)||B>=n||(B+=1,W.files.push(x),W.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),O.add(x))},q=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.symlinks.push(x),W.symlinksNames.add(Ee),b.push(x),v.add(Ee),g.propertyIsEnumerable(Ee)||(g[Ee]=[]),g[Ee].push(x),O.add(x),r&&(se>=i||B>=n||de(x,se+1)))},z=(W,x,Ee,se,Oe)=>{d.aborted||c(x)||(se.isDirectory()?R(W,x,Ee,Oe):se.isFile()?T(W,x,Ee):se.isSymbolicLink()&&q(W,x,Ee,Oe))},N=(W,x,Ee,se)=>{if(d.aborted)return;let Oe=x===SXa.default.sep?"":SXa.default.sep,Fe=Ee.name,ae=`${x}${Oe}${Fe}`;c(ae)||(Ee.isDirectory()?R(W,ae,Fe,se):Ee.isFile()?T(W,ae,Fe):Ee.isSymbolicLink()&&q(W,ae,Fe,se))},H=(W,x,Ee,se)=>{for(let Oe=0,Fe=Ee.length;Oe<Fe;Oe++)N(W,x,Ee[Oe],se)},$=(W,x)=>{d.aborted||x>i||B>=n||(w(),sEu.default.readdir(W,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||r6h).then(()=>{let Fe=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Fe,W,se,x),D()})}))},de=(W,x)=>{w(),sEu.default.realpath(W,(Ee,se)=>{if(Ee||d.aborted)return D();sEu.default.stat(se,(Oe,Fe)=>{if(Oe||d.aborted)return D();let ae=SXa.default.basename(se),re=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Fe,x),D()})})};return(async(W,x=1)=>(W=SXa.default.normalize(W),O.add(W),$(W,x),await M,d.aborted?A:j))(e)},a6h=O1B;var qXt={lang:{debounce:uEu,attempt:e=>{try{return e()}catch(t){return qXt.lang.castError(t)}},castArray:e=>qXt.lang.isArray(e)?e:[e],castError:e=>qXt.lang.isError(e)?e:qXt.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(qXt.lang.isNaN(e))return qXt.lang.isNaN(t);if(qXt.lang.isPrimitive(e)||qXt.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(cEu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Uil.default.realpathSync.native(e):Uil.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===cEu.default.sep&&t.length-e.length>cEu.default.sep.length,poll:(e,t=$5h)=>k5h.retry.stat(t)(e,{bigint:!0}).catch(qXt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await a6h(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Gp=qXt;var lEu=ue(require("path"),1);var Lil=class{constructor(t,r,i){this.base=i,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||Gp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=H5h){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Gp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===rf.CHANGE&&c===rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??qYi:Math.min(1,this.options.depth??qYi),o=this.options.limit??jXa,[c,d]=await Gp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Gp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!TYi&&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(rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(lEu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(lEu.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(rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===rf.ADD?this.onTargetAdd(i):r===rf.ADD_DIR?this.onTargetAddDir(i):r===rf.CHANGE?this.onTargetChange(i):r===rf.UNLINK?this.onTargetUnlink(i):r===rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=yOn.CHANGE,r){if(this.watcher.isClosed())return;let i=lEu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){Ril&&t.code==="EPERM"?this.onWatcherChange(yOn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(wXa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(wXa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(yOn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&TYi&&this.options.native!==!1?this.options.depth??qYi:Math.min(1,this.options.depth??qYi),i=this.options.limit??jXa,[n,a]=await Gp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(yOn.CHANGE,c,t)}))}}},o6h=Lil;var Qx={interval:100,intervalId:void 0,fns:new Map,init:()=>{Qx.intervalId||(Qx.intervalId=setInterval(Qx.resolve,Qx.interval))},reset:()=>{Qx.intervalId&&(clearInterval(Qx.intervalId),delete Qx.intervalId)},add:(e,t)=>{Qx.fns.set(e,Date.now()+t),Qx.init()},remove:e=>{Qx.fns.delete(e)},resolve:()=>{if(!Qx.fns.size)return Qx.reset();let e=Date.now();for(let[t,r]of Qx.fns)r>=e||(Qx.remove(t),t())}},MXa=Qx;var DXa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=zil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Gp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),MXa.remove(s)},s=()=>{d(),c()};MXa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=zil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),MXa.remove(s)},s=()=>{d(),c()};MXa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,rf.ADD,IXt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,rf.ADD_DIR,IXt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,rf.UNLINK,IXt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,rf.UNLINK_DIR,IXt.DIR);return this.getLockUnlink({ino:i,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}}};DXa.DIR_EVENTS={add:rf.ADD_DIR,rename:rf.RENAME_DIR,unlink:rf.UNLINK_DIR};DXa.FILE_EVENTS={add:rf.ADD,change:rf.CHANGE,rename:rf.RENAME,unlink:rf.UNLINK};var u6h=DXa;var Vil=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Gp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Gp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Gp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Gp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Gp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Gp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Wil=Vil;var Gil=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}},s6h=Gil;var xil=class{constructor(){this.inos={},this.paths=new Wil,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Gp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new s6h(i)}reset(){this.inos={},this.paths=new Wil,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,rf.ADD,n),[rf.ADD];if(n.isDirectory())return this.updateIno(t,rf.ADD_DIR,n),[rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,rf.UNLINK,i),[rf.UNLINK];if(i.isDirectory())return this.updateIno(t,rf.UNLINK_DIR,i),[rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,rf.CHANGE,n),[rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,rf.UNLINK,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK,rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD,n),[rf.UNLINK_DIR,rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK_DIR,rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?IXt.FILE:IXt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},Hil=xil;var Kil=class e extends c6h.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Fx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Fx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Fx.READY,n)),this._locker=new u6h(this),this._roots=new Set,this._poller=new Hil,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Gp.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(Fx.CLOSE))}error(t){if(this.isClosed())return!1;let r=Gp.lang.castError(t);return this.emit(Fx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Fx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Fx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Gp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,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,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new o6h(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Gp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=bOn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??qYi))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&TYi&&u.options.native!==!1)))return!0;if(!TYi)break;let s=bOn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Gp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||TYi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:fEu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=bOn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||TYi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??qYi,c=r.limit??jXa,[d]=await Gp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Gp.fs.getDepth(t);for(let l of d){let p=Gp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(Fx.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(Fx.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=bOn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new Hil,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Gp.lang.noop;if(this.pollerExists(t,r))return Gp.lang.noop;let n={...r,interval:r.pollingInterval??J5h},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(Fx.CLOSE,c),fEu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Fx.CLOSE,c),fEu.default.unwatchFile(t,i)};return Gp.lang.attempt(o),()=>Gp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Gp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Gp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=bOn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Gp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=bOn.default.dirname(t);return(await Gp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Gp.lang.noop){if(Gp.lang.isFunction(t))return this.watch([],{},t);if(Gp.lang.isUndefined(t))return this.watch([],r,i);if(Gp.lang.isFunction(r))return this.watch(t,{},r);if(Gp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Gp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Gp.lang.noop&&this.on(Fx.ALL,i),r.readdirMap=void 0,this.ready())}},dEu=Kil;hru();var Pla=require("fs/promises"),l6h=require("os"),f6h=ue(require("path"),1),m1B=".fern",A1B="logs";function P1B(){return"cli@3.49.1"}var BXa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Tt(Sr.of((0,l6h.homedir)()),He.of(m1B)),r=Tt(t,He.of(A1B));await Ai(r)||await(0,Pla.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Tt(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${f6h.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
1949
|
+
`;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Nt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??cS(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Nt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??cS(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Kfn(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new aOn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Nt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??cS(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??cS(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):RG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(us),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:RG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Kfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:RG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function bEB(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${Rx(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function vEB(e){switch(e){case"beta":return Nt.V1.NavigationV1Availability.Beta;case"deprecated":return Nt.V1.NavigationV1Availability.Deprecated;case"ga":return Nt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Nt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function BL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof jS?t:null))).filter(us)}async function jtl(e,t,r){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return Tx({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var uc={};Yt(uc,{AlgoliaSearchIndex:()=>rUh,ApiDefinitionId:()=>PUh,ApiId:()=>SUh,Availability:()=>VUh,DocsConfigId:()=>MUh,EndpointId:()=>BUh,EndpointPathLiteral:()=>UUh,EnvironmentId:()=>DUh,FileId:()=>RUh,HttpMethod:()=>LUh,IndexSegmentId:()=>iUh,JqString:()=>NUh,OrgId:()=>wUh,PageId:()=>TUh,PayloadLocation:()=>h4h,PropertyKey:()=>FUh,PullRequestState:()=>l4h,RoleId:()=>QUh,TokenId:()=>EUh,TypeId:()=>qUh,Url:()=>zUh,VersionId:()=>jUh,WebSocketId:()=>IUh,WebhookId:()=>CUh,algolia:()=>wtl,api:()=>Rtl,commons:()=>ztl,diff:()=>WUh,docs:()=>xtl,generators:()=>Ktl,git:()=>Jtl,navigation:()=>Xtl,sdks:()=>ktl,snippets:()=>p4h,snippetsFactory:()=>_4h,templates:()=>erl,tokens:()=>y4h});var wtl={};Yt(wtl,{AlgoliaSearchIndex:()=>rUh,IndexSegmentId:()=>iUh});function rUh(e){return e}function iUh(e){return e}var Rtl={};Yt(Rtl,{latest:()=>Mtl,v1:()=>Ttl});var Mtl={};Yt(Mtl,{AuthSchemeId:()=>nUh,WebhookHttpMethod:()=>sUh,auth:()=>Etl,commons:()=>aUh,endpoint:()=>oUh,type_:()=>uUh,webhook:()=>Stl,websocket:()=>cUh});var Etl={};Yt(Etl,{AuthSchemeId:()=>nUh});function nUh(e){return e}var aUh={};var oUh={};var uUh={};var Stl={};Yt(Stl,{WebhookHttpMethod:()=>sUh});var sUh={Get:"GET",Post:"POST"};var cUh={};var Ttl={};Yt(Ttl,{SubpackageId:()=>gUh,WebSocketMessageId:()=>OUh,WebSocketMessageOrigin:()=>mUh,WebhookHttpMethod:()=>AUh,commons:()=>qtl,db:()=>Dtl,read:()=>Itl,register:()=>Ctl});var Dtl={};Yt(Dtl,{endpoint:()=>lUh});var lUh={};var Itl={};Yt(Itl,{SupportedLanguage:()=>fUh,endpoint:()=>Btl,type_:()=>dUh,webhook:()=>pUh,websocket:()=>_Uh});var Btl={};Yt(Btl,{SupportedLanguage:()=>fUh});var fUh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var dUh={};var pUh={};var _Uh={};var Ctl={};Yt(Ctl,{SourceId:()=>gEB,endpoint:()=>hUh,type_:()=>yUh,webhook:()=>bUh,websocket:()=>vUh});var hUh={};var yUh={};var bUh={};var vUh={};function gEB(e){return e}var qtl={};Yt(qtl,{SubpackageId:()=>gUh,WebSocketMessageId:()=>OUh,WebSocketMessageOrigin:()=>mUh,WebhookHttpMethod:()=>AUh});function gUh(e){return e}function OUh(e){return e}var mUh={Client:"client",Server:"server"};var AUh={Get:"GET",Post:"POST"};var ztl={};Yt(ztl,{ApiDefinitionId:()=>PUh,ApiId:()=>SUh,Availability:()=>VUh,DocsConfigId:()=>MUh,EndpointId:()=>BUh,EndpointPathLiteral:()=>UUh,EnvironmentId:()=>DUh,FileId:()=>RUh,HttpMethod:()=>LUh,JqString:()=>NUh,OrgId:()=>wUh,PageId:()=>TUh,PropertyKey:()=>FUh,RoleId:()=>QUh,TokenId:()=>EUh,TypeId:()=>qUh,Url:()=>zUh,VersionId:()=>jUh,WebSocketId:()=>IUh,WebhookId:()=>CUh});function PUh(e){return e}function jUh(e){return e}function wUh(e){return e}function EUh(e){return e}function SUh(e){return e}function MUh(e){return e}function DUh(e){return e}function BUh(e){return e}function IUh(e){return e}function CUh(e){return e}function qUh(e){return e}function TUh(e){return e}function RUh(e){return e}function zUh(e){return e}function NUh(e){return e}function FUh(e){return e}function QUh(e){return e}function UUh(e){return e}var LUh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var VUh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var WUh={};var xtl={};Yt(xtl,{latest:()=>Qtl,v1:()=>Wtl,v2:()=>Gtl});var Qtl={};Yt(Qtl,{Layout:()=>xUh,MdxEngine:()=>OEB,TwitterCardSetting:()=>HUh,commons:()=>GUh,frontmatter:()=>Ntl,seo:()=>Ftl});var OEB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var GUh={};var Ntl={};Yt(Ntl,{Layout:()=>xUh});var xUh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Ftl={};Yt(Ftl,{TwitterCardSetting:()=>HUh});var HUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wtl={};Yt(Wtl,{commons:()=>Vtl,db:()=>KUh,read:()=>JUh,write:()=>Utl});var KUh={};var JUh={};var Utl={};Yt(Utl,{DocsRegistrationId:()=>AEB,FilePath:()=>mEB});function mEB(e){return e}function AEB(e){return e}var Vtl={};Yt(Vtl,{ContentAlignment:()=>ZUh,FontDisplay:()=>i4h,FontStyle:()=>r4h,HeaderPosition:()=>kUh,JsScriptStrategy:()=>t4h,ProgrammingLanguage:()=>$Uh,SearchbarPlacement:()=>YUh,TabsPlacement:()=>XUh,TwitterCardSetting:()=>e4h,commons:()=>Ltl});var Ltl={};Yt(Ltl,{ContentAlignment:()=>ZUh,FontDisplay:()=>i4h,FontStyle:()=>r4h,HeaderPosition:()=>kUh,JsScriptStrategy:()=>t4h,ProgrammingLanguage:()=>$Uh,SearchbarPlacement:()=>YUh,TabsPlacement:()=>XUh,TwitterCardSetting:()=>e4h});var $Uh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var YUh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var XUh={Header:"HEADER",Sidebar:"SIDEBAR"};var ZUh={Center:"CENTER",Left:"LEFT"};var kUh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var e4h={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var t4h={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var r4h={Normal:"normal",Italic:"italic"};var i4h={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Gtl={};Yt(Gtl,{read:()=>n4h,write:()=>a4h});var n4h={};var a4h={};var Ktl={};Yt(Ktl,{ChangelogEntryType:()=>u4h,GeneratorId:()=>PEB,GeneratorLanguage:()=>jEB,ReleaseType:()=>s4h,cli:()=>o4h,commons:()=>Htl,versions:()=>c4h});var o4h={};var Htl={};Yt(Htl,{ChangelogEntryType:()=>u4h,ReleaseType:()=>s4h});var u4h={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var s4h={Ga:"GA",Rc:"RC"};var c4h={};function PEB(e){return e}var jEB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Jtl={};Yt(Jtl,{PullRequestState:()=>l4h});var l4h={Open:"open",Closed:"closed",Merged:"merged"};var Xtl={};Yt(Xtl,{latest:()=>$tl,v1:()=>Ytl});var $tl={};Yt($tl,{NodeId:()=>SEB,ProductId:()=>MEB,Slug:()=>wEB,TabId:()=>EEB});function wEB(e){return e}function EEB(e){return e}function SEB(e){return e}function MEB(e){return e}var Ytl={};Yt(Ytl,{NavigationV1Availability:()=>qEB,NodeId:()=>IEB,ProductId:()=>CEB,Slug:()=>DEB,TabId:()=>BEB});function DEB(e){return e}function BEB(e){return e}function IEB(e){return e}function CEB(e){return e}var qEB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var ktl={};Yt(ktl,{Language:()=>f4h,VersionBump:()=>d4h,versions:()=>Ztl});var Ztl={};Yt(Ztl,{Language:()=>f4h,VersionBump:()=>d4h});var f4h={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var d4h={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var p4h={};var _4h={};var erl={};Yt(erl,{PayloadLocation:()=>h4h});var h4h={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var y4h={};var p0u=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Ho(e){return e!=null}var v4h=ue(m4a(),1);var b4h=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function wXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,v4h.default)(e,{special:b4h}).replace(/V\s(\d)/g,"V$1")}function g4h({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=uc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:wXt(a)},n.push(a)})}),r}var _0u=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function O4h(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var mo=class extends _0u{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${O4h(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},IC=class extends mo{},CY=class extends IC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var m4h="x-fern-base-path",A4h="x-fern-availability",h0u="x-fern-sdk-group-name",P4h="x-fern-global-headers",j4h="x-fern-sdk-method-name";var w4h="x-fern-webhook",E4h="x-fern-access-token-locator",S4h="x-fern-basic",M4h="x-fern-username-variable-name",D4h="x-fern-password-variable-name",B4h="x-fern-bearer",I4h="x-fern-token-variable-name",C4h="x-fern-header",q4h="x-fern-header-variable-name",T4h="x-fern-server-name",R4h="x-fern-examples";var y0u=class extends mo{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[T4h]}convert(){if(this.serverName!=null)return this.serverName}};var b0u=class extends mo{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uc.EnvironmentId(t),baseUrl:this.url}}};function vYi(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new b0u({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function tg(e){return typeof e=="object"&&Ho(e)&&"$ref"in e&&typeof e.$ref=="string"}function IL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(tg(n)&&(n=IL(n,t,r)),n)}function v0u(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return tg(r)?IL(r,t,void 0):r}var ELh=ue(bM());var g0u=class extends mo{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[S4h];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var O0u=class extends mo{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[D4h]}convert(){return this.passwordVariableName}};var m0u=class extends mo{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[M4h]}convert(){return this.usernameVariableName}};var A0u=class extends mo{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[B4h];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var P0u=class extends mo{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[I4h]}convert(){return this.tokenVariableName}};function z4h(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var N4h="x-bearer-format",F4h="x-code-samples",Q4h="x-codeSamples";var j0u=class extends mo{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[N4h]}convert(){return this.bearerFormat}};var w0u=class extends mo{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[C4h];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var E0u=class extends mo{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[q4h]}convert(){return this.headerVariableName}};function U4h(e){return e.type==="apiKey"}var kca=class extends mo{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){U4h(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new w0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new E0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new j0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function S0u(e){return e}function M0u(e){return e==="__proto__"}function D0u(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function ela(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function XYa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(XYa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function B0u(e){if(Array.isArray(e))return e.map(ela);if(typeof e=="symbol")return[e];e=XYa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function ZYa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(M0u(t))return r;let i=e[t];return i===void 0?D0u(t)?ZYa(e,B0u(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=ela(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return TEB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),M0u(t))return r;let i=e[t];return i===void 0?r:i}}}function TEB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||M0u(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function L4h(e){return function(t){return ZYa(t,e)}}function V4h(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function I0u(e){return e==null||typeof e!="object"&&typeof e!="function"}function trl(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function irl(e,t,r){return typeof r!="function"?irl(e,t,()=>{}):rrl(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:rrl(n,a,i,s)},new Map)}function rrl(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return REB(e,t,r,i);case"function":return Object.keys(t).length>0?rrl(e,{...t},r,i):trl(e,t);default:return V4h(e)?typeof t=="string"?t==="":!0:trl(e,t)}}function REB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return W4h(e,t,r,i);if(t instanceof Map)return zEB(e,t,r,i);if(t instanceof Set)return NEB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!I0u(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function zEB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function W4h(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function NEB(e,t,r,i){return t.size===0?!0:e instanceof Set?W4h([...e],[...t],r,i):!1}function C0u(e,t){return irl(e,t,()=>{})}function G4h(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function q0u(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var x4h="[object RegExp]",T0u="[object String]",R0u="[object Number]",z0u="[object Boolean]",N0u="[object Arguments]",H4h="[object Symbol]",K4h="[object Date]",J4h="[object Map]",$4h="[object Set]",Y4h="[object Array]";var X4h="[object ArrayBuffer]",Z4h="[object Object]";var k4h="[object DataView]",eLh="[object Uint8Array]",tLh="[object Uint8ClampedArray]",rLh="[object Uint16Array]",iLh="[object Uint32Array]";var nLh="[object Int8Array]",aLh="[object Int16Array]",oLh="[object Int32Array]";var uLh="[object Float32Array]",sLh="[object Float64Array]";function cLh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lLh(e,t){return gYi(e,void 0,e,new Map,t)}function gYi(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(I0u(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=gYi(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,gYi(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(gYi(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(cLh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=gYi(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,eWt(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),eWt(o,e,r,i,n),o}if(typeof e=="object"&&FEB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),eWt(o,e,r,i,n),o}return e}function eWt(e,t,r=e,i,n){let a=[...Object.keys(t),...G4h(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=gYi(t[c],c,r,i,n))}}function FEB(e){switch(q0u(e)){case N0u:case Y4h:case X4h:case k4h:case z0u:case K4h:case uLh:case sLh:case nLh:case aLh:case oLh:case J4h:case R0u:case Z4h:case x4h:case $4h:case T0u:case H4h:case eLh:case tLh:case rLh:case iLh:return!0;default:return!1}}function fLh(e){return gYi(e,void 0,e,new Map,void 0)}function dLh(e){return e=fLh(e),t=>C0u(t,e)}function pLh(e,t){return lLh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case R0u:case T0u:case z0u:{let c=new e.constructor(e?.valueOf());return eWt(c,e),c}case N0u:{let c={};return eWt(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function _Lh(e){return pLh(e)}var QEB=/^(?:0|[1-9]\d*)$/;function hLh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return QEB.test(e)}}function yLh(e){return e!==null&&typeof e=="object"&&q0u(e)==="[object Arguments]"}function bLh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&D0u(t)&&e?.[t]==null?r=B0u(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||yLh(i))&&hLh(a)&&a<i.length))return!1;i=i[a]}return!0}function vLh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=ela(e);break}}return t=_Lh(t),function(r){let i=ZYa(r,e);return i===void 0?bLh(r,e):t===void 0?i===void 0:C0u(i,t)}}function gLh(e){if(e==null)return S0u;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?vLh(e[0],e[1]):dLh(e);case"string":case"symbol":case"number":return L4h(e)}}function OLh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function F0u(e,t=S0u){return e==null?{}:OLh(e,gLh(t))}function mLh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var UEB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function ALh(e){return Array.from(e.match(UEB)??[])}function PLh(e){let t=ALh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>mLh(n)).join("")}`}function jLh(e){return typeof e!="string"&&(e=XYa(e)),e.replace(/['\u2019]/g,"")}function tWt(e){return PLh(jLh(e))}function ij(e){if(e!=null)return Array.isArray(e)?e:[e]}function Q0u({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${LEB(o)}${VEB(e)}.${WEB(i,n,a,c)}`}function LEB(e){return e?"webhook_":"endpoint_"}function VEB(e){return e!=null?ij(e)?.map(t=>tWt(t)).join("/"):""}function WEB(e,t,r,i){return e||t||tWt(r??"")||tWt(i??"")}function wLh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var U0u=class extends mo{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[E4h],this.accessTokenLocator!=null&&(wLh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var L0u=class extends mo{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new kca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new U0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Q0u({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uc.EndpointId(r),accessTokenLocator:uc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var tla=class extends mo{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new g0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new m0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new O0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new A0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new P0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{z4h(this.input)?(this.authScheme="header",this.headerAuthNode=new kca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new L0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new ELh.UnreachableCaseError(this.authScheme);return}}};var rla=class extends mo{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=v0u(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new tla({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Ho))}};var V0u=class extends mo{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[m4h],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function SLh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function MLh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function ila(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>ij(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!SLh(n))&&(o=MLh(o,o.type==="enum"?o.default:void 0)),{key:uc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Ho)).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function W0u(e,t){return tg(e)?IL(e,t,void 0):e}function OYi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function DLh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function BLh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var ILh=ue(bM());var nrl=["decimal","decimal128","double-int","double","float","sf-decimal"],arl=["int16","int32","int64","int8","sf-integer","uint8"],orl=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],url=["beta","pre-release","in-development","generally-available","deprecated"];function CC(e,t){return tg(e)?IL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ESe=class extends mo{availability;constructor(t){super(t),this.safeParse()}parse(){if(CC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[A4h];r!=null&&(url.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${url.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uc.Availability.Beta;case"in-development":return uc.Availability.InDevelopment;case"generally-available":return uc.Availability.GenerallyAvailable;case"deprecated":return uc.Availability.Deprecated;case void 0:return;default:new ILh.UnreachableCaseError(this.availability);return}}};var x0u=ue(bM());function CLh(e){return typeof e=="object"&&e!=null&&"language"in e}function qLh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function TLh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function RLh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function G0u(e){return typeof e=="object"&&e!=null&&"event"in e}function srl(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(G0u)}function mYi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zLh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var H0u=class extends mo{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[R4h]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return mYi(o)?[n,{type:"filenameWithData",filename:o.filename,data:uc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>mYi(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:uc.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new x0u.UnreachableCaseError(a.multipartType);return}}).filter(Ho))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=zLh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new x0u.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{TLh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{srl(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!srl(r.response)&&RLh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new x0u.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{CLh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):qLh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[uc.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var kYa=class extends mo{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[h0u]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uc.api.v1.SubpackageId(tWt(r)))}};var K0u=class extends mo{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[j4h]}convert(){return this.sdkMethodName}};var J0u=class extends mo{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[w4h]}convert(){return this.isWebhook}};var $0u=class extends mo{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[F4h]??[],...this.input[Q4h]??[]],this.codeSamples.forEach(t=>{[...Object.values(uc.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var oOn=ue(bM());function crl(e,t){return tg(e)?IL(e,t,void 0):e}function NLh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var TF="",EXt=class extends mo{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(mYi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>mYi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new oOn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=crl(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=crl(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(G0u)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return mYi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>mYi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uc.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new oOn.UnreachableCaseError(i.multipartType);return}}).filter(Ho))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new oOn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new oOn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Ho));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Ho));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:NLh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?wXt(this.name):this.summary!=null?wXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function FLh(e,t){return tg(e)?IL(e,t,void 0):e}var XLh=ue(bM());var QLh="#/components/schemas/";function nla(e){if(e.$ref.startsWith(QLh))return e.$ref.replace(QLh,"")}function p4i(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function AYi(e){return typeof e.type=="string"&&e.type==="array"}function ULh(e){return e.type==="boolean"}function LLh(e){return e.type==="integer"}function PYi(e){return!Array.isArray(e.type)&&!AYi(e)}function VLh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||PYi(t)||AYi(t))}function WLh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function GLh(e){return e.type==="null"}function xLh(e){return e.type==="number"}function lrl(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function HLh(e){return e.type==="string"}var Y0u=class extends CY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new hw({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return ij(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var X0u=class extends IC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Z0u=class extends CY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Ho)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>ij(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Ho).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(p4i).filter(Ho):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function k0u(e){return e!=null&&e.length>0?e:[void 0]}var ala=class extends CY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new hw({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(tg(t))return nla(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new hw({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Ho))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return ila(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:ij(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Ho)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>k0u(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=CC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new hw({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var ewu=class extends CY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>CC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>CC(t,this.context.document)?.type!=="null"?new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Ho);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=CC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new hw({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Ho);return this.isNullable&&n!=null?n.map(p4i).filter(Ho):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>ij(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??wXt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Ho)).filter(Ho)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>ij(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?wXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?wXt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Ho)).filter(Ho)}:void 0,i=this.isNullable?p4i(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var twu=class extends IC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var jYi=class extends IC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(tg(r)){let n=CC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Ho),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var KLh=ue(bM());function GEB(e){return arl.includes(e)}var rwu=class extends IC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(GEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${arl.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new KLh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var iwu=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return p4i({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var JLh=ue(bM());function xEB(e){return nrl.includes(e)}var nwu=class extends IC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(xEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${nrl.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new JLh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var $Lh=ue(bM());function HEB(e){return orl.includes(e)}var awu=class extends IC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new $Lh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(HEB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${orl.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new jYi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var YLh=ue(bM());var owu=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,YLh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var uOn=class extends CY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=nla(this.input);let t=CC(this.input,this.context.document);t?.enum!=null&&PYi(t)&&(this.maybeEnumConverterNode=new jYi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=CC(this.input,this.context.document);if(r!=null)return new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var hw=class e extends CY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),PYi(this.input)&&WLh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),tg(this.input)){let t=nla(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new uOn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new X0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(VLh(this.input))this.typeShapeNode=new Z0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new ewu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(lrl(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ala({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYi(this.input)&&this.input.enum!=null)this.typeShapeNode=new jYi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":lrl(this.input)&&(this.typeShapeNode=new ala({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":AYi(this.input)&&(this.typeShapeNode=new Y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":ULh(this.input)&&(this.typeShapeNode=new twu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":LLh(this.input)&&(this.typeShapeNode=new rwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":xLh(this.input)&&(this.typeShapeNode=new nwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":HLh(this.input)&&(this.typeShapeNode=new awu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":GLh(this.input)&&(this.typeShapeNode=new iwu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new XLh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new ala({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new owu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!tg(this.input)&&(!AYi(this.input)&&this.input==null||AYi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=ij(t)?.map(i=>this.nullable?p4i(i):i).filter(Ho);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function wYi(e){if(e!=null)return ila(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Ho))}var SXt=class extends IC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;tg(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new ESe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=FLh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ZLh(e,t){return tg(e)?IL(e,t,void 0):e}var frl=ue(bM());function uwu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var kLh=ue(vnc(),1),ola=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=kLh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function KEB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var swu=class extends mo{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),KEB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(tg(r)?n=v0u(r.$ref,this.context.document):n=r,n!=null)return[t,new tla({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Ho)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uc.api.latest.AuthSchemeId(t),i]}).filter(Ho)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=ij(r.convert());return n==null?[t,void 0]:[uc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Ho(r))):void 0}}};var cwu=class extends hw{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=CC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${tg(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=CC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var lwu=class extends mo{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=CC(this.input.schema,this.context.document);this.availability=new ESe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=tg(this.input.schema)?new uOn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=ola.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new cwu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Ho))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[TF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[TF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:ij(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=tWt([this.method,this.path,this.contentType,"request"].join("_"));return uwu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new frl.UnreachableCaseError(n);return}}).filter(Ho)}convert(){if(this.schema instanceof uOn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=ij(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:uc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new frl.UnreachableCaseError(n.multipartType),[]}}).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var fwu=class extends mo{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ZLh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new lwu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>ij(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Ho)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>ij(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Ho)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var eVh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function tVh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var dwu=ue(bM());var rVh="application/json";var iVh="application/octet-stream";function nVh(e,t){return e===t||t===TF||e===TF}var eXa=class extends mo{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)nVh(c,a)&&(i.add(c),this.examples?.push(new EXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,OYi(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new EXt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,OYi(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new EXt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,OYi(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new EXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,OYi(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[TF];if(a!=null)for(let o of a)this.examples?.push(new EXt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,OYi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=ola.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=rVh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=iVh,this.contentSubtype=CC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new hw({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=F0u(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]=[{value:this.input.example}]);let i=CC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=F0u(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[TF]??=[],r[TF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==TF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Ho(d)&&c!==TF);Object.keys(r).every(c=>c===TF)||this.matchExamplesByIndex(a,o),!n.has(TF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return ij(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new dwu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return ij(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=tWt([this.method,this.path,this.statusCode,"response"].join("_"));return uwu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new dwu.UnreachableCaseError(i);return}}).filter(Ho)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new dwu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var tXa=class extends mo{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=tVh(this.input,this.context.document);if(r==null){this.context.errors.error({message:tg(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new SXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new eXa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new eXa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Ho)}};var pwu=class extends mo{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new tXa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new tXa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return k0u(wYi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(Ho))})))}).filter(Ho)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=ij(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??eVh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Ho)})).filter(Ho)})).filter(Ho)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var EYi=class extends mo{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new EXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,OYi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=vYi(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new J0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(tg(i)){let a=W0u(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new SXt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new $0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new fwu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new pwu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new rla({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new kYa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new kYa({input:{[h0u]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new K0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Q0u({namespace:ij(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Ho),this.xFernExamplesNode=new H0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Ho)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uc.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(Ho),n=BLh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:DLh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:wYi(this.queryParameters)?.flat(),headers:wYi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Ho)}}).filter(Ho);let a=this.servers?.map(u=>u.convert()).filter(Ho),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(Ho);return this.endpointIds.map((u,l)=>({id:uc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>uc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>uc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:wYi(this.pathParameters)?.flat(),queryParameters:wYi(this.queryParameters)?.flat(),requestHeaders:wYi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var ula=class extends mo{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=vYi(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new EYi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new EYi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new EYi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new EYi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new EYi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Ho)}};function _wu(e){return"payloads"in e}var hwu=class extends mo{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new ula({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:vYi(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Ho)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{_wu(a)?r[uc.WebhookId(a.id)]=a:t[uc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var ywu=class extends mo{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[P4h]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||W0u(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new SXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return ila(this.globalHeaders,this.requiredProperties)?.flat()}};function aVh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var bwu=class extends mo{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=aVh(a,this.context.document);if(o!=null)return new ula({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Ho)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{_wu(i)&&(t[uc.WebhookId(i.id)]=i)}),t),{})}};var vwu=class extends mo{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=vYi(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new rla({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new V0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new hwu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new bwu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new swu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new ywu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=zve(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=g4h({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:uc.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function drl(e,t){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let r=new W8t(e.absoluteFilePath),i=await bSe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i,loadAiExamples:!0}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new p0u,generatedTypes:{}},d=new vwu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=m$n(a,d.convert())}return a}var PKh=ue(hrl(),1),jKh=ue(oEu(),1),BSu=require("fs/promises"),wKh=ue(require("http"),1),EKh=ue(require("path"),1);var c6h=require("events"),fEu=ue(require("fs"),1),bOn=ue(require("path"),1);var x5h=ue(require("os"),1),H5h=300,qYi=20,jXa=1e7,K5h=x5h.default.platform();var h1B=K5h==="darwin",Ril=K5h==="win32",TYi=h1B||Ril,J5h=3e3,$5h=2e4,zil=1250;var IXt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(IXt||(IXt={}));var yOn;(function(e){e.CHANGE="change",e.RENAME="rename"})(yOn||(yOn={}));var wXa;(function(e){e.CHANGE="change",e.ERROR="error"})(wXa||(wXa={}));var rf;(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"})(rf||(rf={}));var Fx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Fx||(Fx={}));var y1B=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let O=Date.now(),A=O-d,j=O-s,M=A>=t||j>=a;return[O,M]},l=O=>{if(s=O,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{g(0)},_=()=>{c&&(p(),l(Date.now()))},h=O=>{if(s=O,i)return l(O)},y=O=>{if(n&&o)return l(O);o=void 0},b=()=>{c=void 0;let[O,A]=u();return A?y(O):v(O)},v=O=>{let A=O-d,j=O-s,M=t-A,w=a-j,D=Math.min(M,w);return g(D)},g=O=>{c&&clearTimeout(c),!(O<=0)&&(c=setTimeout(b,O))},m=(...O)=>{let[A,j]=u(),M=!!c;if(o=O,d=A,(j||!c)&&g(t),j)return M?l(A):h(A)};return m.cancel=p,m.flush=_,m},uEu=y1B;var Uil=ue(require("fs"),1),cEu=ue(require("path"),1);var dm=ue(require("fs"),1),CL=require("util");var h4i=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},CXt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var Nil=ue(require("process"),1),Y5h=Nil.default.getuid?!Nil.default.getuid():!1,X5h=1e4,zY=()=>{};var EXa={isChangeErrorOk:e=>{if(!EXa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Y5h&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!EXa.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(!EXa.isNodeError(e))throw e;if(!EXa.isChangeErrorOk(e))throw e}},qC=EXa;var Fil=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=X5h,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(i),i=()=>t(r);this.add(i)}),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()}}}}},Z5h=new Fil;var y4i=(e,t)=>function(i){return function n(...a){return Z5h.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},b4i=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var b1B={attempt:{chmod:h4i((0,CL.promisify)(dm.default.chmod),qC.onChangeError),chown:h4i((0,CL.promisify)(dm.default.chown),qC.onChangeError),close:h4i((0,CL.promisify)(dm.default.close),zY),fsync:h4i((0,CL.promisify)(dm.default.fsync),zY),mkdir:h4i((0,CL.promisify)(dm.default.mkdir),zY),realpath:h4i((0,CL.promisify)(dm.default.realpath),zY),stat:h4i((0,CL.promisify)(dm.default.stat),zY),unlink:h4i((0,CL.promisify)(dm.default.unlink),zY),chmodSync:CXt(dm.default.chmodSync,qC.onChangeError),chownSync:CXt(dm.default.chownSync,qC.onChangeError),closeSync:CXt(dm.default.closeSync,zY),existsSync:CXt(dm.default.existsSync,zY),fsyncSync:CXt(dm.default.fsync,zY),mkdirSync:CXt(dm.default.mkdirSync,zY),realpathSync:CXt(dm.default.realpathSync,zY),statSync:CXt(dm.default.statSync,zY),unlinkSync:CXt(dm.default.unlinkSync,zY)},retry:{close:y4i((0,CL.promisify)(dm.default.close),qC.isRetriableError),fsync:y4i((0,CL.promisify)(dm.default.fsync),qC.isRetriableError),open:y4i((0,CL.promisify)(dm.default.open),qC.isRetriableError),readFile:y4i((0,CL.promisify)(dm.default.readFile),qC.isRetriableError),rename:y4i((0,CL.promisify)(dm.default.rename),qC.isRetriableError),stat:y4i((0,CL.promisify)(dm.default.stat),qC.isRetriableError),write:y4i((0,CL.promisify)(dm.default.write),qC.isRetriableError),writeFile:y4i((0,CL.promisify)(dm.default.writeFile),qC.isRetriableError),closeSync:b4i(dm.default.closeSync,qC.isRetriableError),fsyncSync:b4i(dm.default.fsyncSync,qC.isRetriableError),openSync:b4i(dm.default.openSync,qC.isRetriableError),readFileSync:b4i(dm.default.readFileSync,qC.isRetriableError),renameSync:b4i(dm.default.renameSync,qC.isRetriableError),statSync:b4i(dm.default.statSync,qC.isRetriableError),writeSync:b4i(dm.default.writeSync,qC.isRetriableError),writeFileSync:b4i(dm.default.writeFileSync,qC.isRetriableError)}},k5h=b1B;var sEu=ue(require("fs"),1),SXa=ue(require("path"),1);var Qil=()=>{};var v1B=()=>{let e=Qil,t=Qil,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},e6h=v1B;var g1B=()=>{let{promise:e,resolve:t,isPending:r}=e6h(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},t6h=g1B;var r6h={then:e=>{e()}};var i6h=e=>Array.isArray(e)?e:[e],n6h=e=>typeof e=="function";var O1B=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=i6h(a).map(W=>n6h(W)?W:x=>W.test(x)),c=W=>o.some(x=>x(W)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,g={},m={},O=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:g,map:m},{promise:M,increment:w,decrement:D}=t6h(),B=0,R=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.directories.push(x),W.directoriesNames.add(Ee),u.push(x),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),O.add(x),!(se>=i)&&(B>=n||$(x,se+1)))},T=(W,x,Ee)=>{O.has(x)||B>=n||(B+=1,W.files.push(x),W.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),O.add(x))},q=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.symlinks.push(x),W.symlinksNames.add(Ee),b.push(x),v.add(Ee),g.propertyIsEnumerable(Ee)||(g[Ee]=[]),g[Ee].push(x),O.add(x),r&&(se>=i||B>=n||de(x,se+1)))},z=(W,x,Ee,se,Oe)=>{d.aborted||c(x)||(se.isDirectory()?R(W,x,Ee,Oe):se.isFile()?T(W,x,Ee):se.isSymbolicLink()&&q(W,x,Ee,Oe))},N=(W,x,Ee,se)=>{if(d.aborted)return;let Oe=x===SXa.default.sep?"":SXa.default.sep,Fe=Ee.name,ae=`${x}${Oe}${Fe}`;c(ae)||(Ee.isDirectory()?R(W,ae,Fe,se):Ee.isFile()?T(W,ae,Fe):Ee.isSymbolicLink()&&q(W,ae,Fe,se))},H=(W,x,Ee,se)=>{for(let Oe=0,Fe=Ee.length;Oe<Fe;Oe++)N(W,x,Ee[Oe],se)},$=(W,x)=>{d.aborted||x>i||B>=n||(w(),sEu.default.readdir(W,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||r6h).then(()=>{let Fe=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Fe,W,se,x),D()})}))},de=(W,x)=>{w(),sEu.default.realpath(W,(Ee,se)=>{if(Ee||d.aborted)return D();sEu.default.stat(se,(Oe,Fe)=>{if(Oe||d.aborted)return D();let ae=SXa.default.basename(se),re=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Fe,x),D()})})};return(async(W,x=1)=>(W=SXa.default.normalize(W),O.add(W),$(W,x),await M,d.aborted?A:j))(e)},a6h=O1B;var qXt={lang:{debounce:uEu,attempt:e=>{try{return e()}catch(t){return qXt.lang.castError(t)}},castArray:e=>qXt.lang.isArray(e)?e:[e],castError:e=>qXt.lang.isError(e)?e:qXt.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(qXt.lang.isNaN(e))return qXt.lang.isNaN(t);if(qXt.lang.isPrimitive(e)||qXt.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(cEu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Uil.default.realpathSync.native(e):Uil.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===cEu.default.sep&&t.length-e.length>cEu.default.sep.length,poll:(e,t=$5h)=>k5h.retry.stat(t)(e,{bigint:!0}).catch(qXt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await a6h(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Gp=qXt;var lEu=ue(require("path"),1);var Lil=class{constructor(t,r,i){this.base=i,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||Gp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=H5h){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Gp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===rf.CHANGE&&c===rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??qYi:Math.min(1,this.options.depth??qYi),o=this.options.limit??jXa,[c,d]=await Gp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Gp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!TYi&&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(rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(lEu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(lEu.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(rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===rf.ADD?this.onTargetAdd(i):r===rf.ADD_DIR?this.onTargetAddDir(i):r===rf.CHANGE?this.onTargetChange(i):r===rf.UNLINK?this.onTargetUnlink(i):r===rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=yOn.CHANGE,r){if(this.watcher.isClosed())return;let i=lEu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){Ril&&t.code==="EPERM"?this.onWatcherChange(yOn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(wXa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(wXa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(yOn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&TYi&&this.options.native!==!1?this.options.depth??qYi:Math.min(1,this.options.depth??qYi),i=this.options.limit??jXa,[n,a]=await Gp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(yOn.CHANGE,c,t)}))}}},o6h=Lil;var Qx={interval:100,intervalId:void 0,fns:new Map,init:()=>{Qx.intervalId||(Qx.intervalId=setInterval(Qx.resolve,Qx.interval))},reset:()=>{Qx.intervalId&&(clearInterval(Qx.intervalId),delete Qx.intervalId)},add:(e,t)=>{Qx.fns.set(e,Date.now()+t),Qx.init()},remove:e=>{Qx.fns.delete(e)},resolve:()=>{if(!Qx.fns.size)return Qx.reset();let e=Date.now();for(let[t,r]of Qx.fns)r>=e||(Qx.remove(t),t())}},MXa=Qx;var DXa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=zil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Gp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),MXa.remove(s)},s=()=>{d(),c()};MXa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=zil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),MXa.remove(s)},s=()=>{d(),c()};MXa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,rf.ADD,IXt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,rf.ADD_DIR,IXt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,rf.UNLINK,IXt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,rf.UNLINK_DIR,IXt.DIR);return this.getLockUnlink({ino:i,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}}};DXa.DIR_EVENTS={add:rf.ADD_DIR,rename:rf.RENAME_DIR,unlink:rf.UNLINK_DIR};DXa.FILE_EVENTS={add:rf.ADD,change:rf.CHANGE,rename:rf.RENAME,unlink:rf.UNLINK};var u6h=DXa;var Vil=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Gp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Gp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Gp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Gp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Gp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Gp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Wil=Vil;var Gil=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}},s6h=Gil;var xil=class{constructor(){this.inos={},this.paths=new Wil,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Gp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new s6h(i)}reset(){this.inos={},this.paths=new Wil,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,rf.ADD,n),[rf.ADD];if(n.isDirectory())return this.updateIno(t,rf.ADD_DIR,n),[rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,rf.UNLINK,i),[rf.UNLINK];if(i.isDirectory())return this.updateIno(t,rf.UNLINK_DIR,i),[rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,rf.CHANGE,n),[rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,rf.UNLINK,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK,rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD,n),[rf.UNLINK_DIR,rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK_DIR,rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?IXt.FILE:IXt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},Hil=xil;var Kil=class e extends c6h.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Fx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Fx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Fx.READY,n)),this._locker=new u6h(this),this._roots=new Set,this._poller=new Hil,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Gp.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(Fx.CLOSE))}error(t){if(this.isClosed())return!1;let r=Gp.lang.castError(t);return this.emit(Fx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Fx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Fx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Gp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,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,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new o6h(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Gp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=bOn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??qYi))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&TYi&&u.options.native!==!1)))return!0;if(!TYi)break;let s=bOn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Gp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||TYi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:fEu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=bOn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||TYi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??qYi,c=r.limit??jXa,[d]=await Gp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Gp.fs.getDepth(t);for(let l of d){let p=Gp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(Fx.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(Fx.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=bOn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new Hil,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Gp.lang.noop;if(this.pollerExists(t,r))return Gp.lang.noop;let n={...r,interval:r.pollingInterval??J5h},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(Fx.CLOSE,c),fEu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Fx.CLOSE,c),fEu.default.unwatchFile(t,i)};return Gp.lang.attempt(o),()=>Gp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Gp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Gp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=bOn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Gp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=bOn.default.dirname(t);return(await Gp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Gp.lang.noop){if(Gp.lang.isFunction(t))return this.watch([],{},t);if(Gp.lang.isUndefined(t))return this.watch([],r,i);if(Gp.lang.isFunction(r))return this.watch(t,{},r);if(Gp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Gp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Gp.lang.noop&&this.on(Fx.ALL,i),r.readdirMap=void 0,this.ready())}},dEu=Kil;hru();var Pla=require("fs/promises"),l6h=require("os"),f6h=ue(require("path"),1),m1B=".fern",A1B="logs";function P1B(){return"cli@3.49.2"}var BXa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Tt(Sr.of((0,l6h.homedir)()),He.of(m1B)),r=Tt(t,He.of(A1B));await Ai(r)||await(0,Pla.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Tt(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${f6h.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
1950
1950
|
`);await(0,Pla.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
1951
1951
|
`;try{await(0,Pla.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 i={timestamp:t.timestamp,source:P1B(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}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 i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}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 Oal=ue(rnl(),1),iKh=ue(iSu(),1),NY=require("fs/promises"),nKh=require("os"),aKh=ue(j4(),1),oKh=ue(tKh(),1),OSu=process.platform==="win32",gal=Rt.cyan("[docs]:"),WNB="etag",GNB=23,rKh=e=>e.padEnd(GNB," "),xNB="preview",HNB="app-preview",KNB="bundle",JNB=".next",$NB="standalone",YNB=".fern",XNB="packages/fern-docs/bundle/.next/server/instrumentation.js",ZNB=".npmrc",kNB=".pnpmfile.cjs",eFB="pnpm-workspace.yaml",tFB='Cannot find matching keyid: {"signatures":';function rFB(){return Tt(Sr.of((0,nKh.homedir)()),He.of(YNB))}function Ula({app:e=!1}){return Tt(rFB(),He.of(e?HNB:xNB))}function WYi({app:e=!1}){return Tt(Ula({app:e}),He.of(e?JNB:KNB))}function eZa({app:e=!1}){return Tt(WYi({app:e}),He.of($NB))}function iFB({app:e=!1}){return Tt(eZa({app:e}),He.of(XNB))}function nFB({app:e=!1}){return Tt(eZa({app:e}),He.of(eFB))}function aFB({app:e=!1}){return Tt(eZa({app:e}),He.of(kNB))}function oFB({app:e=!1}){return Tt(eZa({app:e}),He.of(ZNB))}function jOn(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function uFB({app:e=!1}){return Tt(Ula({app:e}),He.of(WNB))}var sFB=`module.exports = {
|
|
1952
1952
|
hooks: {
|