fern-api 5.110.0 → 5.110.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -937,7 +937,7 @@ ${t.join(`
937
937
  `+t)+`
938
938
  `}var eCu=h(()=>{"use strict";OE();cee();RVr();Wh();b_();dA();o3();uLe();pve();oRo()});var tCu=h(()=>{"use strict";qxu();Gxu();Yxu();eCu()});var AUr=h(()=>{"use strict";Uxu();_xu();tCu()});function aCu(e){let t=[],r=new Map,n=new Map,i=new Map,o=[],s={types:new Set,seen:!1};for(let u of e)for(let l of rGd(u).definitions){if(l.kind===wt.DIRECTIVE_DEFINITION){let p=l.name.value;if(sCu.has(p))continue;let d=n.get(p);d==null?n.set(p,{definition:l,filePath:u.filePath}):Vp(d.definition)!==Vp(l)&&t.push({typeName:`@${p}`,memberName:"<declaration>",kept:d.filePath,dropped:u.filePath});continue}if(l.kind===wt.SCHEMA_DEFINITION||l.kind===wt.SCHEMA_EXTENSION){for(let p of l.operationTypes??[]){let d=i.get(p.operation);d==null?i.set(p.operation,{operationType:p,filePath:u.filePath}):d.operationType.type.name.value!==p.type.name.value&&t.push({typeName:"schema",memberName:p.operation,kept:d.filePath,dropped:u.filePath})}continue}if(iGd(l)){nCu({incoming:oGd(l),isExtension:!0,filePath:u.filePath,types:r,conflicts:t,inaccessible:s});continue}if(nGd(l)){nCu({incoming:l,isExtension:!1,filePath:u.filePath,types:r,conflicts:t,inaccessible:s});continue}l.kind===wt.OPERATION_DEFINITION||l.kind===wt.FRAGMENT_DEFINITION||o.push(l)}if(s.seen){let u=tGd(i,r);if(cGd(r,s.types),uGd(r),u!=null&&!r.has(u))throw new Error(`Every field on the GraphQL query root "${u}" returns a type marked @inaccessible (${[...s.types].sort().join(", ")}), so the merged schema has no reachable operations. Remove @inaccessible from at least one reachable type, or exclude these files from the docs.`)}let a=[...[...n.values()].map(u=>u.definition),...o,...[...r.values()].map(u=>u.definition)],c=[...i.values()].map(u=>u.operationType).filter(u=>r.has(u.type.name.value));return c.length>0&&a.push({kind:wt.SCHEMA_DEFINITION,operationTypes:c}),{document:{kind:wt.DOCUMENT,definitions:a},conflicts:t}}function tGd(e,t){let r=e.get("query")?.operationType.type.name.value;return r!=null?t.has(r)?r:void 0:t.has("Query")?"Query":void 0}function rGd(e){try{return QVr(e.sdl)}catch(t){throw new Error(`${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}}function nGd(e){return e.kind===wt.SCALAR_TYPE_DEFINITION||e.kind===wt.OBJECT_TYPE_DEFINITION||e.kind===wt.INTERFACE_TYPE_DEFINITION||e.kind===wt.UNION_TYPE_DEFINITION||e.kind===wt.ENUM_TYPE_DEFINITION||e.kind===wt.INPUT_OBJECT_TYPE_DEFINITION}function iGd(e){return e.kind===wt.SCALAR_TYPE_EXTENSION||e.kind===wt.OBJECT_TYPE_EXTENSION||e.kind===wt.INTERFACE_TYPE_EXTENSION||e.kind===wt.UNION_TYPE_EXTENSION||e.kind===wt.ENUM_TYPE_EXTENSION||e.kind===wt.INPUT_OBJECT_TYPE_EXTENSION}function oGd(e){switch(e.kind){case wt.SCALAR_TYPE_EXTENSION:return{...e,kind:wt.SCALAR_TYPE_DEFINITION,description:void 0};case wt.OBJECT_TYPE_EXTENSION:return{...e,kind:wt.OBJECT_TYPE_DEFINITION,description:void 0};case wt.INTERFACE_TYPE_EXTENSION:return{...e,kind:wt.INTERFACE_TYPE_DEFINITION,description:void 0};case wt.UNION_TYPE_EXTENSION:return{...e,kind:wt.UNION_TYPE_DEFINITION,description:void 0};case wt.ENUM_TYPE_EXTENSION:return{...e,kind:wt.ENUM_TYPE_DEFINITION,description:void 0};case wt.INPUT_OBJECT_TYPE_EXTENSION:return{...e,kind:wt.INPUT_OBJECT_TYPE_DEFINITION,description:void 0}}}function W4t(e){if(e!=null)return e.filter(t=>!sCu.has(t.name.value))}function cCu(e){return e.directives?.some(t=>t.name.value===eGd)??!1}function sGd(e,t){return e?.filter(uCu(t)).map(r=>({...r,directives:W4t(r.directives)}))}function uCu(e){return t=>cCu(t)?(e.seen=!0,!1):!0}function aGd(e,t){let r=W4t(e.directives);cCu(e)&&(t.seen=!0,t.types.add(e.name.value));let n=uCu(t);switch(e.kind){case wt.OBJECT_TYPE_DEFINITION:case wt.INTERFACE_TYPE_DEFINITION:return{...e,directives:r,fields:e.fields?.filter(n).map(i=>({...i,directives:W4t(i.directives),arguments:sGd(i.arguments,t)}))};case wt.INPUT_OBJECT_TYPE_DEFINITION:return{...e,directives:r,fields:e.fields?.filter(n).map(i=>({...i,directives:W4t(i.directives)}))};case wt.ENUM_TYPE_DEFINITION:return{...e,directives:r,values:e.values?.filter(n).map(i=>({...i,directives:W4t(i.directives)}))};case wt.SCALAR_TYPE_DEFINITION:case wt.UNION_TYPE_DEFINITION:return{...e,directives:r}}}function yUr(e){switch(e.kind){case wt.NAMED_TYPE:return e.name.value;case wt.LIST_TYPE:case wt.NON_NULL_TYPE:return yUr(e.type)}}function cGd(e,t){let r=new Set;for(let i of t)e.delete(i)&&r.add(i);let n=!0;for(;n;){n=!1;for(let[i,o]of e){let s=lGd(o.definition,r);if(s==null){e.delete(i),r.add(i),n=!0;continue}s!==o.definition&&(o.definition=s,n=!0)}}}function rCu(e){return e.kind!==wt.OBJECT_TYPE_DEFINITION&&e.kind!==wt.INTERFACE_TYPE_DEFINITION?new Set:new Set((e.fields??[]).map(t=>t.name.value))}function uGd(e){for(let t of e.values()){let r=t.definition;if(r.kind!==wt.OBJECT_TYPE_DEFINITION&&r.kind!==wt.INTERFACE_TYPE_DEFINITION)continue;let n=r.interfaces??[],i=rCu(r),o=n.filter(s=>{let a=e.get(s.name.value);return a==null?!1:[...rCu(a.definition)].every(c=>i.has(c))});o.length!==n.length&&(t.definition={...r,interfaces:o})}}function lGd(e,t){switch(e.kind){case wt.OBJECT_TYPE_DEFINITION:case wt.INTERFACE_TYPE_DEFINITION:{let r=(e.fields??[]).filter(i=>!t.has(yUr(i.type))&&!(i.arguments??[]).some(o=>t.has(yUr(o.type))));if(r.length===0)return null;let n=(e.interfaces??[]).filter(i=>!t.has(i.name.value));return r.length===e.fields?.length&&n.length===(e.interfaces??[]).length?e:{...e,fields:r,interfaces:n}}case wt.INPUT_OBJECT_TYPE_DEFINITION:{let r=(e.fields??[]).filter(n=>!t.has(yUr(n.type)));return r.length===0?null:r.length===e.fields?.length?e:{...e,fields:r}}case wt.UNION_TYPE_DEFINITION:{let r=(e.types??[]).filter(n=>!t.has(n.name.value));return r.length===0?null:r.length===e.types?.length?e:{...e,types:r}}case wt.ENUM_TYPE_DEFINITION:return e.values?.length===0?null:e;case wt.SCALAR_TYPE_DEFINITION:return e}}function nCu({incoming:e,isExtension:t,filePath:r,types:n,conflicts:i,inaccessible:o}){let s=e.name.value,a=aGd(e,o),c=n.get(s);if(c==null){n.set(s,iCu(a,r,t));return}if(c.definition.kind!==a.kind){i.push({typeName:s,memberName:"<declaration>",kept:c.filePath,dropped:r});return}if(c.fromExtension&&!t){let u=iCu(a,r,!1);u.definition=oCu(u,c.definition,c.filePath,i),n.set(s,u);return}c.definition=oCu(c,a,r,i)}function iCu(e,t,r){let n=new Map;for(let i of pGd(e))n.set(i.name.value,{filePath:t,signature:lCu(i)});return{definition:e,filePath:t,members:n,fromExtension:r}}function pGd(e){switch(e.kind){case wt.OBJECT_TYPE_DEFINITION:case wt.INTERFACE_TYPE_DEFINITION:case wt.INPUT_OBJECT_TYPE_DEFINITION:return e.fields??[];case wt.ENUM_TYPE_DEFINITION:return e.values??[];case wt.UNION_TYPE_DEFINITION:return e.types??[];case wt.SCALAR_TYPE_DEFINITION:return[]}}function lCu(e){if(e.kind===wt.FIELD_DEFINITION){let t=(e.arguments??[]).map(r=>`${r.name.value}:${Vp(r.type)}`);return`${Vp(e.type)}(${t.join(",")})`}return e.kind===wt.INPUT_VALUE_DEFINITION?Vp(e.type):e.name.value}function oCu(e,t,r,n){let i=e.definition,o=i.description??t.description,s=i.name.value,a=(c,u)=>{let l=[...c??[]];for(let p of u??[]){let d=p.name.value,f=lCu(p),m=e.members.get(d);if(m!=null){m.signature!==f&&n.push({typeName:s,memberName:d,kept:m.filePath,dropped:r});continue}e.members.set(d,{filePath:r,signature:f}),l.push(p)}return l};return i.kind===wt.OBJECT_TYPE_DEFINITION&&t.kind===wt.OBJECT_TYPE_DEFINITION?{...i,description:o,interfaces:QRo(i.interfaces,t.interfaces),fields:a(i.fields,t.fields)}:i.kind===wt.INTERFACE_TYPE_DEFINITION&&t.kind===wt.INTERFACE_TYPE_DEFINITION?{...i,description:o,interfaces:QRo(i.interfaces,t.interfaces),fields:a(i.fields,t.fields)}:i.kind===wt.INPUT_OBJECT_TYPE_DEFINITION&&t.kind===wt.INPUT_OBJECT_TYPE_DEFINITION?{...i,description:o,fields:a(i.fields,t.fields)}:i.kind===wt.ENUM_TYPE_DEFINITION&&t.kind===wt.ENUM_TYPE_DEFINITION?{...i,description:o,values:a(i.values,t.values)}:i.kind===wt.UNION_TYPE_DEFINITION&&t.kind===wt.UNION_TYPE_DEFINITION?{...i,description:o,types:QRo(i.types,t.types)}:{...i,description:o}}function QRo(e,t){let r=new Set((e??[]).map(i=>i.name.value)),n=[...e??[]];for(let i of t??[])r.has(i.name.value)||(r.add(i.name.value),n.push(i));return n}var eGd,sCu,pCu=h(()=>{"use strict";AUr();eGd="inaccessible",sCu=new Set(["link","key","external","requires","provides","shareable","inaccessible","override","extends","composeDirective","interfaceObject","tag","authenticated","requiresScopes","policy","context","fromContext","cost","listSize"])});var fCu,nnt,dCu=h(()=>{"use strict";Tt();Jm();fCu=require("fs/promises");AUr();pCu();nnt=class{schema;context;filePaths;namespace;processingTypes=new Set;types={};typeCategories={};namespaceTypeNames=new Set;examplesByOperation=new Map;constructor({context:t,filePath:r,namespace:n,examples:i}){if(this.context=t,this.filePaths=Array.isArray(r)?r:[r],this.namespace=n,i!=null)for(let o of i){let s=o.examples.map(c=>({name:c.name??void 0,description:c.description??void 0,query:c.query,variables:c.variables??void 0,response:c.response??void 0})),a=o.operationType!=null?`${o.operationType.toLowerCase()}:${o.operation}`:o.operation;if(this.examplesByOperation.has(a)){this.context.logger.warn(`Multiple GraphQL examples provided for "${a}". Keeping the first and ignoring the rest.`);continue}this.examplesByOperation.set(a,s)}}availabilityOf(t){return t.deprecationReason!=null?"Deprecated":void 0}describeWithDeprecation(t){let r=t.description??void 0;if(t.deprecationReason==null||t.deprecationReason===sLe)return r;let n=`**Deprecated:** ${t.deprecationReason}`;return r!=null?`${r}
939
939
 
940
- ${n}`:n}isBuiltInScalar(t){return["String","Int","Float","Boolean","ID"].includes(t)}getNamespacedTypeId(t){let r=this.namespace?`${this.namespace}_${t}`:t;return un.TypeId(r)}getNamespacedOperationId(t){let r=this.namespace?`${this.namespace}_${t}`:t;return un.GraphQlOperationId(r)}getNamespacedTypeName(t){return this.namespace?`${this.namespace}_${t}`:t}isActualSubscriptionRootType(t){return!(t.getInterfaces().length>0)}isNamespaceType(t){let r=Object.values(t.getFields());return r.length===0?!1:r.every(n=>n.args.length>0)}buildSchema(t){try{let r=q4t(t);for(let n of sUr(r))this.context.logger.warn(`Invalid GraphQL schema: ${n.message}`);return r}catch(r){let n;try{n=q4t(t,{assumeValidSDL:!0})}catch{throw r}return this.context.logger.warn(`Invalid GraphQL schema: ${r instanceof Error?r.message:String(r)} Continuing without SDL validation.`),n}}async convert(){let t=await Promise.all(this.filePaths.map(async u=>({filePath:u,sdl:await(0,fCu.readFile)(u,"utf-8")}))),{document:r,conflicts:n}=aCu(t);for(let u of n){let l=`${u.typeName}.${u.memberName}`;this.context.logger.warn(u.kept===u.dropped?`GraphQL schema conflict: ${l} is declared more than once in ${u.kept} with differing shapes. Keeping the first declaration.`:`GraphQL schema conflict: ${l} is defined in both ${u.kept} and ${u.dropped}. Keeping the definition from ${u.kept}.`)}this.schema=this.buildSchema(r),this.collectTypeDefinitions();let i=[],o=this.schema.getQueryType();o&&this.convertOperations(o,"QUERY",i);let s=this.schema.getMutationType();s&&this.convertOperations(s,"MUTATION",i);let a=this.schema.getSubscriptionType();a&&this.isActualSubscriptionRootType(a)&&this.convertOperations(a,"SUBSCRIPTION",i);let c=this.resolveOperationIds(i);for(let u of this.namespaceTypeNames)delete this.typeCategories[this.getNamespacedTypeId(u)];return{graphqlOperations:c,types:this.types,typeCategories:this.typeCategories}}resolveOperationIds(t){let r=new Map;for(let i of t)r.set(i.flatId,(r.get(i.flatId)??0)+1);let n={};for(let i of t){let s=(r.get(i.flatId)??0)>1?i.namespacedId:i.flatId,a=this.getNamespacedOperationId(s);n[a]={...i.operation,id:a}}return n}collectTypeDefinitions(){if(!this.schema)return;let t=this.schema.getTypeMap();for(let[r,n]of Object.entries(t)){if(r.startsWith("__")||n===this.schema.getQueryType()||n===this.schema.getMutationType()||n===this.schema.getSubscriptionType()&&n instanceof BE&&this.isActualSubscriptionRootType(n)||n instanceof NI&&this.isBuiltInScalar(r))continue;let i=this.getNamespacedTypeId(r);if(this.typeCategories[i]=this.typeCategoryOf(n),n instanceof V1){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertEnumTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof qQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertInterfaceTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof BE){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertObjectTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof WQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertInputObjectTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof GQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertUnionTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof NI){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertScalarTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}}}typeCategoryOf(t){if(t instanceof BE)return"object";if(t instanceof WQ)return"input";if(t instanceof V1)return"enum";if(t instanceof qQ)return"interface";if(t instanceof GQ)return"union";if(t instanceof NI)return"scalar";be(t)}buildOperationId(t,r){return`${t.toLowerCase()}_${r.join(".")}`}convertOperations(t,r,n){let i=t.getFields();for(let[o,s]of Object.entries(i)){let a=this.unwrapNonNull(s.type);if(a instanceof BE&&s.args.length===0&&this.isNamespaceType(a)){if(r==="QUERY"){let c=this.buildOperationId(r,[o]);n.push({flatId:c,namespacedId:c,operation:this.convertField(s,o,r)})}this.namespaceTypeNames.add(a.name),this.convertNamespaceOperations(a,r,n,[o])}else{let c=this.buildOperationId(r,[o]);n.push({flatId:c,namespacedId:c,operation:this.convertField(s,o,r)})}}}convertNamespaceOperations(t,r,n,i){let o=t.getFields();for(let[s,a]of Object.entries(o)){let c=this.buildOperationId(r,[s]),u=this.buildOperationId(r,[...i,s]);n.push({flatId:c,namespacedId:u,operation:this.convertField(a,s,r,i)})}}unwrapNonNull(t){return t instanceof Rc?t.ofType:t}convertField(t,r,n,i){let o=t.args.map(a=>this.convertArgument(a)),s=this.examplesByOperation.get(`${n.toLowerCase()}:${r}`)??this.examplesByOperation.get(r);return{id:un.GraphQlOperationId(""),operationType:n,name:r,displayName:void 0,description:this.describeWithDeprecation(t),availability:this.availabilityOf(t),fieldPath:i!=null&&i.length>0?i:void 0,arguments:o.length>0?o:void 0,returnType:this.convertOutputType(t.type),examples:s!=null&&s.length>0?s:void 0,snippets:void 0}}convertArgument(t){return{name:t.name,description:this.describeWithDeprecation(t),availability:this.availabilityOf(t),type:this.convertInputType(t.type),defaultValue:t.defaultValue}}convertOutputType(t){return t instanceof Rc?this.convertNonNullOutputType(t.ofType):{type:"optional",itemType:this.convertNonNullOutputType(t),defaultValue:void 0}}convertNonNullOutputType(t){return t instanceof vy?{type:"list",itemType:this.convertOutputType(t.ofType),minItems:void 0,maxItems:void 0}:t instanceof NI?this.convertScalarType(t):t instanceof V1?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof BE||t instanceof qQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof GQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:{type:"unknown"}}convertInputType(t){return t instanceof Rc?this.convertNonNullInputType(t.ofType):{type:"optional",itemType:this.convertNonNullInputType(t),defaultValue:void 0}}convertNonNullInputType(t){return t instanceof vy?{type:"list",itemType:this.convertInputType(t.ofType),minItems:void 0,maxItems:void 0}:t instanceof NI?this.convertScalarType(t):t instanceof V1?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof WQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:{type:"unknown"}}convertScalarType(t){if(this.isBuiltInScalar(t.name))switch(t.name.toLowerCase()){case"string":case"id":return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"int":return{type:"primitive",value:{type:"integer",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"float":return{type:"primitive",value:{type:"double",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"boolean":return{type:"primitive",value:{type:"boolean",default:void 0}};default:return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}else return{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}}convertEnumTypeDefinition(t){return{type:"enum",values:t.getValues().map(n=>({value:n.name,description:this.describeWithDeprecation(n),availability:this.availabilityOf(n)})),default:void 0}}convertObjectTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([o,s])=>({key:un.PropertyKey(o),valueType:this.convertOutputType(s.type),description:this.describeWithDeprecation(s),availability:this.availabilityOf(s),propertyAccess:void 0,arguments:s.args.length>0?s.args.map(a=>this.convertArgument(a)):void 0}));return{type:"object",extends:t.getInterfaces().map(o=>this.getNamespacedTypeId(o.name)),properties:n,extraProperties:void 0}}convertInterfaceTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([i,o])=>({key:un.PropertyKey(i),valueType:this.convertOutputType(o.type),description:this.describeWithDeprecation(o),availability:this.availabilityOf(o),propertyAccess:void 0,arguments:o.args.length>0?o.args.map(s=>this.convertArgument(s)):void 0}));return{type:"object",extends:[],properties:n,extraProperties:void 0}}convertInputObjectTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([i,o])=>({key:un.PropertyKey(i),valueType:this.convertInputType(o.type),description:this.describeWithDeprecation(o),availability:this.availabilityOf(o),propertyAccess:void 0}));return{type:"object",extends:[],properties:n,extraProperties:void 0}}convertUnionTypeDefinition(t){return{type:"undiscriminatedUnion",variants:t.getTypes().map(n=>({typeName:n.name,displayName:n.name,type:{type:"id",value:this.getNamespacedTypeId(n.name),default:void 0},description:n.description??void 0,availability:void 0}))}}convertScalarTypeDefinition(t){let r=t.name.toLowerCase();return{type:"alias",value:this.getBaseTypeForCustomScalar(r)}}getBaseTypeForCustomScalar(t){switch(t){case"datetime":case"timestamp":case"zoneddatetime":case"offsetdatetime":return{type:"primitive",value:{type:"datetime",default:void 0}};case"date":case"localdate":return{type:"primitive",value:{type:"date",default:void 0}};case"email":case"emailaddress":return{type:"primitive",value:{type:"string",format:"email",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"url":case"uri":case"urlstring":return{type:"primitive",value:{type:"string",format:"uri",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"uuid":case"guid":return{type:"primitive",value:{type:"string",format:"uuid",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"json":case"jsonobject":return{type:"unknown"};case"upload":case"file":return{type:"primitive",value:{type:"string",format:"binary",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"bigint":case"long":return{type:"primitive",value:{type:"long",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"decimal":case"currency":case"money":return{type:"primitive",value:{type:"double",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};default:return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}}}});var mCu={};X(mCu,{GraphQLConverter:()=>nnt});var zRo=h(()=>{"use strict";dCu()});function HQ(e,t){let r=e.map(i=>t(i.settings));if(r.some(i=>i!=null))return r.every(i=>i==null||i===!0)}function bUr(e,t){try{return ve.of(e)}catch{throw new O({message:`"${t}: ${e}" must be a relative path, not an absolute one.`,code:O.Code.ConfigError})}}function fGd(e){return e.every(t=>t.settings?.removeDiscriminantsFromSchemas===jn.RemoveDiscriminantsFromSchemas.Never)?jn.RemoveDiscriminantsFromSchemas.Never:jn.RemoveDiscriminantsFromSchemas.Always}async function dGd(e,t){if(e!=null)try{let r=(await(0,EUr.readFile)(e)).toString(),n=Er.load(r);if(!Array.isArray(n))return;for(let o of n){if(typeof o!="object"||o==null){t.logger.warn(`Skipping invalid entry in GraphQL examples file ${e}: expected object`);continue}if(typeof o.operation!="string"){t.logger.warn(`Skipping entry in GraphQL examples file ${e}: missing or invalid 'operation' field`);continue}if(!Array.isArray(o.examples)){t.logger.warn(`Skipping entry for operation '${o.operation}' in ${e}: 'examples' must be an array`);continue}}let i=n.filter(o=>typeof o=="object"&&o!=null&&typeof o.operation=="string"&&Array.isArray(o.examples)).map(o=>{let s=o.examples.filter(a=>typeof a!="object"||a==null||typeof a.query!="string"?(t.logger.warn(`Skipping malformed example for operation '${o.operation}' in ${e}: missing or invalid 'query' field`),!1):!0);if(o.operationType!=null){let a=o.operationType.toLowerCase();a!=="query"&&a!=="mutation"&&a!=="subscription"&&t.logger.warn(`Invalid operationType '${o.operationType}' for operation '${o.operation}' in ${e}: must be 'query', 'mutation', or 'subscription'`)}return{...o,examples:s}}).filter(o=>o.examples.length>0);return i.length>0?i:void 0}catch(r){t.logger.error(`Failed to load GraphQL examples from ${e}:`,Nn(r));return}}async function hCu(e){for(let t of e){if(t.type!=="openapi")continue;let r=t.absoluteFilepathToOverrides==null?[]:Array.isArray(t.absoluteFilepathToOverrides)?t.absoluteFilepathToOverrides:[t.absoluteFilepathToOverrides];for(let n of r)try{let i=(await(0,EUr.readFile)(n)).toString(),o=Er.load(i);if(o!=null&&o.auth!=null)return{auth:o.auth,...o["auth-schemes"]!=null?{"auth-schemes":o["auth-schemes"]}:{}}}catch{}}}function mGd(e){if(e?.auth!=null)return;let t=Object.keys(e?.["auth-schemes"]??{}),r=t[0];if(r!=null)return`generators.yml declares auth-schemes (${t.join(", ")}) but no \`api.auth\`, so the entire auth-schemes block is ignored \u2014 including any \`env:\` overrides. Add \`auth: ${r}\` under \`api\``+(t.length>1?", or list them all under an `auth.any` key":"")+". Without it, auth is re-derived from the spec's securitySchemes and each generator falls back to its own default environment variable name."}var EUr,cp,gCu=h(()=>{"use strict";Il();fEu();e_();ba();Tt();Yt();Mn();Ya();V7();yVr();nIu();Qt();_o();EUr=require("fs/promises");ns();Vrt();dIu();qPo();TIu();LDo();cp=class e extends T2t{type="oss";allSpecs;specs;sources;loader;parseOptions;groupMultiApiEnvironments;graphqlOperations={};graphqlTypes={};openApiSpecsCache=new Map;constructor({allSpecs:t,specs:r,...n}){let i=r.filter(s=>s.type==="openapi"&&s.source.type==="openapi");super({...n,respectReadonlySchemas:HQ(r,s=>s?.respectReadonlySchemas),useReadVariantForResponses:HQ(r,s=>s?.useReadVariantForResponses),respectNullableSchemas:HQ(r,s=>s?.respectNullableSchemas),wrapReferencesToNullableInOptional:HQ(r,s=>s?.wrapReferencesToNullableInOptional),removeDiscriminantsFromSchemas:fGd(r),coerceOptionalSchemasToNullable:HQ(r,s=>s?.coerceOptionalSchemasToNullable),coerceEnumsToLiterals:HQ(r,s=>s?.coerceEnumsToLiterals),onlyIncludeReferencedSchemas:HQ(r,s=>s?.onlyIncludeReferencedSchemas),inlinePathParameters:HQ(r,s=>s?.inlinePathParameters),objectQueryParameters:HQ(r,s=>s?.objectQueryParameters),useBytesForBinaryResponse:HQ(i,s=>s?.useBytesForBinaryResponse),respectForwardCompatibleEnums:HQ(i,s=>s?.respectForwardCompatibleEnums),respectOptionalRequestBody:HQ(i,s=>s?.respectOptionalRequestBody),inlineAllOfSchemas:HQ(r,s=>s?.inlineAllOfSchemas),resolveAliases:(()=>{let s=r.map(u=>u.settings?.resolveAliases);return s.some(u=>u!=null)?s.some(u=>u===!1)?!1:{except:r.flatMap(u=>typeof u.settings?.resolveAliases=="object"?u.settings.resolveAliases.except??[]:[])}:void 0})(),exampleGeneration:r[0]?.settings?.exampleGeneration,groupEnvironmentsByHost:r.some(s=>s.settings?.groupEnvironmentsByHost),multiServerStrategy:r.find(s=>s.settings?.multiServerStrategy!=null)?.settings?.multiServerStrategy,inferDefaultEnvironment:HQ(r,s=>s?.inferDefaultEnvironment),defaultIntegerFormat:r[0]?.settings?.defaultIntegerFormat,pathParameterOrder:r[0]?.settings?.pathParameterOrder,coerceConstsTo:r[0]?.settings?.coerceConstsTo}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new afe(this.absoluteFilePath),this.groupMultiApiEnvironments=this.specs.some(s=>s.settings?.groupMultiApiEnvironments);let o=r.some(s=>s.type==="protobuf");this.parseOptions={onlyIncludeReferencedSchemas:this.onlyIncludeReferencedSchemas,respectReadonlySchemas:this.respectReadonlySchemas,respectNullableSchemas:this.respectNullableSchemas,wrapReferencesToNullableInOptional:this.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:this.coerceOptionalSchemasToNullable,coerceEnumsToLiterals:this.coerceEnumsToLiterals,inlinePathParameters:this.inlinePathParameters,objectQueryParameters:this.objectQueryParameters,exampleGeneration:this.exampleGeneration,useBytesForBinaryResponse:this.useBytesForBinaryResponse,respectForwardCompatibleEnums:this.respectForwardCompatibleEnums,inlineAllOfSchemas:this.inlineAllOfSchemas,resolveAliases:this.resolveAliases,removeDiscriminantsFromSchemas:this.removeDiscriminantsFromSchemas,groupMultiApiEnvironments:this.groupMultiApiEnvironments,groupEnvironmentsByHost:this.groupEnvironmentsByHost,defaultIntegerFormat:this.defaultIntegerFormat,pathParameterOrder:this.pathParameterOrder,coerceConstsTo:this.coerceConstsTo,respectByteFormat:o}}getGraphqlOperations(){return this.graphqlOperations}getGraphqlTypes(){return this.graphqlTypes}getGraphqlOperationsCount(){return Object.keys(this.graphqlOperations).length}getGraphqlTypesCount(){return Object.keys(this.graphqlTypes).length}async processGraphQLSpecs(t){let{GraphQLConverter:r}=await Promise.resolve().then(()=>(zRo(),mCu)),n=this.allSpecs.filter(i=>i.type==="graphql");for(let[,i]of lkr(n)){let o=i.map(s=>s.absoluteFilepath);try{let s=(await Promise.all(i.map(u=>dGd(u.absoluteFilepathToExamples,t)))).filter(ia).flat(),c=await new r({context:t,filePath:o,namespace:i[0]?.namespace,examples:s}).convert();Object.assign(this.graphqlOperations,c.graphqlOperations),Object.assign(this.graphqlTypes,c.types)}catch(s){t.logger.error(`Failed to process GraphQL spec(s) ${o.join(", ")}:`,Nn(s))}}}getOpenAPISpecsCached({context:t,relativePathToDependency:r}){let n=r??"",i=this.openApiSpecsCache.get(n);return i==null&&(i=eLe({context:t,specs:this.specs,relativePathToDependency:r}),this.openApiSpecsCache.set(n,i)),i}async getOpenAPIIr({context:t,relativePathToDependency:r,loadAiExamples:n=!1},i){let o=await this.getOpenAPISpecsCached({context:t,relativePathToDependency:r});return Wje({context:t,documents:await this.loader.loadDocuments({context:t,specs:o,loadAiExamples:n}),options:{...i,...this.parseOptions}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,logWarnings:o}){let s=this.generateAllProtobufIRs({context:t}),a=await this.getOpenAPISpecsCached({context:t}),c=await this.loader.loadDocuments({context:t,specs:a}),u=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,l=mGd(this.generatorsConfiguration?.api);l!=null&&t.logger.warn(l),u==null&&(u=await hCu(a));let p=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;p&&t.logger.trace("Using environment overrides from generators configuration");let d=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;d&&t.logger.trace("Using global header overrides from generators configuration");let f,m=[];for(let y of c){let E=Me(this.absoluteFilePath,ve.of(y.source?.file??"")),x=fE(nu(),E),I=new y_({logger:t.logger,relativeFilepathToSpec:x});m.push(I);let C;switch(y.type){case"openapi":{let P=y.value,D=y.namespace??P["x-fern-sdk-namespace"],S=new cfe({namespace:D,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:P,exampleGenerationArgs:{disabled:!1},errorCollector:I,authOverrides:u,environmentOverrides:p,globalHeaderOverrides:d,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,settings:X7({options:y.settings}),documentBaseDir:gn(E)});C=await new c4t({context:S,audiences:r}).convert();break}case"asyncapi":{let P=y.namespace??y.value["x-fern-sdk-namespace"],D=new o4t({namespace:P,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:y.value,exampleGenerationArgs:{disabled:!1},errorCollector:I,authOverrides:u,enableUniqueErrorsPerEndpoint:n,settings:X7({options:y.settings}),generateV1Examples:i});C=await new i4t({context:D,audiences:r}).convert();break}default:I.collect({message:`Unsupported document type: ${y}`,path:[]});break}let T=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});C!=null&&(f=f===void 0?C:QMe(f,C,T))}for(let y of this.allSpecs)if(y.type==="openrpc"){let E=y.absoluteFilepath,x=fE(nu(),E),I=new y_({logger:t.logger,relativeFilepathToSpec:x});m.push(I);let C=new l4t({namespace:y.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await SDo({context:t,absoluteFilePath:y.absoluteFilepath,absoluteFilePathToOverrides:y.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:I,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,settings:X7()}),P=await new u4t({context:C,audiences:r}).convert(),D=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});P!=null&&(f=f===void 0?P:QMe(f,P,D))}let g=await s,A=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});for(let y of g)f=f===void 0?y:QMe(f,y,A);for(let y of m)if(y.hasErrors()){let E=y.getErrorStats(),x=y.relativeFilepathToSpec?` for ${y.relativeFilepathToSpec}`:"";E.numErrors>0?t.logger.log("error",`API validation${x} completed with ${E.numErrors} errors.`):E.numWarnings>0&&o&&t.logger.log("warn",`API validation${x} completed with ${E.numWarnings} warnings.`),await y.logErrors({logWarnings:o})}if(f===void 0)throw new O({message:"Failed to generate intermediate representation",code:O.Code.IrConversionError});return u!=null&&(f=vDo({ir:f,authOverrides:u})),f}async generateAllProtobufIRs({context:t}){let r=this.allSpecs.filter(i=>i.type==="protobuf");if(r.length===0)return[];let n=[];for(let i of r)try{let s=await new CVr({context:t}).generate({absoluteFilepathToProtobufRoot:i.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:i.absoluteFilepathToProtobufTarget,local:!0,deps:i.dependencies}),a=await(0,EUr.readFile)(s,"utf-8");if(a!=null){let c=ki.IntermediateRepresentation.parse(JSON.parse(a),{allowUnrecognizedEnumValues:!0,skipValidation:!0});if(c.ok){n.push(c.value);continue}t.logger.log("error","Failed to parse protobuf IR")}}catch(o){t.logger.log("warn","Failed to parse protobuf IR: "+o)}return n}async toFernWorkspace({context:t},r,n){if(n!=null)return this.createWorkspaceWithSpecsOverride({context:t},n,r);let i=r;if(this.generatorsConfiguration?.api?.auth==null&&r?.auth==null){let s=await this.getOpenAPISpecsCached({context:t}),a=await hCu(s);a!=null&&(i={...r,auth:a.auth,authSchemes:a["auth-schemes"]})}let o=await this.getDefinition({context:t},i);return new Vj({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:o,cliVersion:this.cliVersion,sources:this.sources})}async createWorkspaceWithSpecsOverride({context:t},r,n){let i=await this.convertSpecsOverrideToSpecs(r),o=i.filter(c=>c.type!=="protobuf"||!c.fromOpenAPI),s=new e({allSpecs:o,specs:i.filter(c=>c.type==="openapi"||c.type==="protobuf"),generatorsConfiguration:this.generatorsConfiguration,workspaceName:this.workspaceName,cliVersion:this.cliVersion,absoluteFilePath:this.absoluteFilePath,changelog:this.changelog}),a=await s.getDefinition({context:t},n);return new Vj({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:a,cliVersion:this.cliVersion,sources:s.sources})}async convertSpecsOverrideToSpecs(t){if(!Array.isArray(t))throw new O({message:"Conjure specs override is not yet supported",code:O.Code.InternalError});let r=[];for(let n of t)if(jn.isOpenApiSpecSchema(n)){if(typeof n.openapi!="string")throw new Error(`Git remote sources are not supported in specs overrides. Please use a local path instead of the git source for repo '${n.openapi.git.repo}'.`);let i=n.openapi,o=Me(this.absoluteFilePath,bUr(i,"openapi")),s,a=[];n.overrides!=null&&(Array.isArray(n.overrides)?a.push(...n.overrides.map(l=>Me(this.absoluteFilePath,bUr(l,"overrides")))):a.push(Me(this.absoluteFilePath,bUr(n.overrides,"overrides")))),a.length>0&&(s=a.length===1?a[0]:a);let c=n.overlays?Me(this.absoluteFilePath,bUr(n.overlays,"overlays")):void 0,u={type:"openapi",absoluteFilepath:o,absoluteFilepathToOverrides:s,absoluteFilepathToOverlays:c,settings:this.specs.length>0?this.specs[0]?.settings:void 0,source:{type:"openapi",file:o},namespace:n.namespace??void 0};r.push(u)}else throw new O({message:"Spec type override not yet supported. Only OpenAPI specs are currently supported in specs override.",code:O.Code.InternalError});return r}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.allSpecs.flatMap(t=>{let r=t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,n=Array.isArray(t.absoluteFilepathToOverrides)?t.absoluteFilepathToOverrides:t.absoluteFilepathToOverrides!=null?[t.absoluteFilepathToOverrides]:[],i=t.type==="graphql"?t.absoluteFilepathToExamples:void 0;return[r,...n,...i!=null?[i]:[]]}).filter(ia)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,n=[];return t.reduce((i,o)=>{let s=o.type==="protobuf"?o.absoluteFilepathToProtobufRoot:o.absoluteFilepath;return r.has(s)||(r.add(s),i.push({type:o.type,id:PD(),absoluteFilePath:s,absoluteFilePathToOverrides:o.type==="openapi"?o.absoluteFilepathToOverrides:void 0})),i},n)}}});var ACu=h(()=>{"use strict";NPo();LDo();jPo();_Po();n6e()});var Am=h(()=>{"use strict";CYc();OAu();qPo();gCu();DDo();zDo();xVr();ACu()});var uko=b((fxI,MCu)=>{"use strict";var p_r=a_().Buffer,R7d=require("stream"),k7d=require("util");function f_r(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=p_r.alloc(0),this;if(typeof e.pipe=="function")return this.buffer=p_r.alloc(0),e.pipe(this),this;if(e.length||typeof e=="object")return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}k7d.inherits(f_r,R7d);f_r.prototype.write=function(t){this.buffer=p_r.concat([this.buffer,p_r.from(t)]),this.emit("data",t)};f_r.prototype.end=function(t){t&&this.write(t),this.emit("end",t),this.emit("close"),this.writable=!1,this.readable=!1};MCu.exports=f_r});var VCu=b((dxI,LCu)=>{"use strict";function lko(e){var t=(e/8|0)+(e%8===0?0:1);return t}var F7d={ES256:lko(256),ES384:lko(384),ES512:lko(521)};function N7d(e){var t=F7d[e];if(t)return t;throw new Error('Unknown algorithm "'+e+'"')}LCu.exports=N7d});var KCu=b((mxI,HCu)=>{"use strict";var d_r=a_().Buffer,_Cu=VCu(),m_r=128,qCu=0,j7d=32,Q7d=16,z7d=2,GCu=Q7d|j7d|qCu<<6,h_r=z7d|qCu<<6;function M7d(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function WCu(e){if(d_r.isBuffer(e))return e;if(typeof e=="string")return d_r.from(e,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function L7d(e,t){e=WCu(e);var r=_Cu(t),n=r+1,i=e.length,o=0;if(e[o++]!==GCu)throw new Error('Could not find expected "seq"');var s=e[o++];if(s===(m_r|1)&&(s=e[o++]),i-o<s)throw new Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(e[o++]!==h_r)throw new Error('Could not find expected "int" for "r"');var a=e[o++];if(i-o-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=o;if(o+=a,e[o++]!==h_r)throw new Error('Could not find expected "int" for "s"');var u=e[o++];if(i-o!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var l=o;if(o+=u,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var p=r-a,d=r-u,f=d_r.allocUnsafe(p+a+d+u);for(o=0;o<p;++o)f[o]=0;e.copy(f,o,c+Math.max(-p,0),c+a),o=r;for(var m=o;o<m+d;++o)f[o]=0;return e.copy(f,o,l+Math.max(-d,0),l+u),f=f.toString("base64"),f=M7d(f),f}function UCu(e,t,r){for(var n=0;t+n<r&&e[t+n]===0;)++n;var i=e[t+n]>=m_r;return i&&--n,n}function V7d(e,t){e=WCu(e);var r=_Cu(t),n=e.length;if(n!==r*2)throw new TypeError('"'+t+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var i=UCu(e,0,r),o=UCu(e,r,e.length),s=r-i,a=r-o,c=2+s+1+1+a,u=c<m_r,l=d_r.allocUnsafe((u?2:3)+c),p=0;return l[p++]=GCu,u?l[p++]=c:(l[p++]=m_r|1,l[p++]=c&255),l[p++]=h_r,l[p++]=s,i<0?(l[p++]=0,p+=e.copy(l,p,0,r)):p+=e.copy(l,p,i,r),l[p++]=h_r,l[p++]=a,o<0?(l[p++]=0,e.copy(l,p,r)):e.copy(l,p,r+o),l}HCu.exports={derToJose:L7d,joseToDer:V7d}});var YCu=b((hxI,JCu)=>{"use strict";var AVt=require("buffer").Buffer,pko=require("buffer").SlowBuffer;JCu.exports=g_r;function g_r(e,t){if(!AVt.isBuffer(e)||!AVt.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}g_r.install=function(){AVt.prototype.equal=pko.prototype.equal=function(t){return g_r(this,t)}};var U7d=AVt.prototype.equal,_7d=pko.prototype.equal;g_r.restore=function(){AVt.prototype.equal=U7d,pko.prototype.equal=_7d}});var hko=b((gxI,owu)=>{"use strict";var Ent=a_().Buffer,C_=require("crypto"),ZCu=KCu(),XCu=require("util"),q7d=`"%s" is not a valid algorithm.
940
+ ${n}`:n}isBuiltInScalar(t){return["String","Int","Float","Boolean","ID"].includes(t)}getNamespacedTypeId(t){let r=this.namespace?`${this.namespace}_${t}`:t;return un.TypeId(r)}getNamespacedOperationId(t){let r=this.namespace?`${this.namespace}_${t}`:t;return un.GraphQlOperationId(r)}getNamespacedTypeName(t){return this.namespace?`${this.namespace}_${t}`:t}isActualSubscriptionRootType(t){return!(t.getInterfaces().length>0)}isNamespaceType(t){let r=Object.values(t.getFields());return r.length===0?!1:r.every(n=>n.args.length>0)}buildSchema(t){try{let r=q4t(t);for(let n of sUr(r))this.context.logger.warn(`Invalid GraphQL schema: ${n.message}`);return r}catch(r){let n;try{n=q4t(t,{assumeValidSDL:!0})}catch{throw r}return this.context.logger.warn(`Invalid GraphQL schema: ${r instanceof Error?r.message:String(r)} Continuing without SDL validation.`),n}}async convert(){let t=await Promise.all(this.filePaths.map(async u=>({filePath:u,sdl:await(0,fCu.readFile)(u,"utf-8")}))),{document:r,conflicts:n}=aCu(t);for(let u of n){let l=`${u.typeName}.${u.memberName}`;this.context.logger.warn(u.kept===u.dropped?`GraphQL schema conflict: ${l} is declared more than once in ${u.kept} with differing shapes. Keeping the first declaration.`:`GraphQL schema conflict: ${l} is defined in both ${u.kept} and ${u.dropped}. Keeping the definition from ${u.kept}.`)}this.schema=this.buildSchema(r),this.collectTypeDefinitions();let i=[],o=this.schema.getQueryType();o&&this.convertOperations(o,"QUERY",i);let s=this.schema.getMutationType();s&&this.convertOperations(s,"MUTATION",i);let a=this.schema.getSubscriptionType();a&&this.isActualSubscriptionRootType(a)&&this.convertOperations(a,"SUBSCRIPTION",i);let c=this.resolveOperationIds(i);for(let u of this.namespaceTypeNames)delete this.typeCategories[this.getNamespacedTypeId(u)];return{graphqlOperations:c,types:this.types,typeCategories:this.typeCategories}}resolveOperationIds(t){let r=new Map;for(let i of t)r.set(i.flatId,(r.get(i.flatId)??0)+1);let n={};for(let i of t){let s=(r.get(i.flatId)??0)>1?i.namespacedId:i.flatId,a=this.getNamespacedOperationId(s);n[a]={...i.operation,id:a}}return n}collectTypeDefinitions(){if(!this.schema)return;let t=this.schema.getTypeMap();for(let[r,n]of Object.entries(t)){if(r.startsWith("__")||n===this.schema.getQueryType()||n===this.schema.getMutationType()||n===this.schema.getSubscriptionType()&&n instanceof BE&&this.isActualSubscriptionRootType(n)||n instanceof NI&&this.isBuiltInScalar(r))continue;let i=this.getNamespacedTypeId(r);if(this.typeCategories[i]=this.typeCategoryOf(n),n instanceof V1){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertEnumTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof qQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertInterfaceTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof BE){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertObjectTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof WQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertInputObjectTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof GQ){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertUnionTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}else if(n instanceof NI){this.processingTypes.add(r);try{this.types[i]={name:this.getNamespacedTypeName(r),shape:this.convertScalarTypeDefinition(n),displayName:void 0,description:n.description??void 0,availability:void 0}}finally{this.processingTypes.delete(r)}}}}typeCategoryOf(t){if(t instanceof BE)return"object";if(t instanceof WQ)return"input";if(t instanceof V1)return"enum";if(t instanceof qQ)return"interface";if(t instanceof GQ)return"union";if(t instanceof NI)return"scalar";be(t)}buildOperationId(t,r){return`${t.toLowerCase()}_${r.join(".")}`}convertOperations(t,r,n){let i=t.getFields();for(let[o,s]of Object.entries(i)){let a=this.unwrapNonNull(s.type);if(a instanceof BE&&s.args.length===0&&this.isNamespaceType(a)){if(r==="QUERY"){let c=this.buildOperationId(r,[o]);n.push({flatId:c,namespacedId:c,operation:this.convertField(s,o,r)})}this.namespaceTypeNames.add(a.name),this.convertNamespaceOperations(a,r,n,[o])}else{let c=this.buildOperationId(r,[o]);n.push({flatId:c,namespacedId:c,operation:this.convertField(s,o,r)})}}}convertNamespaceOperations(t,r,n,i){let o=t.getFields();for(let[s,a]of Object.entries(o)){let c=this.buildOperationId(r,[s]),u=this.buildOperationId(r,[...i,s]);n.push({flatId:c,namespacedId:u,operation:this.convertField(a,s,r,i)})}}unwrapNonNull(t){return t instanceof Rc?t.ofType:t}convertField(t,r,n,i){let o=t.args.map(a=>this.convertArgument(a)),s=this.examplesByOperation.get(`${n.toLowerCase()}:${r}`)??this.examplesByOperation.get(r);return{id:un.GraphQlOperationId(""),operationType:n,name:r,displayName:void 0,description:this.describeWithDeprecation(t),availability:this.availabilityOf(t),fieldPath:i!=null&&i.length>0?i:void 0,arguments:o.length>0?o:void 0,returnType:this.convertOutputType(t.type),examples:s!=null&&s.length>0?s:void 0,snippets:void 0}}convertArgument(t){return{name:t.name,description:this.describeWithDeprecation(t),availability:this.availabilityOf(t),type:this.convertInputType(t.type),defaultValue:t.defaultValue}}convertOutputType(t){return t instanceof Rc?this.convertNonNullOutputType(t.ofType):{type:"optional",itemType:this.convertNonNullOutputType(t),defaultValue:void 0}}convertNonNullOutputType(t){return t instanceof vy?{type:"list",itemType:this.convertOutputType(t.ofType),minItems:void 0,maxItems:void 0}:t instanceof NI?this.convertScalarType(t):t instanceof V1?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof BE||t instanceof qQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof GQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:{type:"unknown"}}convertInputType(t){return t instanceof Rc?this.convertNonNullInputType(t.ofType):{type:"optional",itemType:this.convertNonNullInputType(t),defaultValue:void 0}}convertNonNullInputType(t){return t instanceof vy?{type:"list",itemType:this.convertInputType(t.ofType),minItems:void 0,maxItems:void 0}:t instanceof NI?this.convertScalarType(t):t instanceof V1?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:t instanceof WQ?{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}:{type:"unknown"}}convertScalarType(t){if(this.isBuiltInScalar(t.name))switch(t.name.toLowerCase()){case"string":case"id":return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"int":return{type:"primitive",value:{type:"integer",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"float":return{type:"primitive",value:{type:"double",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"boolean":return{type:"primitive",value:{type:"boolean",default:void 0}};default:return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}else return{type:"id",value:this.getNamespacedTypeId(t.name),default:void 0}}convertEnumTypeDefinition(t){return{type:"enum",values:t.getValues().map(n=>({value:n.name,description:this.describeWithDeprecation(n),availability:this.availabilityOf(n)})),default:void 0}}convertObjectTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([o,s])=>({key:un.PropertyKey(o),valueType:this.convertOutputType(s.type),description:this.describeWithDeprecation(s),availability:this.availabilityOf(s),propertyAccess:void 0,arguments:s.args.length>0?s.args.map(a=>this.convertArgument(a)):void 0}));return{type:"object",extends:t.getInterfaces().map(o=>this.getNamespacedTypeId(o.name)),properties:n,extraProperties:void 0}}convertInterfaceTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([i,o])=>({key:un.PropertyKey(i),valueType:this.convertOutputType(o.type),description:this.describeWithDeprecation(o),availability:this.availabilityOf(o),propertyAccess:void 0,arguments:o.args.length>0?o.args.map(s=>this.convertArgument(s)):void 0}));return{type:"object",extends:[],properties:n,extraProperties:void 0}}convertInputObjectTypeDefinition(t){let r=t.getFields(),n=Object.entries(r).map(([i,o])=>({key:un.PropertyKey(i),valueType:this.convertInputType(o.type),description:this.describeWithDeprecation(o),availability:this.availabilityOf(o),propertyAccess:void 0}));return{type:"object",extends:[],properties:n,extraProperties:void 0}}convertUnionTypeDefinition(t){return{type:"undiscriminatedUnion",variants:t.getTypes().map(n=>({typeName:n.name,displayName:n.name,type:{type:"id",value:this.getNamespacedTypeId(n.name),default:void 0},description:n.description??void 0,availability:void 0}))}}convertScalarTypeDefinition(t){let r=t.name.toLowerCase();return{type:"alias",value:this.getBaseTypeForCustomScalar(r)}}getBaseTypeForCustomScalar(t){switch(t){case"datetime":case"timestamp":case"zoneddatetime":case"offsetdatetime":return{type:"primitive",value:{type:"datetime",default:void 0}};case"date":case"localdate":return{type:"primitive",value:{type:"date",default:void 0}};case"email":case"emailaddress":return{type:"primitive",value:{type:"string",format:"email",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"url":case"uri":case"urlstring":return{type:"primitive",value:{type:"string",format:"uri",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"uuid":case"guid":return{type:"primitive",value:{type:"string",format:"uuid",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"json":case"jsonobject":return{type:"unknown"};case"upload":case"file":return{type:"primitive",value:{type:"string",format:"binary",regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}};case"bigint":case"long":return{type:"primitive",value:{type:"long",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};case"decimal":case"currency":case"money":return{type:"primitive",value:{type:"double",minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,default:void 0}};default:return{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}}}});var mCu={};X(mCu,{GraphQLConverter:()=>nnt});var zRo=h(()=>{"use strict";dCu()});function HQ(e,t){let r=e.map(i=>t(i.settings));if(r.some(i=>i!=null))return r.every(i=>i==null||i===!0)}function bUr(e,t){try{return ve.of(e)}catch{throw new O({message:`"${t}: ${e}" must be a relative path, not an absolute one.`,code:O.Code.ConfigError})}}function fGd(e){return e.every(t=>t.settings?.removeDiscriminantsFromSchemas===jn.RemoveDiscriminantsFromSchemas.Never)?jn.RemoveDiscriminantsFromSchemas.Never:jn.RemoveDiscriminantsFromSchemas.Always}async function dGd(e,t){if(e!=null)try{let r=(await(0,EUr.readFile)(e)).toString(),n=Er.load(r);if(!Array.isArray(n))return;for(let o of n){if(typeof o!="object"||o==null){t.logger.warn(`Skipping invalid entry in GraphQL examples file ${e}: expected object`);continue}if(typeof o.operation!="string"){t.logger.warn(`Skipping entry in GraphQL examples file ${e}: missing or invalid 'operation' field`);continue}if(!Array.isArray(o.examples)){t.logger.warn(`Skipping entry for operation '${o.operation}' in ${e}: 'examples' must be an array`);continue}}let i=n.filter(o=>typeof o=="object"&&o!=null&&typeof o.operation=="string"&&Array.isArray(o.examples)).map(o=>{let s=o.examples.filter(a=>typeof a!="object"||a==null||typeof a.query!="string"?(t.logger.warn(`Skipping malformed example for operation '${o.operation}' in ${e}: missing or invalid 'query' field`),!1):!0);if(o.operationType!=null){let a=o.operationType.toLowerCase();a!=="query"&&a!=="mutation"&&a!=="subscription"&&t.logger.warn(`Invalid operationType '${o.operationType}' for operation '${o.operation}' in ${e}: must be 'query', 'mutation', or 'subscription'`)}return{...o,examples:s}}).filter(o=>o.examples.length>0);return i.length>0?i:void 0}catch(r){t.logger.error(`Failed to load GraphQL examples from ${e}:`,Nn(r));return}}async function hCu(e){for(let t of e){if(t.type!=="openapi")continue;let r=t.absoluteFilepathToOverrides==null?[]:Array.isArray(t.absoluteFilepathToOverrides)?t.absoluteFilepathToOverrides:[t.absoluteFilepathToOverrides];for(let n of r)try{let i=(await(0,EUr.readFile)(n)).toString(),o=Er.load(i);if(o!=null&&o.auth!=null)return{auth:o.auth,...o["auth-schemes"]!=null?{"auth-schemes":o["auth-schemes"]}:{}}}catch{}}}function mGd(e){if(e?.auth!=null)return;let t=Object.keys(e?.["auth-schemes"]??{}),r=t[0];if(r!=null)return`generators.yml declares auth-schemes (${t.join(", ")}) but no \`api.auth\`, so the entire auth-schemes block is ignored \u2014 including any \`env:\` overrides. Add \`auth: ${r}\` under \`api\``+(t.length>1?", or list them all under an `auth.any` key":"")+". Without it, auth is re-derived from the spec's securitySchemes and each generator falls back to its own default environment variable name."}var EUr,cp,gCu=h(()=>{"use strict";Il();fEu();e_();ba();Tt();Yt();Mn();Ya();V7();yVr();nIu();Qt();_o();EUr=require("fs/promises");ns();Vrt();dIu();qPo();TIu();LDo();cp=class e extends T2t{type="oss";allSpecs;specs;sources;loader;parseOptions;groupMultiApiEnvironments;graphqlOperations={};graphqlTypes={};openApiSpecsCache=new Map;hasWarnedOrphanedAuthSchemes=!1;constructor({allSpecs:t,specs:r,...n}){let i=r.filter(s=>s.type==="openapi"&&s.source.type==="openapi");super({...n,respectReadonlySchemas:HQ(r,s=>s?.respectReadonlySchemas),useReadVariantForResponses:HQ(r,s=>s?.useReadVariantForResponses),respectNullableSchemas:HQ(r,s=>s?.respectNullableSchemas),wrapReferencesToNullableInOptional:HQ(r,s=>s?.wrapReferencesToNullableInOptional),removeDiscriminantsFromSchemas:fGd(r),coerceOptionalSchemasToNullable:HQ(r,s=>s?.coerceOptionalSchemasToNullable),coerceEnumsToLiterals:HQ(r,s=>s?.coerceEnumsToLiterals),onlyIncludeReferencedSchemas:HQ(r,s=>s?.onlyIncludeReferencedSchemas),inlinePathParameters:HQ(r,s=>s?.inlinePathParameters),objectQueryParameters:HQ(r,s=>s?.objectQueryParameters),useBytesForBinaryResponse:HQ(i,s=>s?.useBytesForBinaryResponse),respectForwardCompatibleEnums:HQ(i,s=>s?.respectForwardCompatibleEnums),respectOptionalRequestBody:HQ(i,s=>s?.respectOptionalRequestBody),inlineAllOfSchemas:HQ(r,s=>s?.inlineAllOfSchemas),resolveAliases:(()=>{let s=r.map(u=>u.settings?.resolveAliases);return s.some(u=>u!=null)?s.some(u=>u===!1)?!1:{except:r.flatMap(u=>typeof u.settings?.resolveAliases=="object"?u.settings.resolveAliases.except??[]:[])}:void 0})(),exampleGeneration:r[0]?.settings?.exampleGeneration,groupEnvironmentsByHost:r.some(s=>s.settings?.groupEnvironmentsByHost),multiServerStrategy:r.find(s=>s.settings?.multiServerStrategy!=null)?.settings?.multiServerStrategy,inferDefaultEnvironment:HQ(r,s=>s?.inferDefaultEnvironment),defaultIntegerFormat:r[0]?.settings?.defaultIntegerFormat,pathParameterOrder:r[0]?.settings?.pathParameterOrder,coerceConstsTo:r[0]?.settings?.coerceConstsTo}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new afe(this.absoluteFilePath),this.groupMultiApiEnvironments=this.specs.some(s=>s.settings?.groupMultiApiEnvironments);let o=r.some(s=>s.type==="protobuf");this.parseOptions={onlyIncludeReferencedSchemas:this.onlyIncludeReferencedSchemas,respectReadonlySchemas:this.respectReadonlySchemas,respectNullableSchemas:this.respectNullableSchemas,wrapReferencesToNullableInOptional:this.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:this.coerceOptionalSchemasToNullable,coerceEnumsToLiterals:this.coerceEnumsToLiterals,inlinePathParameters:this.inlinePathParameters,objectQueryParameters:this.objectQueryParameters,exampleGeneration:this.exampleGeneration,useBytesForBinaryResponse:this.useBytesForBinaryResponse,respectForwardCompatibleEnums:this.respectForwardCompatibleEnums,inlineAllOfSchemas:this.inlineAllOfSchemas,resolveAliases:this.resolveAliases,removeDiscriminantsFromSchemas:this.removeDiscriminantsFromSchemas,groupMultiApiEnvironments:this.groupMultiApiEnvironments,groupEnvironmentsByHost:this.groupEnvironmentsByHost,defaultIntegerFormat:this.defaultIntegerFormat,pathParameterOrder:this.pathParameterOrder,coerceConstsTo:this.coerceConstsTo,respectByteFormat:o}}getGraphqlOperations(){return this.graphqlOperations}getGraphqlTypes(){return this.graphqlTypes}getGraphqlOperationsCount(){return Object.keys(this.graphqlOperations).length}getGraphqlTypesCount(){return Object.keys(this.graphqlTypes).length}async processGraphQLSpecs(t){let{GraphQLConverter:r}=await Promise.resolve().then(()=>(zRo(),mCu)),n=this.allSpecs.filter(i=>i.type==="graphql");for(let[,i]of lkr(n)){let o=i.map(s=>s.absoluteFilepath);try{let s=(await Promise.all(i.map(u=>dGd(u.absoluteFilepathToExamples,t)))).filter(ia).flat(),c=await new r({context:t,filePath:o,namespace:i[0]?.namespace,examples:s}).convert();Object.assign(this.graphqlOperations,c.graphqlOperations),Object.assign(this.graphqlTypes,c.types)}catch(s){t.logger.error(`Failed to process GraphQL spec(s) ${o.join(", ")}:`,Nn(s))}}}getOpenAPISpecsCached({context:t,relativePathToDependency:r}){let n=r??"",i=this.openApiSpecsCache.get(n);return i==null&&(i=eLe({context:t,specs:this.specs,relativePathToDependency:r}),this.openApiSpecsCache.set(n,i)),i}async getOpenAPIIr({context:t,relativePathToDependency:r,loadAiExamples:n=!1},i){let o=await this.getOpenAPISpecsCached({context:t,relativePathToDependency:r});return Wje({context:t,documents:await this.loader.loadDocuments({context:t,specs:o,loadAiExamples:n}),options:{...i,...this.parseOptions}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,logWarnings:o}){let s=this.generateAllProtobufIRs({context:t}),a=await this.getOpenAPISpecsCached({context:t}),c=await this.loader.loadDocuments({context:t,specs:a}),u=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;this.warnOnOrphanedAuthSchemes(t),u==null&&(u=await hCu(a));let l=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using environment overrides from generators configuration");let p=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;p&&t.logger.trace("Using global header overrides from generators configuration");let d,f=[];for(let A of c){let y=Me(this.absoluteFilePath,ve.of(A.source?.file??"")),E=fE(nu(),y),x=new y_({logger:t.logger,relativeFilepathToSpec:E});f.push(x);let I;switch(A.type){case"openapi":{let T=A.value,P=A.namespace??T["x-fern-sdk-namespace"],D=new cfe({namespace:P,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:T,exampleGenerationArgs:{disabled:!1},errorCollector:x,authOverrides:u,environmentOverrides:l,globalHeaderOverrides:p,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,settings:X7({options:A.settings}),documentBaseDir:gn(y)});I=await new c4t({context:D,audiences:r}).convert();break}case"asyncapi":{let T=A.namespace??A.value["x-fern-sdk-namespace"],P=new o4t({namespace:T,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:A.value,exampleGenerationArgs:{disabled:!1},errorCollector:x,authOverrides:u,enableUniqueErrorsPerEndpoint:n,settings:X7({options:A.settings}),generateV1Examples:i});I=await new i4t({context:P,audiences:r}).convert();break}default:x.collect({message:`Unsupported document type: ${A}`,path:[]});break}let C=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});I!=null&&(d=d===void 0?I:QMe(d,I,C))}for(let A of this.allSpecs)if(A.type==="openrpc"){let y=A.absoluteFilepath,E=fE(nu(),y),x=new y_({logger:t.logger,relativeFilepathToSpec:E});f.push(x);let I=new l4t({namespace:A.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await SDo({context:t,absoluteFilePath:A.absoluteFilepath,absoluteFilePathToOverrides:A.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:x,enableUniqueErrorsPerEndpoint:n,generateV1Examples:i,settings:X7()}),T=await new u4t({context:I,audiences:r}).convert(),P=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});T!=null&&(d=d===void 0?T:QMe(d,T,P))}let m=await s,g=Nw({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});for(let A of m)d=d===void 0?A:QMe(d,A,g);for(let A of f)if(A.hasErrors()){let y=A.getErrorStats(),E=A.relativeFilepathToSpec?` for ${A.relativeFilepathToSpec}`:"";y.numErrors>0?t.logger.log("error",`API validation${E} completed with ${y.numErrors} errors.`):y.numWarnings>0&&o&&t.logger.log("warn",`API validation${E} completed with ${y.numWarnings} warnings.`),await A.logErrors({logWarnings:o})}if(d===void 0)throw new O({message:"Failed to generate intermediate representation",code:O.Code.IrConversionError});return u!=null&&(d=vDo({ir:d,authOverrides:u})),d}async generateAllProtobufIRs({context:t}){let r=this.allSpecs.filter(i=>i.type==="protobuf");if(r.length===0)return[];let n=[];for(let i of r)try{let s=await new CVr({context:t}).generate({absoluteFilepathToProtobufRoot:i.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:i.absoluteFilepathToProtobufTarget,local:!0,deps:i.dependencies}),a=await(0,EUr.readFile)(s,"utf-8");if(a!=null){let c=ki.IntermediateRepresentation.parse(JSON.parse(a),{allowUnrecognizedEnumValues:!0,skipValidation:!0});if(c.ok){n.push(c.value);continue}t.logger.log("error","Failed to parse protobuf IR")}}catch(o){t.logger.log("warn","Failed to parse protobuf IR: "+o)}return n}warnOnOrphanedAuthSchemes(t){if(this.hasWarnedOrphanedAuthSchemes)return;let r=mGd(this.generatorsConfiguration?.api);r!=null&&(this.hasWarnedOrphanedAuthSchemes=!0,t.logger.warn(r))}async toFernWorkspace({context:t},r,n){if(this.warnOnOrphanedAuthSchemes(t),n!=null)return this.createWorkspaceWithSpecsOverride({context:t},n,r);let i=r;if(this.generatorsConfiguration?.api?.auth==null&&r?.auth==null){let s=await this.getOpenAPISpecsCached({context:t}),a=await hCu(s);a!=null&&(i={...r,auth:a.auth,authSchemes:a["auth-schemes"]})}let o=await this.getDefinition({context:t},i);return new Vj({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:o,cliVersion:this.cliVersion,sources:this.sources})}async createWorkspaceWithSpecsOverride({context:t},r,n){let i=await this.convertSpecsOverrideToSpecs(r),o=i.filter(c=>c.type!=="protobuf"||!c.fromOpenAPI),s=new e({allSpecs:o,specs:i.filter(c=>c.type==="openapi"||c.type==="protobuf"),generatorsConfiguration:this.generatorsConfiguration,workspaceName:this.workspaceName,cliVersion:this.cliVersion,absoluteFilePath:this.absoluteFilePath,changelog:this.changelog}),a=await s.getDefinition({context:t},n);return new Vj({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:a,cliVersion:this.cliVersion,sources:s.sources})}async convertSpecsOverrideToSpecs(t){if(!Array.isArray(t))throw new O({message:"Conjure specs override is not yet supported",code:O.Code.InternalError});let r=[];for(let n of t)if(jn.isOpenApiSpecSchema(n)){if(typeof n.openapi!="string")throw new Error(`Git remote sources are not supported in specs overrides. Please use a local path instead of the git source for repo '${n.openapi.git.repo}'.`);let i=n.openapi,o=Me(this.absoluteFilePath,bUr(i,"openapi")),s,a=[];n.overrides!=null&&(Array.isArray(n.overrides)?a.push(...n.overrides.map(l=>Me(this.absoluteFilePath,bUr(l,"overrides")))):a.push(Me(this.absoluteFilePath,bUr(n.overrides,"overrides")))),a.length>0&&(s=a.length===1?a[0]:a);let c=n.overlays?Me(this.absoluteFilePath,bUr(n.overlays,"overlays")):void 0,u={type:"openapi",absoluteFilepath:o,absoluteFilepathToOverrides:s,absoluteFilepathToOverlays:c,settings:this.specs.length>0?this.specs[0]?.settings:void 0,source:{type:"openapi",file:o},namespace:n.namespace??void 0};r.push(u)}else throw new O({message:"Spec type override not yet supported. Only OpenAPI specs are currently supported in specs override.",code:O.Code.InternalError});return r}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.allSpecs.flatMap(t=>{let r=t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,n=Array.isArray(t.absoluteFilepathToOverrides)?t.absoluteFilepathToOverrides:t.absoluteFilepathToOverrides!=null?[t.absoluteFilepathToOverrides]:[],i=t.type==="graphql"?t.absoluteFilepathToExamples:void 0;return[r,...n,...i!=null?[i]:[]]}).filter(ia)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,n=[];return t.reduce((i,o)=>{let s=o.type==="protobuf"?o.absoluteFilepathToProtobufRoot:o.absoluteFilepath;return r.has(s)||(r.add(s),i.push({type:o.type,id:PD(),absoluteFilePath:s,absoluteFilePathToOverrides:o.type==="openapi"?o.absoluteFilepathToOverrides:void 0})),i},n)}}});var ACu=h(()=>{"use strict";NPo();LDo();jPo();_Po();n6e()});var Am=h(()=>{"use strict";CYc();OAu();qPo();gCu();DDo();zDo();xVr();ACu()});var uko=b((fxI,MCu)=>{"use strict";var p_r=a_().Buffer,R7d=require("stream"),k7d=require("util");function f_r(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=p_r.alloc(0),this;if(typeof e.pipe=="function")return this.buffer=p_r.alloc(0),e.pipe(this),this;if(e.length||typeof e=="object")return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}k7d.inherits(f_r,R7d);f_r.prototype.write=function(t){this.buffer=p_r.concat([this.buffer,p_r.from(t)]),this.emit("data",t)};f_r.prototype.end=function(t){t&&this.write(t),this.emit("end",t),this.emit("close"),this.writable=!1,this.readable=!1};MCu.exports=f_r});var VCu=b((dxI,LCu)=>{"use strict";function lko(e){var t=(e/8|0)+(e%8===0?0:1);return t}var F7d={ES256:lko(256),ES384:lko(384),ES512:lko(521)};function N7d(e){var t=F7d[e];if(t)return t;throw new Error('Unknown algorithm "'+e+'"')}LCu.exports=N7d});var KCu=b((mxI,HCu)=>{"use strict";var d_r=a_().Buffer,_Cu=VCu(),m_r=128,qCu=0,j7d=32,Q7d=16,z7d=2,GCu=Q7d|j7d|qCu<<6,h_r=z7d|qCu<<6;function M7d(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function WCu(e){if(d_r.isBuffer(e))return e;if(typeof e=="string")return d_r.from(e,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function L7d(e,t){e=WCu(e);var r=_Cu(t),n=r+1,i=e.length,o=0;if(e[o++]!==GCu)throw new Error('Could not find expected "seq"');var s=e[o++];if(s===(m_r|1)&&(s=e[o++]),i-o<s)throw new Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(e[o++]!==h_r)throw new Error('Could not find expected "int" for "r"');var a=e[o++];if(i-o-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=o;if(o+=a,e[o++]!==h_r)throw new Error('Could not find expected "int" for "s"');var u=e[o++];if(i-o!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var l=o;if(o+=u,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var p=r-a,d=r-u,f=d_r.allocUnsafe(p+a+d+u);for(o=0;o<p;++o)f[o]=0;e.copy(f,o,c+Math.max(-p,0),c+a),o=r;for(var m=o;o<m+d;++o)f[o]=0;return e.copy(f,o,l+Math.max(-d,0),l+u),f=f.toString("base64"),f=M7d(f),f}function UCu(e,t,r){for(var n=0;t+n<r&&e[t+n]===0;)++n;var i=e[t+n]>=m_r;return i&&--n,n}function V7d(e,t){e=WCu(e);var r=_Cu(t),n=e.length;if(n!==r*2)throw new TypeError('"'+t+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var i=UCu(e,0,r),o=UCu(e,r,e.length),s=r-i,a=r-o,c=2+s+1+1+a,u=c<m_r,l=d_r.allocUnsafe((u?2:3)+c),p=0;return l[p++]=GCu,u?l[p++]=c:(l[p++]=m_r|1,l[p++]=c&255),l[p++]=h_r,l[p++]=s,i<0?(l[p++]=0,p+=e.copy(l,p,0,r)):p+=e.copy(l,p,i,r),l[p++]=h_r,l[p++]=a,o<0?(l[p++]=0,e.copy(l,p,r)):e.copy(l,p,r+o),l}HCu.exports={derToJose:L7d,joseToDer:V7d}});var YCu=b((hxI,JCu)=>{"use strict";var AVt=require("buffer").Buffer,pko=require("buffer").SlowBuffer;JCu.exports=g_r;function g_r(e,t){if(!AVt.isBuffer(e)||!AVt.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}g_r.install=function(){AVt.prototype.equal=pko.prototype.equal=function(t){return g_r(this,t)}};var U7d=AVt.prototype.equal,_7d=pko.prototype.equal;g_r.restore=function(){AVt.prototype.equal=U7d,pko.prototype.equal=_7d}});var hko=b((gxI,owu)=>{"use strict";var Ent=a_().Buffer,C_=require("crypto"),ZCu=KCu(),XCu=require("util"),q7d=`"%s" is not a valid algorithm.
941
941
  Supported algorithms are:
942
942
  "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,yVt="secret must be a string or buffer",bnt="key must be a string or a buffer",G7d="key must be a string, a buffer or an object",dko=typeof C_.createPublicKey=="function";dko&&(bnt+=" or a KeyObject",yVt+="or a KeyObject");function $Cu(e){if(!Ent.isBuffer(e)&&typeof e!="string"&&(!dko||typeof e!="object"||typeof e.type!="string"||typeof e.asymmetricKeyType!="string"||typeof e.export!="function"))throw rH(bnt)}function ewu(e){if(!Ent.isBuffer(e)&&typeof e!="string"&&typeof e!="object")throw rH(G7d)}function W7d(e){if(!Ent.isBuffer(e)){if(typeof e=="string")return e;if(!dko||typeof e!="object"||e.type!=="secret"||typeof e.export!="function")throw rH(yVt)}}function mko(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function twu(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function rH(e){var t=[].slice.call(arguments,1),r=XCu.format.bind(XCu,e).apply(null,t);return new TypeError(r)}function H7d(e){return Ent.isBuffer(e)||typeof e=="string"}function bVt(e){return H7d(e)||(e=JSON.stringify(e)),e}function rwu(e){return function(r,n){W7d(n),r=bVt(r);var i=C_.createHmac("sha"+e,n),o=(i.update(r),i.digest("base64"));return mko(o)}}var fko,K7d="timingSafeEqual"in C_?function(t,r){return t.byteLength!==r.byteLength?!1:C_.timingSafeEqual(t,r)}:function(t,r){return fko||(fko=YCu()),fko(t,r)};function J7d(e){return function(r,n,i){var o=rwu(e)(r,i);return K7d(Ent.from(n),Ent.from(o))}}function nwu(e){return function(r,n){ewu(n),r=bVt(r);var i=C_.createSign("RSA-SHA"+e),o=(i.update(r),i.sign(n,"base64"));return mko(o)}}function iwu(e){return function(r,n,i){$Cu(i),r=bVt(r),n=twu(n);var o=C_.createVerify("RSA-SHA"+e);return o.update(r),o.verify(i,n,"base64")}}function Y7d(e){return function(r,n){ewu(n),r=bVt(r);var i=C_.createSign("RSA-SHA"+e),o=(i.update(r),i.sign({key:n,padding:C_.constants.RSA_PKCS1_PSS_PADDING,saltLength:C_.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return mko(o)}}function X7d(e){return function(r,n,i){$Cu(i),r=bVt(r),n=twu(n);var o=C_.createVerify("RSA-SHA"+e);return o.update(r),o.verify({key:i,padding:C_.constants.RSA_PKCS1_PSS_PADDING,saltLength:C_.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Z7d(e){var t=nwu(e);return function(){var n=t.apply(null,arguments);return n=ZCu.derToJose(n,"ES"+e),n}}function $7d(e){var t=iwu(e);return function(n,i,o){i=ZCu.joseToDer(i,"ES"+e).toString("base64");var s=t(n,i,o);return s}}function eWd(){return function(){return""}}function tWd(){return function(t,r){return r===""}}owu.exports=function(t){var r={hs:rwu,rs:nwu,ps:Y7d,es:Z7d,none:eWd},n={hs:J7d,rs:iwu,ps:X7d,es:$7d,none:tWd},i=t.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw rH(q7d,t);var o=(i[1]||i[3]).toLowerCase(),s=i[2];return{sign:r[o](s),verify:n[o](s)}}});var gko=b((AxI,swu)=>{"use strict";var rWd=require("buffer").Buffer;swu.exports=function(t){return typeof t=="string"?t:typeof t=="number"||rWd.isBuffer(t)?t.toString():JSON.stringify(t)}});var fwu=b((yxI,pwu)=>{"use strict";var nWd=a_().Buffer,awu=uko(),iWd=hko(),oWd=require("stream"),cwu=gko(),Ako=require("util");function uwu(e,t){return nWd.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function sWd(e,t,r){r=r||"utf8";var n=uwu(cwu(e),"binary"),i=uwu(cwu(t),r);return Ako.format("%s.%s",n,i)}function lwu(e){var t=e.header,r=e.payload,n=e.secret||e.privateKey,i=e.encoding,o=iWd(t.alg),s=sWd(t,r,i),a=o.sign(s,n);return Ako.format("%s.%s",s,a)}function A_r(e){var t=e.secret;if(t=t??e.privateKey,t=t??e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new awu(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new awu(e.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Ako.inherits(A_r,oWd);A_r.prototype.sign=function(){try{var t=lwu({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",t),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};A_r.sign=lwu;pwu.exports=A_r});var vwu=b((bxI,Iwu)=>{"use strict";var mwu=a_().Buffer,dwu=uko(),aWd=hko(),cWd=require("stream"),hwu=gko(),uWd=require("util"),lWd=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function pWd(e){return Object.prototype.toString.call(e)==="[object Object]"}function fWd(e){if(pWd(e))return e;try{return JSON.parse(e)}catch{return}}function gwu(e){var t=e.split(".",1)[0];return fWd(mwu.from(t,"base64").toString("binary"))}function dWd(e){return e.split(".",2).join(".")}function Awu(e){return e.split(".")[2]}function mWd(e,t){t=t||"utf8";var r=e.split(".")[1];return mwu.from(r,"base64").toString(t)}function ywu(e){return lWd.test(e)&&!!gwu(e)}function bwu(e,t,r){if(!t){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}e=hwu(e);var i=Awu(e),o=dWd(e),s=aWd(t);return s.verify(o,i,r)}function Ewu(e,t){if(t=t||{},e=hwu(e),!ywu(e))return null;var r=gwu(e);if(!r)return null;var n=mWd(e);return(r.typ==="JWT"||t.json)&&(n=JSON.parse(n,t.encoding)),{header:r,payload:n,signature:Awu(e)}}function Int(e){e=e||{};var t=e.secret;if(t=t??e.publicKey,t=t??e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new dwu(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new dwu(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}uWd.inherits(Int,cWd);Int.prototype.verify=function(){try{var t=bwu(this.signature.buffer,this.algorithm,this.key.buffer),r=Ewu(this.signature.buffer,this.encoding);return this.emit("done",t,r),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Int.decode=Ewu;Int.isValid=ywu;Int.verify=bwu;Iwu.exports=Int});var b_r=b(yve=>{"use strict";var xwu=fwu(),y_r=vwu(),hWd=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];yve.ALGORITHMS=hWd;yve.sign=xwu.sign;yve.verify=y_r.verify;yve.decode=y_r.decode;yve.isValid=y_r.isValid;yve.createSign=function(t){return new xwu(t)};yve.createVerify=function(t){return new y_r(t)}});var yko=b((IxI,Cwu)=>{"use strict";var gWd=b_r();Cwu.exports=function(e,t){t=t||{};var r=gWd.decode(e,t);if(!r)return null;var n=r.payload;if(typeof n=="string")try{var i=JSON.parse(n);i!==null&&typeof i=="object"&&(n=i)}catch{}return t.complete===!0?{header:r.header,payload:n,signature:r.signature}:n}});var EVt=b((vxI,wwu)=>{"use strict";var E_r=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=e,t&&(this.inner=t)};E_r.prototype=Object.create(Error.prototype);E_r.prototype.constructor=E_r;wwu.exports=E_r});var bko=b((xxI,Twu)=>{"use strict";var Swu=EVt(),I_r=function(e,t){Swu.call(this,e),this.name="NotBeforeError",this.date=t};I_r.prototype=Object.create(Swu.prototype);I_r.prototype.constructor=I_r;Twu.exports=I_r});var Eko=b((CxI,Bwu)=>{"use strict";var Owu=EVt(),v_r=function(e,t){Owu.call(this,e),this.name="TokenExpiredError",this.expiredAt=t};v_r.prototype=Object.create(Owu.prototype);v_r.prototype.constructor=v_r;Bwu.exports=v_r});var Iko=b((wxI,Pwu)=>{"use strict";var AWd=Fer();Pwu.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e=="string"){var n=AWd(e);return typeof n>"u"?void 0:Math.floor(r+n/1e3)}else return typeof e=="number"?r+e:void 0}});var Rwu=b((SxI,Dwu)=>{"use strict";var yWd=fw();Dwu.exports=yWd.satisfies(process.version,">=15.7.0")});var Fwu=b((TxI,kwu)=>{"use strict";var bWd=fw();kwu.exports=bWd.satisfies(process.version,">=16.9.0")});var vko=b((OxI,Nwu)=>{"use strict";var EWd=Rwu(),IWd=Fwu(),vWd={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},xWd={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Nwu.exports=function(e,t){if(!e||!t)return;let r=t.asymmetricKeyType;if(!r)return;let n=vWd[r];if(!n)throw new Error(`Unknown key type "${r}".`);if(!n.includes(e))throw new Error(`"alg" parameter for "${r}" key type must be one of: ${n.join(", ")}.`);if(EWd)switch(r){case"ec":let i=t.asymmetricKeyDetails.namedCurve,o=xWd[e];if(i!==o)throw new Error(`"alg" parameter "${e}" requires curve "${o}".`);break;case"rsa-pss":if(IWd){let s=parseInt(e.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:c,saltLength:u}=t.asymmetricKeyDetails;if(a!==`sha${s}`||c!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(u!==void 0&&u>s>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}});var xko=b((BxI,jwu)=>{"use strict";var CWd=fw();jwu.exports=CWd.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Mwu=b((PxI,zwu)=>{"use strict";var xy=EVt(),wWd=bko(),Qwu=Eko(),SWd=yko(),TWd=Iko(),OWd=vko(),BWd=xko(),PWd=b_r(),{KeyObject:DWd,createSecretKey:RWd,createPublicKey:kWd}=require("crypto"),Cko=["RS256","RS384","RS512"],FWd=["ES256","ES384","ES512"],wko=["RS256","RS384","RS512"],NWd=["HS256","HS384","HS512"];BWd&&(Cko.splice(Cko.length,0,"PS256","PS384","PS512"),wko.splice(wko.length,0,"PS256","PS384","PS512"));zwu.exports=function(e,t,r,n){typeof r=="function"&&!n&&(n=r,r={}),r||(r={}),r=Object.assign({},r);let i;if(n?i=n:i=function(l,p){if(l)throw l;return p},r.clockTimestamp&&typeof r.clockTimestamp!="number")return i(new xy("clockTimestamp must be a number"));if(r.nonce!==void 0&&(typeof r.nonce!="string"||r.nonce.trim()===""))return i(new xy("nonce must be a non-empty string"));if(r.allowInvalidAsymmetricKeyTypes!==void 0&&typeof r.allowInvalidAsymmetricKeyTypes!="boolean")return i(new xy("allowInvalidAsymmetricKeyTypes must be a boolean"));let o=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return i(new xy("jwt must be provided"));if(typeof e!="string")return i(new xy("jwt must be a string"));let s=e.split(".");if(s.length!==3)return i(new xy("jwt malformed"));let a;try{a=SWd(e,{complete:!0})}catch(l){return i(l)}if(!a)return i(new xy("invalid token"));let c=a.header,u;if(typeof t=="function"){if(!n)return i(new xy("verify must be called asynchronous if secret or public key is provided as a callback"));u=t}else u=function(l,p){return p(null,t)};return u(c,function(l,p){if(l)return i(new xy("error in secret or public key callback: "+l.message));let d=s[2].trim()!=="";if(!d&&p)return i(new xy("jwt signature is required"));if(d&&!p)return i(new xy("secret or public key must be provided"));if(!d&&!r.algorithms)return i(new xy('please specify "none" in "algorithms" to verify unsigned tokens'));if(p!=null&&!(p instanceof DWd))try{p=kWd(p)}catch{try{p=RWd(typeof p=="string"?Buffer.from(p):p)}catch{return i(new xy("secretOrPublicKey is not valid key material"))}}if(r.algorithms||(p.type==="secret"?r.algorithms=NWd:["rsa","rsa-pss"].includes(p.asymmetricKeyType)?r.algorithms=wko:p.asymmetricKeyType==="ec"?r.algorithms=FWd:r.algorithms=Cko),r.algorithms.indexOf(a.header.alg)===-1)return i(new xy("invalid algorithm"));if(c.alg.startsWith("HS")&&p.type!=="secret")return i(new xy(`secretOrPublicKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)&&p.type!=="public")return i(new xy(`secretOrPublicKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInvalidAsymmetricKeyTypes)try{OWd(c.alg,p)}catch(g){return i(g)}let f;try{f=PWd.verify(e,a.header.alg,p)}catch(g){return i(g)}if(!f)return i(new xy("invalid signature"));let m=a.payload;if(typeof m.nbf<"u"&&!r.ignoreNotBefore){if(typeof m.nbf!="number")return i(new xy("invalid nbf value"));if(m.nbf>o+(r.clockTolerance||0))return i(new wWd("jwt not active",new Date(m.nbf*1e3)))}if(typeof m.exp<"u"&&!r.ignoreExpiration){if(typeof m.exp!="number")return i(new xy("invalid exp value"));if(o>=m.exp+(r.clockTolerance||0))return i(new Qwu("jwt expired",new Date(m.exp*1e3)))}if(r.audience){let g=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(m.aud)?m.aud:[m.aud]).some(function(E){return g.some(function(x){return x instanceof RegExp?x.test(E):x===E})}))return i(new xy("jwt audience invalid. expected: "+g.join(" or ")))}if(r.issuer&&(typeof r.issuer=="string"&&m.iss!==r.issuer||Array.isArray(r.issuer)&&r.issuer.indexOf(m.iss)===-1))return i(new xy("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&m.sub!==r.subject)return i(new xy("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&m.jti!==r.jwtid)return i(new xy("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&m.nonce!==r.nonce)return i(new xy("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if(typeof m.iat!="number")return i(new xy("iat required when maxAge is specified"));let g=TWd(r.maxAge,m.iat);if(typeof g>"u")return i(new xy('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=g+(r.clockTolerance||0))return i(new Qwu("maxAge exceeded",new Date(g*1e3)))}if(r.complete===!0){let g=a.signature;return i(null,{header:c,payload:m,signature:g})}return i(null,m)})}});var Gwu=b((DxI,qwu)=>{"use strict";var Lwu=1/0,Uwu=9007199254740991,jWd=17976931348623157e292,Vwu=NaN,QWd="[object Arguments]",zWd="[object Function]",MWd="[object GeneratorFunction]",LWd="[object String]",VWd="[object Symbol]",UWd=/^\s+|\s+$/g,_Wd=/^[-+]0x[0-9a-f]+$/i,qWd=/^0b[01]+$/i,GWd=/^0o[0-7]+$/i,WWd=/^(?:0|[1-9]\d*)$/,HWd=parseInt;function KWd(e,t){for(var r=-1,n=e?e.length:0,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}function JWd(e,t,r,n){for(var i=e.length,o=r+(n?1:-1);n?o--:++o<i;)if(t(e[o],o,e))return o;return-1}function YWd(e,t,r){if(t!==t)return JWd(e,XWd,r);for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1}function XWd(e){return e!==e}function ZWd(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function $Wd(e,t){return KWd(t,function(r){return e[r]})}function eHd(e,t){return function(r){return e(t(r))}}var x_r=Object.prototype,Tko=x_r.hasOwnProperty,C_r=x_r.toString,tHd=x_r.propertyIsEnumerable,rHd=eHd(Object.keys,Object),nHd=Math.max;function iHd(e,t){var r=_wu(e)||uHd(e)?ZWd(e.length,String):[],n=r.length,i=!!n;for(var o in e)(t||Tko.call(e,o))&&!(i&&(o=="length"||sHd(o,n)))&&r.push(o);return r}function oHd(e){if(!aHd(e))return rHd(e);var t=[];for(var r in Object(e))Tko.call(e,r)&&r!="constructor"&&t.push(r);return t}function sHd(e,t){return t=t??Uwu,!!t&&(typeof e=="number"||WWd.test(e))&&e>-1&&e%1==0&&e<t}function aHd(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||x_r;return e===r}function cHd(e,t,r,n){e=Oko(e)?e:bHd(e),r=r&&!n?gHd(r):0;var i=e.length;return r<0&&(r=nHd(i+r,0)),dHd(e)?r<=i&&e.indexOf(t,r)>-1:!!i&&YWd(e,t,r)>-1}function uHd(e){return lHd(e)&&Tko.call(e,"callee")&&(!tHd.call(e,"callee")||C_r.call(e)==QWd)}var _wu=Array.isArray;function Oko(e){return e!=null&&fHd(e.length)&&!pHd(e)}function lHd(e){return Bko(e)&&Oko(e)}function pHd(e){var t=Sko(e)?C_r.call(e):"";return t==zWd||t==MWd}function fHd(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Uwu}function Sko(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Bko(e){return!!e&&typeof e=="object"}function dHd(e){return typeof e=="string"||!_wu(e)&&Bko(e)&&C_r.call(e)==LWd}function mHd(e){return typeof e=="symbol"||Bko(e)&&C_r.call(e)==VWd}function hHd(e){if(!e)return e===0?e:0;if(e=AHd(e),e===Lwu||e===-Lwu){var t=e<0?-1:1;return t*jWd}return e===e?e:0}function gHd(e){var t=hHd(e),r=t%1;return t===t?r?t-r:t:0}function AHd(e){if(typeof e=="number")return e;if(mHd(e))return Vwu;if(Sko(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Sko(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(UWd,"");var r=qWd.test(e);return r||GWd.test(e)?HWd(e.slice(2),r?2:8):_Wd.test(e)?Vwu:+e}function yHd(e){return Oko(e)?iHd(e):oHd(e)}function bHd(e){return e?$Wd(e,yHd(e)):[]}qwu.exports=cHd});var Hwu=b((RxI,Wwu)=>{"use strict";var EHd="[object Boolean]",IHd=Object.prototype,vHd=IHd.toString;function xHd(e){return e===!0||e===!1||CHd(e)&&vHd.call(e)==EHd}function CHd(e){return!!e&&typeof e=="object"}Wwu.exports=xHd});var Zwu=b((kxI,Xwu)=>{"use strict";var Kwu=1/0,wHd=17976931348623157e292,Jwu=NaN,SHd="[object Symbol]",THd=/^\s+|\s+$/g,OHd=/^[-+]0x[0-9a-f]+$/i,BHd=/^0b[01]+$/i,PHd=/^0o[0-7]+$/i,DHd=parseInt,RHd=Object.prototype,kHd=RHd.toString;function FHd(e){return typeof e=="number"&&e==zHd(e)}function Ywu(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function NHd(e){return!!e&&typeof e=="object"}function jHd(e){return typeof e=="symbol"||NHd(e)&&kHd.call(e)==SHd}function QHd(e){if(!e)return e===0?e:0;if(e=MHd(e),e===Kwu||e===-Kwu){var t=e<0?-1:1;return t*wHd}return e===e?e:0}function zHd(e){var t=QHd(e),r=t%1;return t===t?r?t-r:t:0}function MHd(e){if(typeof e=="number")return e;if(jHd(e))return Jwu;if(Ywu(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Ywu(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(THd,"");var r=BHd.test(e);return r||PHd.test(e)?DHd(e.slice(2),r?2:8):OHd.test(e)?Jwu:+e}Xwu.exports=FHd});var eSu=b((FxI,$wu)=>{"use strict";var LHd="[object Number]",VHd=Object.prototype,UHd=VHd.toString;function _Hd(e){return!!e&&typeof e=="object"}function qHd(e){return typeof e=="number"||_Hd(e)&&UHd.call(e)==LHd}$wu.exports=qHd});var iSu=b((NxI,nSu)=>{"use strict";var GHd="[object Object]";function WHd(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}function HHd(e,t){return function(r){return e(t(r))}}var KHd=Function.prototype,tSu=Object.prototype,rSu=KHd.toString,JHd=tSu.hasOwnProperty,YHd=rSu.call(Object),XHd=tSu.toString,ZHd=HHd(Object.getPrototypeOf,Object);function $Hd(e){return!!e&&typeof e=="object"}function eKd(e){if(!$Hd(e)||XHd.call(e)!=GHd||WHd(e))return!1;var t=ZHd(e);if(t===null)return!0;var r=JHd.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&rSu.call(r)==YHd}nSu.exports=eKd});var sSu=b((jxI,oSu)=>{"use strict";var tKd="[object String]",rKd=Object.prototype,nKd=rKd.toString,iKd=Array.isArray;function oKd(e){return!!e&&typeof e=="object"}function sKd(e){return typeof e=="string"||!iKd(e)&&oKd(e)&&nKd.call(e)==tKd}oSu.exports=sKd});var pSu=b((QxI,lSu)=>{"use strict";var aKd="Expected a function",aSu=1/0,cKd=17976931348623157e292,cSu=NaN,uKd="[object Symbol]",lKd=/^\s+|\s+$/g,pKd=/^[-+]0x[0-9a-f]+$/i,fKd=/^0b[01]+$/i,dKd=/^0o[0-7]+$/i,mKd=parseInt,hKd=Object.prototype,gKd=hKd.toString;function AKd(e,t){var r;if(typeof t!="function")throw new TypeError(aKd);return e=vKd(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function yKd(e){return AKd(2,e)}function uSu(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function bKd(e){return!!e&&typeof e=="object"}function EKd(e){return typeof e=="symbol"||bKd(e)&&gKd.call(e)==uKd}function IKd(e){if(!e)return e===0?e:0;if(e=xKd(e),e===aSu||e===-aSu){var t=e<0?-1:1;return t*cKd}return e===e?e:0}function vKd(e){var t=IKd(e),r=t%1;return t===t?r?t-r:t:0}function xKd(e){if(typeof e=="number")return e;if(EKd(e))return cSu;if(uSu(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=uSu(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(lKd,"");var r=fKd.test(e);return r||dKd.test(e)?mKd(e.slice(2),r?2:8):pKd.test(e)?cSu:+e}lSu.exports=yKd});var ESu=b((zxI,bSu)=>{"use strict";var fSu=Iko(),CKd=xko(),wKd=vko(),dSu=b_r(),SKd=Gwu(),w_r=Hwu(),mSu=Zwu(),Pko=eSu(),gSu=iSu(),bve=sSu(),TKd=pSu(),{KeyObject:OKd,createSecretKey:BKd,createPrivateKey:PKd}=require("crypto"),ASu=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];CKd&&ASu.splice(3,0,"PS256","PS384","PS512");var DKd={expiresIn:{isValid:function(e){return mSu(e)||bve(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return mSu(e)||bve(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return bve(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:SKd.bind(null,ASu),message:'"algorithm" must be a valid string enum value'},header:{isValid:gSu,message:'"header" must be an object'},encoding:{isValid:bve,message:'"encoding" must be a string'},issuer:{isValid:bve,message:'"issuer" must be a string'},subject:{isValid:bve,message:'"subject" must be a string'},jwtid:{isValid:bve,message:'"jwtid" must be a string'},noTimestamp:{isValid:w_r,message:'"noTimestamp" must be a boolean'},keyid:{isValid:bve,message:'"keyid" must be a string'},mutatePayload:{isValid:w_r,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:w_r,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:w_r,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},RKd={iat:{isValid:Pko,message:'"iat" should be a number of seconds'},exp:{isValid:Pko,message:'"exp" should be a number of seconds'},nbf:{isValid:Pko,message:'"nbf" should be a number of seconds'}};function ySu(e,t,r,n){if(!gSu(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach(function(i){let o=e[i];if(!o){if(!t)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!o.isValid(r[i]))throw new Error(o.message)})}function kKd(e){return ySu(DKd,!1,e,"options")}function FKd(e){return ySu(RKd,!0,e,"payload")}var hSu={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},NKd=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];bSu.exports=function(e,t,r,n){typeof r=="function"?(n=r,r={}):r=r||{};let i=typeof e=="object"&&!Buffer.isBuffer(e),o=Object.assign({alg:r.algorithm||"HS256",typ:i?"JWT":void 0,kid:r.keyid},r.header);function s(u){if(n)return n(u);throw u}if(!t&&r.algorithm!=="none")return s(new Error("secretOrPrivateKey must have a value"));if(t!=null&&!(t instanceof OKd))try{t=PKd(t)}catch{try{t=BKd(typeof t=="string"?Buffer.from(t):t)}catch{return s(new Error("secretOrPrivateKey is not valid key material"))}}if(o.alg.startsWith("HS")&&t.type!=="secret")return s(new Error(`secretOrPrivateKey must be a symmetric key when using ${o.alg}`));if(/^(?:RS|PS|ES)/.test(o.alg)){if(t.type!=="private")return s(new Error(`secretOrPrivateKey must be an asymmetric key when using ${o.alg}`));if(!r.allowInsecureKeySizes&&!o.alg.startsWith("ES")&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return s(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`))}if(typeof e>"u")return s(new Error("payload is required"));if(i){try{FKd(e)}catch(u){return s(u)}r.mutatePayload||(e=Object.assign({},e))}else{let u=NKd.filter(function(l){return typeof r[l]<"u"});if(u.length>0)return s(new Error("invalid "+u.join(",")+" option for "+typeof e+" payload"))}if(typeof e.exp<"u"&&typeof r.expiresIn<"u")return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof e.nbf<"u"&&typeof r.notBefore<"u")return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{kKd(r)}catch(u){return s(u)}if(!r.allowInvalidAsymmetricKeyTypes)try{wKd(o.alg,t)}catch(u){return s(u)}let a=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:i&&(e.iat=a),typeof r.notBefore<"u"){try{e.nbf=fSu(r.notBefore,a)}catch(u){return s(u)}if(typeof e.nbf>"u")return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof r.expiresIn<"u"&&typeof e=="object"){try{e.exp=fSu(r.expiresIn,a)}catch(u){return s(u)}if(typeof e.exp>"u")return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(hSu).forEach(function(u){let l=hSu[u];if(typeof r[u]<"u"){if(typeof e[l]<"u")return s(new Error('Bad "options.'+u+'" option. The payload already has an "'+l+'" property.'));e[l]=r[u]}});let c=r.encoding||"utf8";if(typeof n=="function")n=n&&TKd(n),dSu.createSign({header:o,privateKey:t,payload:e,encoding:c}).once("error",n).once("done",function(u){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`));n(null,u)});else{let u=dSu.sign({header:o,payload:e,secret:t,encoding:c});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`);return u}}});var S_r=b((MxI,ISu)=>{"use strict";ISu.exports={decode:yko(),verify:Mwu(),sign:ESu(),JsonWebTokenError:EVt(),NotBeforeError:bko(),TokenExpiredError:Eko()}});var kko=b(Rko=>{"use strict";Object.defineProperty(Rko,"__esModule",{value:!0});var jKd=require("crypto"),QKd=(e,t)=>(0,jKd.createHash)(e).update(t).digest();Rko.default=QKd});var QI=b(Lw=>{"use strict";Object.defineProperty(Lw,"__esModule",{value:!0});Lw.concatKdf=Lw.lengthAndInput=Lw.uint32be=Lw.uint64be=Lw.p2s=Lw.concat=Lw.decoder=Lw.encoder=void 0;var zKd=kko();Lw.encoder=new TextEncoder;Lw.decoder=new TextDecoder;var T_r=2**32;function Nko(...e){let t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r}Lw.concat=Nko;function MKd(e,t){return Nko(Lw.encoder.encode(e),new Uint8Array([0]),t)}Lw.p2s=MKd;function Fko(e,t,r){if(t<0||t>=T_r)throw new RangeError(`value must be >= 0 and <= ${T_r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function LKd(e){let t=Math.floor(e/T_r),r=e%T_r,n=new Uint8Array(8);return Fko(n,t,0),Fko(n,r,4),n}Lw.uint64be=LKd;function jko(e){let t=new Uint8Array(4);return Fko(t,e),t}Lw.uint32be=jko;function VKd(e){return Nko(jko(e.length),e)}Lw.lengthAndInput=VKd;async function UKd(e,t,r){let n=Math.ceil((t>>3)/32),i=new Uint8Array(n*32);for(let o=0;o<n;o++){let s=new Uint8Array(4+e.length+r.length);s.set(jko(o+1)),s.set(e,4),s.set(r,4+e.length),i.set(await(0,zKd.default)("sha256",s),o*32)}return i.slice(0,t>>3)}Lw.concatKdf=UKd});var kD=b(nH=>{"use strict";Object.defineProperty(nH,"__esModule",{value:!0});nH.decode=nH.encode=nH.encodeBase64=nH.decodeBase64=void 0;var vnt=require("buffer"),_Kd=QI(),CSu;function qKd(e){let t=e;return t instanceof Uint8Array&&(t=_Kd.decoder.decode(t)),t}vnt.Buffer.isEncoding("base64url")?nH.encode=CSu=e=>vnt.Buffer.from(e).toString("base64url"):nH.encode=CSu=e=>vnt.Buffer.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var GKd=e=>vnt.Buffer.from(e,"base64");nH.decodeBase64=GKd;var WKd=e=>vnt.Buffer.from(e).toString("base64");nH.encodeBase64=WKd;var HKd=e=>vnt.Buffer.from(qKd(e),"base64");nH.decode=HKd});var wl=b(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});jd.JWSSignatureVerificationFailed=jd.JWKSTimeout=jd.JWKSMultipleMatchingKeys=jd.JWKSNoMatchingKey=jd.JWKSInvalid=jd.JWKInvalid=jd.JWTInvalid=jd.JWSInvalid=jd.JWEInvalid=jd.JWEDecompressionFailed=jd.JWEDecryptionFailed=jd.JOSENotSupported=jd.JOSEAlgNotAllowed=jd.JWTExpired=jd.JWTClaimValidationFailed=jd.JOSEError=void 0;var U1=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};jd.JOSEError=U1;var Qko=class extends U1{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}};jd.JWTClaimValidationFailed=Qko;var zko=class extends U1{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}};jd.JWTExpired=zko;var Mko=class extends U1{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}};jd.JOSEAlgNotAllowed=Mko;var Lko=class extends U1{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};jd.JOSENotSupported=Lko;var Vko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}};jd.JWEDecryptionFailed=Vko;var Uko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}};jd.JWEDecompressionFailed=Uko;var _ko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}};jd.JWEInvalid=_ko;var qko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}};jd.JWSInvalid=qko;var Gko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};jd.JWTInvalid=Gko;var Wko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}};jd.JWKInvalid=Wko;var Hko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}};jd.JWKSInvalid=Hko;var Kko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}};jd.JWKSNoMatchingKey=Kko;var Jko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};jd.JWKSMultipleMatchingKeys=Jko;var Yko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}};jd.JWKSTimeout=Yko;var Xko=class extends U1{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};jd.JWSSignatureVerificationFailed=Xko});var IVt=b(O_r=>{"use strict";Object.defineProperty(O_r,"__esModule",{value:!0});O_r.default=void 0;var KKd=require("crypto");Object.defineProperty(O_r,"default",{enumerable:!0,get:function(){return KKd.randomFillSync}})});var B_r=b(vVt=>{"use strict";Object.defineProperty(vVt,"__esModule",{value:!0});vVt.bitLength=void 0;var JKd=wl(),YKd=IVt();function wSu(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new JKd.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}vVt.bitLength=wSu;vVt.default=e=>(0,YKd.default)(new Uint8Array(wSu(e)>>3))});var $ko=b(Zko=>{"use strict";Object.defineProperty(Zko,"__esModule",{value:!0});var XKd=wl(),ZKd=B_r(),$Kd=(e,t)=>{if(t.length<<3!==(0,ZKd.bitLength)(e))throw new XKd.JWEInvalid("Invalid Initialization Vector length")};Zko.default=$Kd});var w_=b(eFo=>{"use strict";Object.defineProperty(eFo,"__esModule",{value:!0});var eJd=require("crypto"),SSu=require("util");eFo.default=SSu.types.isKeyObject?e=>SSu.types.isKeyObject(e):e=>e!=null&&e instanceof eJd.KeyObject});var nFo=b(rFo=>{"use strict";Object.defineProperty(rFo,"__esModule",{value:!0});var tFo=wl(),tJd=w_(),rJd=(e,t)=>{let r;switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new tFo.JOSENotSupported(`Content Encryption Algorithm ${e} is not supported either by JOSE or your javascript runtime`)}if(t instanceof Uint8Array){let n=t.byteLength<<3;if(n!==r)throw new tFo.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${n} bits`);return}if((0,tJd.default)(t)&&t.type==="secret"){let n=t.symmetricKeySize<<3;if(n!==r)throw new tFo.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${n} bits`);return}throw new TypeError("Invalid Content Encryption Key type")};rFo.default=rJd});var TSu=b(iFo=>{"use strict";Object.defineProperty(iFo,"__esModule",{value:!0});var nJd=require("crypto"),iJd=nJd.timingSafeEqual;iFo.default=iJd});var sFo=b(oFo=>{"use strict";Object.defineProperty(oFo,"__esModule",{value:!0});var oJd=require("crypto"),OSu=QI();function sJd(e,t,r,n,i,o){let s=(0,OSu.concat)(e,t,r,(0,OSu.uint64be)(e.length<<3)),a=(0,oJd.createHmac)(`sha${n}`,i);return a.update(s),a.digest().slice(0,o>>3)}oFo.default=sJd});var S_=b(xVt=>{"use strict";Object.defineProperty(xVt,"__esModule",{value:!0});xVt.isCryptoKey=void 0;var aJd=require("crypto"),BSu=require("util"),cJd=aJd.webcrypto;xVt.default=cJd;xVt.isCryptoKey=BSu.types.isCryptoKey?e=>BSu.types.isCryptoKey(e):e=>!1});var Ive=b(xnt=>{"use strict";Object.defineProperty(xnt,"__esModule",{value:!0});xnt.checkEncCryptoKey=xnt.checkSigCryptoKey=void 0;function wB(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Eve(e,t){return e.name===t}function P_r(e){return parseInt(e.name.slice(4),10)}function uJd(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function PSu(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function lJd(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Eve(e.algorithm,"HMAC"))throw wB("HMAC");let n=parseInt(t.slice(2),10);if(P_r(e.algorithm.hash)!==n)throw wB(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Eve(e.algorithm,"RSASSA-PKCS1-v1_5"))throw wB("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(P_r(e.algorithm.hash)!==n)throw wB(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Eve(e.algorithm,"RSA-PSS"))throw wB("RSA-PSS");let n=parseInt(t.slice(2),10);if(P_r(e.algorithm.hash)!==n)throw wB(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw wB("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Eve(e.algorithm,"ECDSA"))throw wB("ECDSA");let n=uJd(t);if(e.algorithm.namedCurve!==n)throw wB(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}PSu(e,r)}xnt.checkSigCryptoKey=lJd;function pJd(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Eve(e.algorithm,"AES-GCM"))throw wB("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wB(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Eve(e.algorithm,"AES-KW"))throw wB("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wB(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw wB("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Eve(e.algorithm,"PBKDF2"))throw wB("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Eve(e.algorithm,"RSA-OAEP"))throw wB("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(P_r(e.algorithm.hash)!==n)throw wB(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}PSu(e,r)}xnt.checkEncCryptoKey=pJd});var T_=b(CVt=>{"use strict";Object.defineProperty(CVt,"__esModule",{value:!0});CVt.withAlg=void 0;function DSu(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}CVt.default=(e,...t)=>DSu("Key must be ",e,...t);function fJd(e,t,...r){return DSu(`Key for the ${e} algorithm must be `,t,...r)}CVt.withAlg=fJd});var D_r=b(cFo=>{"use strict";Object.defineProperty(cFo,"__esModule",{value:!0});var dJd=require("crypto"),aFo;cFo.default=e=>(aFo||(aFo=new Set((0,dJd.getCiphers)())),aFo.has(e))});var O_=b(wVt=>{"use strict";Object.defineProperty(wVt,"__esModule",{value:!0});wVt.types=void 0;var R_r=S_(),mJd=w_();wVt.default=e=>(0,mJd.default)(e)||(0,R_r.isCryptoKey)(e);var RSu=["KeyObject"];wVt.types=RSu;(globalThis.CryptoKey||!(R_r.default===null||R_r.default===void 0)&&R_r.default.CryptoKey)&&RSu.push("CryptoKey")});var pFo=b(lFo=>{"use strict";Object.defineProperty(lFo,"__esModule",{value:!0});var uFo=require("crypto"),hJd=$ko(),gJd=nFo(),AJd=QI(),Cnt=wl(),yJd=TSu(),bJd=sFo(),EJd=S_(),IJd=Ive(),kSu=w_(),vJd=T_(),FSu=D_r(),xJd=O_();function CJd(e,t,r,n,i,o){let s=parseInt(e.slice(1,4),10);(0,kSu.default)(t)&&(t=t.export());let a=t.subarray(s>>3),c=t.subarray(0,s>>3),u=parseInt(e.slice(-3),10),l=`aes-${s}-cbc`;if(!(0,FSu.default)(l))throw new Cnt.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let p=(0,bJd.default)(o,n,r,u,c,s),d;try{d=(0,yJd.default)(i,p)}catch{}if(!d)throw new Cnt.JWEDecryptionFailed;let f;try{let m=(0,uFo.createDecipheriv)(l,a,n);f=(0,AJd.concat)(m.update(r),m.final())}catch{}if(!f)throw new Cnt.JWEDecryptionFailed;return f}function wJd(e,t,r,n,i,o){let a=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,FSu.default)(a))throw new Cnt.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);try{let c=(0,uFo.createDecipheriv)(a,t,n,{authTagLength:16});c.setAuthTag(i),o.byteLength&&c.setAAD(o,{plaintextLength:r.length});let u=c.update(r);return c.final(),u}catch{throw new Cnt.JWEDecryptionFailed}}var SJd=(e,t,r,n,i,o)=>{let s;if((0,EJd.isCryptoKey)(t))(0,IJd.checkEncCryptoKey)(t,e,"decrypt"),s=uFo.KeyObject.from(t);else if(t instanceof Uint8Array||(0,kSu.default)(t))s=t;else throw new TypeError((0,vJd.default)(t,...xJd.types,"Uint8Array"));switch((0,gJd.default)(e,s),(0,hJd.default)(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return CJd(e,s,r,n,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return wJd(e,s,r,n,i,o);default:throw new Cnt.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};lFo.default=SJd});var fFo=b(wnt=>{"use strict";Object.defineProperty(wnt,"__esModule",{value:!0});wnt.deflate=wnt.inflate=void 0;var NSu=require("util"),jSu=require("zlib"),TJd=wl(),OJd=(0,NSu.promisify)(jSu.inflateRaw),BJd=(0,NSu.promisify)(jSu.deflateRaw),PJd=e=>OJd(e,{maxOutputLength:25e4}).catch(()=>{throw new TJd.JWEDecompressionFailed});wnt.inflate=PJd;var DJd=e=>BJd(e);wnt.deflate=DJd});var Snt=b(dFo=>{"use strict";Object.defineProperty(dFo,"__esModule",{value:!0});var RJd=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let o of i){if(r.has(o))return!1;r.add(o)}}return!0};dFo.default=RJd});var JQ=b(mFo=>{"use strict";Object.defineProperty(mFo,"__esModule",{value:!0});function kJd(e){return typeof e=="object"&&e!==null}function FJd(e){if(!kJd(e)||Object.prototype.toString.call(e)!=="[object Object]")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}mFo.default=FJd});var F_r=b(Tnt=>{"use strict";Object.defineProperty(Tnt,"__esModule",{value:!0});Tnt.unwrap=Tnt.wrap=void 0;var QSu=require("buffer"),k_r=require("crypto"),zSu=wl(),MSu=QI(),NJd=S_(),jJd=Ive(),QJd=w_(),zJd=T_(),LSu=D_r(),MJd=O_();function VSu(e,t){if(e.symmetricKeySize<<3!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function USu(e,t,r){if((0,QJd.default)(e))return e;if(e instanceof Uint8Array)return(0,k_r.createSecretKey)(e);if((0,NJd.isCryptoKey)(e))return(0,jJd.checkEncCryptoKey)(e,t,r),k_r.KeyObject.from(e);throw new TypeError((0,zJd.default)(e,...MJd.types,"Uint8Array"))}var LJd=(e,t,r)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,LSu.default)(i))throw new zSu.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=USu(t,e,"wrapKey");VSu(o,e);let s=(0,k_r.createCipheriv)(i,o,QSu.Buffer.alloc(8,166));return(0,MSu.concat)(s.update(r),s.final())};Tnt.wrap=LJd;var VJd=(e,t,r)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,LSu.default)(i))throw new zSu.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=USu(t,e,"unwrapKey");VSu(o,e);let s=(0,k_r.createDecipheriv)(i,o,QSu.Buffer.alloc(8,166));return(0,MSu.concat)(s.update(r),s.final())};Tnt.unwrap=VJd});var SVt=b(iH=>{"use strict";Object.defineProperty(iH,"__esModule",{value:!0});iH.setCurve=iH.weakMap=void 0;var N_r=require("buffer"),_Su=require("crypto"),qSu=wl(),UJd=S_(),_Jd=w_(),qJd=T_(),GJd=O_(),WJd=N_r.Buffer.from([42,134,72,206,61,3,1,7]),HJd=N_r.Buffer.from([43,129,4,0,34]),KJd=N_r.Buffer.from([43,129,4,0,35]),JJd=N_r.Buffer.from([43,129,4,0,10]);iH.weakMap=new WeakMap;var YJd=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new qSu.JOSENotSupported("Unsupported key curve for this operation")}},GSu=(e,t)=>{var r;let n;if((0,UJd.isCryptoKey)(e))n=_Su.KeyObject.from(e);else if((0,_Jd.default)(e))n=e;else throw new TypeError((0,qJd.default)(e,...GJd.types));if(n.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(n.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${n.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${n.asymmetricKeyType.slice(1)}`;case"ec":{if(iH.weakMap.has(n))return iH.weakMap.get(n);let i=(r=n.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!i&&n.type==="private")i=GSu((0,_Su.createPublicKey)(n),!0);else if(!i){let s=n.export({format:"der",type:"spki"}),a=s[1]<128?14:15,c=s[a],u=s.slice(a+1,a+1+c);if(u.equals(WJd))i="prime256v1";else if(u.equals(HJd))i="secp384r1";else if(u.equals(KJd))i="secp521r1";else if(u.equals(JJd))i="secp256k1";else throw new qSu.JOSENotSupported("Unsupported key curve for this operation")}if(t)return i;let o=YJd(i);return iH.weakMap.set(n,o),o}default:throw new TypeError("Invalid asymmetric key type for this operation")}};function XJd(e,t){iH.weakMap.set(e,t)}iH.setCurve=XJd;iH.default=GSu});var EFo=b(vve=>{"use strict";Object.defineProperty(vve,"__esModule",{value:!0});vve.ecdhAllowed=vve.generateEpk=vve.deriveKey=void 0;var TVt=require("crypto"),ZJd=require("util"),HSu=SVt(),ALe=QI(),$Jd=wl(),gFo=S_(),WSu=Ive(),AFo=w_(),yFo=T_(),bFo=O_(),hFo=(0,ZJd.promisify)(TVt.generateKeyPair);async function eYd(e,t,r,n,i=new Uint8Array(0),o=new Uint8Array(0)){let s;if((0,gFo.isCryptoKey)(e))(0,WSu.checkEncCryptoKey)(e,"ECDH"),s=TVt.KeyObject.from(e);else if((0,AFo.default)(e))s=e;else throw new TypeError((0,yFo.default)(e,...bFo.types));let a;if((0,gFo.isCryptoKey)(t))(0,WSu.checkEncCryptoKey)(t,"ECDH","deriveBits"),a=TVt.KeyObject.from(t);else if((0,AFo.default)(t))a=t;else throw new TypeError((0,yFo.default)(t,...bFo.types));let c=(0,ALe.concat)((0,ALe.lengthAndInput)(ALe.encoder.encode(r)),(0,ALe.lengthAndInput)(i),(0,ALe.lengthAndInput)(o),(0,ALe.uint32be)(n)),u=(0,TVt.diffieHellman)({privateKey:a,publicKey:s});return(0,ALe.concatKdf)(u,n,c)}vve.deriveKey=eYd;async function tYd(e){let t;if((0,gFo.isCryptoKey)(e))t=TVt.KeyObject.from(e);else if((0,AFo.default)(e))t=e;else throw new TypeError((0,yFo.default)(e,...bFo.types));switch(t.asymmetricKeyType){case"x25519":return hFo("x25519");case"x448":return hFo("x448");case"ec":{let r=(0,HSu.default)(t);return hFo("ec",{namedCurve:r})}default:throw new $Jd.JOSENotSupported("Invalid or unsupported EPK")}}vve.generateEpk=tYd;var rYd=e=>["P-256","P-384","P-521","X25519","X448"].includes((0,HSu.default)(e));vve.ecdhAllowed=rYd});var KSu=b(IFo=>{"use strict";Object.defineProperty(IFo,"__esModule",{value:!0});var nYd=wl();function iYd(e){if(!(e instanceof Uint8Array)||e.length<8)throw new nYd.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}IFo.default=iYd});var vFo=b(Ont=>{"use strict";Object.defineProperty(Ont,"__esModule",{value:!0});Ont.decrypt=Ont.encrypt=void 0;var oYd=require("util"),JSu=require("crypto"),sYd=IVt(),YSu=QI(),aYd=kD(),XSu=F_r(),ZSu=KSu(),cYd=S_(),uYd=Ive(),lYd=w_(),pYd=T_(),fYd=O_(),$Su=(0,oYd.promisify)(JSu.pbkdf2);function e1u(e,t){if((0,lYd.default)(e))return e.export();if(e instanceof Uint8Array)return e;if((0,cYd.isCryptoKey)(e))return(0,uYd.checkEncCryptoKey)(e,t,"deriveBits","deriveKey"),JSu.KeyObject.from(e).export();throw new TypeError((0,pYd.default)(e,...fYd.types,"Uint8Array"))}var dYd=async(e,t,r,n=2048,i=(0,sYd.default)(new Uint8Array(16)))=>{(0,ZSu.default)(i);let o=(0,YSu.p2s)(e,i),s=parseInt(e.slice(13,16),10)>>3,a=e1u(t,e),c=await $Su(a,o,n,s,`sha${e.slice(8,11)}`);return{encryptedKey:await(0,XSu.wrap)(e.slice(-6),c,r),p2c:n,p2s:(0,aYd.encode)(i)}};Ont.encrypt=dYd;var mYd=async(e,t,r,n,i)=>{(0,ZSu.default)(i);let o=(0,YSu.p2s)(e,i),s=parseInt(e.slice(13,16),10)>>3,a=e1u(t,e),c=await $Su(a,o,n,s,`sha${e.slice(8,11)}`);return(0,XSu.unwrap)(e.slice(-6),c,r)};Ont.decrypt=mYd});var OVt=b(oH=>{"use strict";Object.defineProperty(oH,"__esModule",{value:!0});oH.setModulusLength=oH.weakMap=void 0;oH.weakMap=new WeakMap;var j_r=(e,t)=>{let r=e.readUInt8(1);if((r&128)===0)return t===0?r:j_r(e.subarray(2+r),t-1);let n=r&127;r=0;for(let i=0;i<n;i++){r<<=8;let o=e.readUInt8(2+i);r|=o}return t===0?r:j_r(e.subarray(2+r),t-1)},hYd=(e,t)=>{let r=e.readUInt8(1);if((r&128)===0)return j_r(e.subarray(2),t);let n=r&127;return j_r(e.subarray(2+n),t)},gYd=e=>{var t,r;if(oH.weakMap.has(e))return oH.weakMap.get(e);let n=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:hYd(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return oH.weakMap.set(e,n),n},AYd=(e,t)=>{oH.weakMap.set(e,t)};oH.setModulusLength=AYd;oH.default=(e,t)=>{if(gYd(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}});var xFo=b(Bnt=>{"use strict";Object.defineProperty(Bnt,"__esModule",{value:!0});Bnt.decrypt=Bnt.encrypt=void 0;var BVt=require("crypto"),yYd=OVt(),bYd=S_(),EYd=Ive(),IYd=w_(),vYd=T_(),xYd=O_(),t1u=(e,t)=>{if(e.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,yYd.default)(e,t)},r1u=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return BVt.constants.RSA_PKCS1_OAEP_PADDING;case"RSA1_5":return BVt.constants.RSA_PKCS1_PADDING;default:return}},n1u=e=>{switch(e){case"RSA-OAEP":return"sha1";case"RSA-OAEP-256":return"sha256";case"RSA-OAEP-384":return"sha384";case"RSA-OAEP-512":return"sha512";default:return}};function i1u(e,t,...r){if((0,IYd.default)(e))return e;if((0,bYd.isCryptoKey)(e))return(0,EYd.checkEncCryptoKey)(e,t,...r),BVt.KeyObject.from(e);throw new TypeError((0,vYd.default)(e,...xYd.types))}var CYd=(e,t,r)=>{let n=r1u(e),i=n1u(e),o=i1u(t,e,"wrapKey","encrypt");return t1u(o,e),(0,BVt.publicEncrypt)({key:o,oaepHash:i,padding:n},r)};Bnt.encrypt=CYd;var wYd=(e,t,r)=>{let n=r1u(e),i=n1u(e),o=i1u(t,e,"unwrapKey","decrypt");return t1u(o,e),(0,BVt.privateDecrypt)({key:o,oaepHash:i,padding:n},r)};Bnt.decrypt=wYd});var DVt=b(PVt=>{"use strict";Object.defineProperty(PVt,"__esModule",{value:!0});PVt.bitLength=void 0;var SYd=wl(),TYd=IVt();function o1u(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new SYd.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}PVt.bitLength=o1u;PVt.default=e=>(0,TYd.default)(new Uint8Array(o1u(e)>>3))});var z_r=b(B_=>{"use strict";Object.defineProperty(B_,"__esModule",{value:!0});B_.fromX509=B_.fromSPKI=B_.fromPKCS8=B_.toPKCS8=B_.toSPKI=void 0;var Q_r=require("crypto"),s1u=require("buffer"),OYd=S_(),BYd=w_(),PYd=T_(),DYd=O_(),a1u=(e,t,r)=>{let n;if((0,OYd.isCryptoKey)(r)){if(!r.extractable)throw new TypeError("CryptoKey is not extractable");n=Q_r.KeyObject.from(r)}else if((0,BYd.default)(r))n=r;else throw new TypeError((0,PYd.default)(r,...DYd.types));if(n.type!==e)throw new TypeError(`key is not a ${e} key`);return n.export({format:"pem",type:t})},RYd=e=>a1u("public","spki",e);B_.toSPKI=RYd;var kYd=e=>a1u("private","pkcs8",e);B_.toPKCS8=kYd;var FYd=e=>(0,Q_r.createPrivateKey)({key:s1u.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});B_.fromPKCS8=FYd;var NYd=e=>(0,Q_r.createPublicKey)({key:s1u.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,""),"base64"),type:"spki",format:"der"});B_.fromSPKI=NYd;var jYd=e=>(0,Q_r.createPublicKey)({key:e,type:"spki",format:"pem"});B_.fromX509=jYd});var c1u=b(SFo=>{"use strict";Object.defineProperty(SFo,"__esModule",{value:!0});var AC=require("buffer"),QYd=wl(),zYd=2,MYd=3,LYd=4,VYd=48,CFo=AC.Buffer.from([0]),M_r=AC.Buffer.from([zYd]),UYd=AC.Buffer.from([MYd]),_Yd=AC.Buffer.from([VYd]),qYd=AC.Buffer.from([LYd]),xve=e=>{if(e<128)return AC.Buffer.from([e]);let t=AC.Buffer.alloc(5);t.writeUInt32BE(e,1);let r=1;for(;t[r]===0;)r++;return t[r-1]=128|5-r,t.slice(r-1)},GYd=new Map([["P-256",AC.Buffer.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",AC.Buffer.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",AC.Buffer.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",AC.Buffer.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",AC.Buffer.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",AC.Buffer.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",AC.Buffer.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",AC.Buffer.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",AC.Buffer.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]),wFo=class{constructor(){this.length=0,this.elements=[]}oidFor(t){let r=GYd.get(t);if(!r)throw new QYd.JOSENotSupported("Invalid or unsupported OID");this.elements.push(r),this.length+=r.length}zero(){this.elements.push(M_r,AC.Buffer.from([1]),CFo),this.length+=3}one(){this.elements.push(M_r,AC.Buffer.from([1]),AC.Buffer.from([1])),this.length+=3}unsignedInteger(t){if(t[0]&128){let r=xve(t.length+1);this.elements.push(M_r,r,CFo,t),this.length+=2+r.length+t.length}else{let r=0;for(;t[r]===0&&(t[r+1]&128)===0;)r++;let n=xve(t.length-r);this.elements.push(M_r,xve(t.length-r),t.slice(r)),this.length+=1+n.length+t.length-r}}octStr(t){let r=xve(t.length);this.elements.push(qYd,xve(t.length),t),this.length+=1+r.length+t.length}bitStr(t){let r=xve(t.length+1);this.elements.push(UYd,xve(t.length+1),CFo,t),this.length+=1+r.length+t.length+1}add(t){this.elements.push(t),this.length+=t.length}end(t=_Yd){let r=xve(this.length);return AC.Buffer.concat([t,r,...this.elements],1+r.length+this.length)}};SFo.default=wFo});var RVt=b(pee=>{"use strict";Object.defineProperty(pee,"__esModule",{value:!0});pee.jwkImport=pee.jwkExport=pee.rsaPssParams=pee.oneShotCallback=void 0;var[Cve,L_r]=process.versions.node.split(".").map(e=>parseInt(e,10));pee.oneShotCallback=Cve>=16||Cve===15&&L_r>=13;pee.rsaPssParams=!("electron"in process.versions)&&(Cve>=17||Cve===16&&L_r>=9);pee.jwkExport=Cve>=16||Cve===15&&L_r>=9;pee.jwkImport=Cve>=16||Cve===15&&L_r>=12});var l1u=b(TFo=>{"use strict";Object.defineProperty(TFo,"__esModule",{value:!0});var _1=require("buffer"),Ife=require("crypto"),WYd=kD(),HYd=wl(),u1u=SVt(),KYd=OVt(),sH=c1u(),JYd=RVt(),YYd=e=>{if(JYd.jwkImport&&e.kty!=="oct")return e.d?(0,Ife.createPrivateKey)({format:"jwk",key:e}):(0,Ife.createPublicKey)({format:"jwk",key:e});switch(e.kty){case"oct":return(0,Ife.createSecretKey)((0,WYd.decode)(e.k));case"RSA":{let t=new sH.default,r=e.d!==void 0,n=_1.Buffer.from(e.n,"base64"),i=_1.Buffer.from(e.e,"base64");r?(t.zero(),t.unsignedInteger(n),t.unsignedInteger(i),t.unsignedInteger(_1.Buffer.from(e.d,"base64")),t.unsignedInteger(_1.Buffer.from(e.p,"base64")),t.unsignedInteger(_1.Buffer.from(e.q,"base64")),t.unsignedInteger(_1.Buffer.from(e.dp,"base64")),t.unsignedInteger(_1.Buffer.from(e.dq,"base64")),t.unsignedInteger(_1.Buffer.from(e.qi,"base64"))):(t.unsignedInteger(n),t.unsignedInteger(i));let s={key:t.end(),format:"der",type:"pkcs1"},a=r?(0,Ife.createPrivateKey)(s):(0,Ife.createPublicKey)(s);return(0,KYd.setModulusLength)(a,n.length<<3),a}case"EC":{let t=new sH.default,r=e.d!==void 0,n=_1.Buffer.concat([_1.Buffer.alloc(1,4),_1.Buffer.from(e.x,"base64"),_1.Buffer.from(e.y,"base64")]);if(r){t.zero();let a=new sH.default;a.oidFor("ecPublicKey"),a.oidFor(e.crv),t.add(a.end());let c=new sH.default;c.one(),c.octStr(_1.Buffer.from(e.d,"base64"));let u=new sH.default;u.bitStr(n);let l=u.end(_1.Buffer.from([161]));c.add(l);let p=c.end(),d=new sH.default;d.add(p);let f=d.end(_1.Buffer.from([4]));t.add(f);let m=t.end(),g=(0,Ife.createPrivateKey)({key:m,format:"der",type:"pkcs8"});return(0,u1u.setCurve)(g,e.crv),g}let i=new sH.default;i.oidFor("ecPublicKey"),i.oidFor(e.crv),t.add(i.end()),t.bitStr(n);let o=t.end(),s=(0,Ife.createPublicKey)({key:o,format:"der",type:"spki"});return(0,u1u.setCurve)(s,e.crv),s}case"OKP":{let t=new sH.default;if(e.d!==void 0){t.zero();let o=new sH.default;o.oidFor(e.crv),t.add(o.end());let s=new sH.default;s.octStr(_1.Buffer.from(e.d,"base64"));let a=s.end(_1.Buffer.from([4]));t.add(a);let c=t.end();return(0,Ife.createPrivateKey)({key:c,format:"der",type:"pkcs8"})}let n=new sH.default;n.oidFor(e.crv),t.add(n.end()),t.bitStr(_1.Buffer.from(e.x,"base64"));let i=t.end();return(0,Ife.createPublicKey)({key:i,format:"der",type:"spki"})}default:throw new HYd.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}};TFo.default=YYd});var kVt=b(fee=>{"use strict";Object.defineProperty(fee,"__esModule",{value:!0});fee.importJWK=fee.importPKCS8=fee.importX509=fee.importSPKI=void 0;var XYd=kD(),OFo=z_r(),p1u=l1u(),f1u=wl(),ZYd=JQ();async function $Yd(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return(0,OFo.fromSPKI)(e,t,r)}fee.importSPKI=$Yd;async function eXd(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return(0,OFo.fromX509)(e,t,r)}fee.importX509=eXd;async function tXd(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,OFo.fromPKCS8)(e,t,r)}fee.importPKCS8=tXd;async function rXd(e,t,r){var n;if(!(0,ZYd.default)(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=e.ext!==!0),r?(0,p1u.default)({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):(0,XYd.decode)(e.k);case"RSA":if(e.oth!==void 0)throw new f1u.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(0,p1u.default)({...e,alg:t});default:throw new f1u.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}fee.importJWK=rXd});var FVt=b(BFo=>{"use strict";Object.defineProperty(BFo,"__esModule",{value:!0});var d1u=T_(),dee=O_(),nXd=(e,t)=>{if(!(t instanceof Uint8Array)){if(!(0,dee.default)(t))throw new TypeError((0,d1u.withAlg)(e,t,...dee.types,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${dee.types.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},iXd=(e,t,r)=>{if(!(0,dee.default)(t))throw new TypeError((0,d1u.withAlg)(e,t,...dee.types));if(t.type==="secret")throw new TypeError(`${dee.types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${dee.types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${dee.types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${dee.types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${dee.types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},oXd=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?nXd(e,t):iXd(e,t,r)};BFo.default=oXd});var kFo=b(RFo=>{"use strict";Object.defineProperty(RFo,"__esModule",{value:!0});var PFo=require("crypto"),sXd=$ko(),aXd=nFo(),cXd=QI(),uXd=sFo(),lXd=S_(),pXd=Ive(),m1u=w_(),fXd=T_(),DFo=wl(),h1u=D_r(),dXd=O_();function mXd(e,t,r,n,i){let o=parseInt(e.slice(1,4),10);(0,m1u.default)(r)&&(r=r.export());let s=r.subarray(o>>3),a=r.subarray(0,o>>3),c=`aes-${o}-cbc`;if(!(0,h1u.default)(c))throw new DFo.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let u=(0,PFo.createCipheriv)(c,s,n),l=(0,cXd.concat)(u.update(t),u.final()),p=parseInt(e.slice(-3),10),d=(0,uXd.default)(i,n,l,p,a,o);return{ciphertext:l,tag:d}}function hXd(e,t,r,n,i){let s=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,h1u.default)(s))throw new DFo.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let a=(0,PFo.createCipheriv)(s,r,n,{authTagLength:16});i.byteLength&&a.setAAD(i,{plaintextLength:t.length});let c=a.update(t);a.final();let u=a.getAuthTag();return{ciphertext:c,tag:u}}var gXd=(e,t,r,n,i)=>{let o;if((0,lXd.isCryptoKey)(r))(0,pXd.checkEncCryptoKey)(r,e,"encrypt"),o=PFo.KeyObject.from(r);else if(r instanceof Uint8Array||(0,m1u.default)(r))o=r;else throw new TypeError((0,fXd.default)(r,...dXd.types,"Uint8Array"));switch((0,aXd.default)(e,o),(0,sXd.default)(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return mXd(e,t,o,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return hXd(e,t,o,n,i);default:throw new DFo.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};RFo.default=gXd});var FFo=b(Pnt=>{"use strict";Object.defineProperty(Pnt,"__esModule",{value:!0});Pnt.unwrap=Pnt.wrap=void 0;var AXd=kFo(),yXd=pFo(),bXd=B_r(),g1u=kD();async function EXd(e,t,r,n){let i=e.slice(0,7);n||(n=(0,bXd.default)(i));let{ciphertext:o,tag:s}=await(0,AXd.default)(i,r,t,n,new Uint8Array(0));return{encryptedKey:o,iv:(0,g1u.encode)(n),tag:(0,g1u.encode)(s)}}Pnt.wrap=EXd;async function IXd(e,t,r,n,i){let o=e.slice(0,7);return(0,yXd.default)(o,t,r,n,i,new Uint8Array(0))}Pnt.unwrap=IXd});var b1u=b(NFo=>{"use strict";Object.defineProperty(NFo,"__esModule",{value:!0});var A1u=F_r(),y1u=EFo(),vXd=vFo(),xXd=xFo(),NVt=kD(),zI=wl(),CXd=DVt(),wXd=kVt(),SXd=FVt(),TXd=JQ(),OXd=FFo();async function BXd(e,t,r,n,i){switch((0,SXd.default)(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new zI.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new zI.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,TXd.default)(n.epk))throw new zI.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!y1u.ecdhAllowed(t))throw new zI.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await(0,wXd.importJWK)(n.epk,e),s,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new zI.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{s=(0,NVt.decode)(n.apu)}catch{throw new zI.JWEInvalid("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new zI.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{a=(0,NVt.decode)(n.apv)}catch{throw new zI.JWEInvalid("Failed to base64url decode the apv")}}let c=await y1u.deriveKey(o,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?(0,CXd.bitLength)(n.enc):parseInt(e.slice(-5,-2),10),s,a);if(e==="ECDH-ES")return c;if(r===void 0)throw new zI.JWEInvalid("JWE Encrypted Key missing");return(0,A1u.unwrap)(e.slice(-6),c,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new zI.JWEInvalid("JWE Encrypted Key missing");return(0,xXd.decrypt)(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new zI.JWEInvalid("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new zI.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new zI.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new zI.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let s;try{s=(0,NVt.decode)(n.p2s)}catch{throw new zI.JWEInvalid("Failed to base64url decode the p2s")}return(0,vXd.decrypt)(e,t,r,n.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new zI.JWEInvalid("JWE Encrypted Key missing");return(0,A1u.unwrap)(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new zI.JWEInvalid("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new zI.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new zI.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o;try{o=(0,NVt.decode)(n.iv)}catch{throw new zI.JWEInvalid("Failed to base64url decode the iv")}let s;try{s=(0,NVt.decode)(n.tag)}catch{throw new zI.JWEInvalid("Failed to base64url decode the tag")}return(0,OXd.unwrap)(e,t,r,o,s)}default:throw new zI.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}}NFo.default=BXd});var Dnt=b(jFo=>{"use strict";Object.defineProperty(jFo,"__esModule",{value:!0});var PXd=wl();function DXd(e,t,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let s of n.crit){if(!o.has(s))throw new PXd.JOSENotSupported(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}jFo.default=DXd});var zFo=b(QFo=>{"use strict";Object.defineProperty(QFo,"__esModule",{value:!0});var RXd=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};QFo.default=RXd});var U_r=b(V_r=>{"use strict";Object.defineProperty(V_r,"__esModule",{value:!0});V_r.flattenedDecrypt=void 0;var Rnt=kD(),kXd=pFo(),FXd=fFo(),Cy=wl(),NXd=Snt(),MFo=JQ(),jXd=b1u(),jVt=QI(),QXd=DVt(),zXd=Dnt(),E1u=zFo();async function MXd(e,t,r){var n;if(!(0,MFo.default)(e))throw new Cy.JWEInvalid("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new Cy.JWEInvalid("JOSE Header missing");if(typeof e.iv!="string")throw new Cy.JWEInvalid("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new Cy.JWEInvalid("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new Cy.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new Cy.JWEInvalid("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new Cy.JWEInvalid("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new Cy.JWEInvalid("JWE AAD incorrect type");if(e.header!==void 0&&!(0,MFo.default)(e.header))throw new Cy.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!(0,MFo.default)(e.unprotected))throw new Cy.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let i;if(e.protected)try{let I=(0,Rnt.decode)(e.protected);i=JSON.parse(jVt.decoder.decode(I))}catch{throw new Cy.JWEInvalid("JWE Protected Header is invalid")}if(!(0,NXd.default)(i,e.header,e.unprotected))throw new Cy.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...i,...e.header,...e.unprotected};if((0,zXd.default)(Cy.JWEInvalid,new Map,r?.crit,i,o),o.zip!==void 0){if(!i||!i.zip)throw new Cy.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(o.zip!=="DEF")throw new Cy.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:s,enc:a}=o;if(typeof s!="string"||!s)throw new Cy.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if(typeof a!="string"||!a)throw new Cy.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");let c=r&&(0,E1u.default)("keyManagementAlgorithms",r.keyManagementAlgorithms),u=r&&(0,E1u.default)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(c&&!c.has(s))throw new Cy.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(u&&!u.has(a))throw new Cy.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');let l;if(e.encrypted_key!==void 0)try{l=(0,Rnt.decode)(e.encrypted_key)}catch{throw new Cy.JWEInvalid("Failed to base64url decode the encrypted_key")}let p=!1;typeof t=="function"&&(t=await t(i,e),p=!0);let d;try{d=await(0,jXd.default)(s,t,l,o,r)}catch(I){if(I instanceof TypeError||I instanceof Cy.JWEInvalid||I instanceof Cy.JOSENotSupported)throw I;d=(0,QXd.default)(a)}let f,m;try{f=(0,Rnt.decode)(e.iv)}catch{throw new Cy.JWEInvalid("Failed to base64url decode the iv")}try{m=(0,Rnt.decode)(e.tag)}catch{throw new Cy.JWEInvalid("Failed to base64url decode the tag")}let g=jVt.encoder.encode((n=e.protected)!==null&&n!==void 0?n:""),A;e.aad!==void 0?A=(0,jVt.concat)(g,jVt.encoder.encode("."),jVt.encoder.encode(e.aad)):A=g;let y;try{y=(0,Rnt.decode)(e.ciphertext)}catch{throw new Cy.JWEInvalid("Failed to base64url decode the ciphertext")}let E=await(0,kXd.default)(a,d,y,f,m,A);o.zip==="DEF"&&(E=await(r?.inflateRaw||FXd.inflate)(E));let x={plaintext:E};if(e.protected!==void 0&&(x.protectedHeader=i),e.aad!==void 0)try{x.additionalAuthenticatedData=(0,Rnt.decode)(e.aad)}catch{throw new Cy.JWEInvalid("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(x.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(x.unprotectedHeader=e.header),p?{...x,key:t}:x}V_r.flattenedDecrypt=MXd});var LFo=b(__r=>{"use strict";Object.defineProperty(__r,"__esModule",{value:!0});__r.compactDecrypt=void 0;var LXd=U_r(),I1u=wl(),VXd=QI();async function UXd(e,t,r){if(e instanceof Uint8Array&&(e=VXd.decoder.decode(e)),typeof e!="string")throw new I1u.JWEInvalid("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new I1u.JWEInvalid("Invalid Compact JWE");let u=await(0,LXd.flattenedDecrypt)({ciphertext:s,iv:o||void 0,protected:n||void 0,tag:a||void 0,encrypted_key:i||void 0},t,r),l={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t=="function"?{...l,key:u.key}:l}__r.compactDecrypt=UXd});var x1u=b(G_r=>{"use strict";Object.defineProperty(G_r,"__esModule",{value:!0});G_r.generalDecrypt=void 0;var _Xd=U_r(),q_r=wl(),v1u=JQ();async function qXd(e,t,r){if(!(0,v1u.default)(e))throw new q_r.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(v1u.default))throw new q_r.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new q_r.JWEInvalid("JWE Recipients has no members");for(let n of e.recipients)try{return await(0,_Xd.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new q_r.JWEDecryptionFailed}G_r.generalDecrypt=qXd});var C1u=b(UFo=>{"use strict";Object.defineProperty(UFo,"__esModule",{value:!0});var GXd=2,WXd=48,VFo=class{constructor(t){if(t[0]!==WXd)throw new TypeError;if(this.buffer=t,this.offset=1,this.decodeLength()!==t.length-this.offset)throw new TypeError}decodeLength(){let t=this.buffer[this.offset++];if(t&128){let r=t&-129;t=0;for(let n=0;n<r;n++)t=t<<8|this.buffer[this.offset+n];this.offset+=r}return t}unsignedInteger(){if(this.buffer[this.offset++]!==GXd)throw new TypeError;let t=this.decodeLength();this.buffer[this.offset]===0&&(this.offset++,t--);let r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}end(){if(this.offset!==this.buffer.length)throw new TypeError}};UFo.default=VFo});var w1u=b(qFo=>{"use strict";Object.defineProperty(qFo,"__esModule",{value:!0});var W_r=require("crypto"),SB=kD(),HXd=C1u(),H_r=wl(),_Fo=SVt(),KXd=S_(),JXd=w_(),YXd=T_(),XXd=O_(),ZXd=RVt(),K_r=e=>{let t;if((0,KXd.isCryptoKey)(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=W_r.KeyObject.from(e)}else if((0,JXd.default)(e))t=e;else{if(e instanceof Uint8Array)return{kty:"oct",k:(0,SB.encode)(e)};throw new TypeError((0,YXd.default)(e,...XXd.types,"Uint8Array"))}if(ZXd.jwkExport){if(t.type!=="secret"&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new H_r.JOSENotSupported("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})}switch(t.type){case"secret":return{kty:"oct",k:(0,SB.encode)(t.export())};case"private":case"public":switch(t.asymmetricKeyType){case"rsa":{let r=t.export({format:"der",type:"pkcs1"}),n=new HXd.default(r);t.type==="private"&&n.unsignedInteger();let i=(0,SB.encode)(n.unsignedInteger()),o=(0,SB.encode)(n.unsignedInteger()),s;return t.type==="private"&&(s={d:(0,SB.encode)(n.unsignedInteger()),p:(0,SB.encode)(n.unsignedInteger()),q:(0,SB.encode)(n.unsignedInteger()),dp:(0,SB.encode)(n.unsignedInteger()),dq:(0,SB.encode)(n.unsignedInteger()),qi:(0,SB.encode)(n.unsignedInteger())}),n.end(),{kty:"RSA",n:i,e:o,...s}}case"ec":{let r=(0,_Fo.default)(t),n,i,o;switch(r){case"secp256k1":n=64,i=33,o=-1;break;case"P-256":n=64,i=36,o=-1;break;case"P-384":n=96,i=35,o=-3;break;case"P-521":n=132,i=35,o=-3;break;default:throw new H_r.JOSENotSupported("Unsupported curve")}if(t.type==="public"){let a=t.export({type:"spki",format:"der"});return{kty:"EC",crv:r,x:(0,SB.encode)(a.subarray(-n,-n/2)),y:(0,SB.encode)(a.subarray(-n/2))}}let s=t.export({type:"pkcs8",format:"der"});return s.length<100&&(i+=o),{...K_r((0,W_r.createPublicKey)(t)),d:(0,SB.encode)(s.subarray(i,i+n/2))}}case"ed25519":case"x25519":{let r=(0,_Fo.default)(t);if(t.type==="public"){let i=t.export({type:"spki",format:"der"});return{kty:"OKP",crv:r,x:(0,SB.encode)(i.subarray(-32))}}let n=t.export({type:"pkcs8",format:"der"});return{...K_r((0,W_r.createPublicKey)(t)),d:(0,SB.encode)(n.subarray(-32))}}case"ed448":case"x448":{let r=(0,_Fo.default)(t);if(t.type==="public"){let i=t.export({type:"spki",format:"der"});return{kty:"OKP",crv:r,x:(0,SB.encode)(i.subarray(r==="Ed448"?-57:-56))}}let n=t.export({type:"pkcs8",format:"der"});return{...K_r((0,W_r.createPublicKey)(t)),d:(0,SB.encode)(n.subarray(r==="Ed448"?-57:-56))}}default:throw new H_r.JOSENotSupported("Unsupported key asymmetricKeyType")}default:throw new H_r.JOSENotSupported("Unsupported key type")}};qFo.default=K_r});var GFo=b(wve=>{"use strict";Object.defineProperty(wve,"__esModule",{value:!0});wve.exportJWK=wve.exportPKCS8=wve.exportSPKI=void 0;var $Xd=z_r(),eZd=z_r(),tZd=w1u();async function rZd(e){return(0,$Xd.toSPKI)(e)}wve.exportSPKI=rZd;async function nZd(e){return(0,eZd.toPKCS8)(e)}wve.exportPKCS8=nZd;async function iZd(e){return(0,tZd.default)(e)}wve.exportJWK=iZd});var KFo=b(HFo=>{"use strict";Object.defineProperty(HFo,"__esModule",{value:!0});var S1u=F_r(),WFo=EFo(),oZd=vFo(),sZd=xFo(),T1u=kD(),knt=DVt(),O1u=wl(),aZd=GFo(),cZd=FVt(),uZd=FFo();async function lZd(e,t,r,n,i={}){let o,s,a;switch((0,cZd.default)(e,r,"encrypt"),e){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!WFo.ecdhAllowed(r))throw new O1u.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=i,{epk:l}=i;l||(l=(await WFo.generateEpk(r)).privateKey);let{x:p,y:d,crv:f,kty:m}=await(0,aZd.exportJWK)(l),g=await WFo.deriveKey(r,l,e==="ECDH-ES"?t:e,e==="ECDH-ES"?(0,knt.bitLength)(t):parseInt(e.slice(-5,-2),10),c,u);if(s={epk:{x:p,crv:f,kty:m}},m==="EC"&&(s.epk.y=d),c&&(s.apu=(0,T1u.encode)(c)),u&&(s.apv=(0,T1u.encode)(u)),e==="ECDH-ES"){a=g;break}a=n||(0,knt.default)(t);let A=e.slice(-6);o=await(0,S1u.wrap)(A,g,a);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||(0,knt.default)(t),o=await(0,sZd.encrypt)(e,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||(0,knt.default)(t);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await(0,oZd.encrypt)(e,r,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=n||(0,knt.default)(t),o=await(0,S1u.wrap)(e,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||(0,knt.default)(t);let{iv:c}=i;({encryptedKey:o,...s}=await(0,uZd.wrap)(e,r,a,c));break}default:throw new O1u.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}HFo.default=lZd});var J_r=b(bLe=>{"use strict";Object.defineProperty(bLe,"__esModule",{value:!0});bLe.FlattenedEncrypt=bLe.unprotected=void 0;var Fnt=kD(),B1u=kFo(),pZd=fFo(),fZd=B_r(),dZd=KFo(),yLe=wl(),mZd=Snt(),Nnt=QI(),hZd=Dnt();bLe.unprotected=Symbol();var JFo=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new yLe.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,mZd.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new yLe.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,hZd.default)(yLe.JWEInvalid,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new yLe.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new yLe.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new yLe.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new yLe.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let s;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let a;{let m;({cek:a,encryptedKey:s,parameters:m}=await(0,dZd.default)(i,o,t,this._cek,this._keyManagementParameters)),m&&(r&&bLe.unprotected in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...m}:this.setUnprotectedHeader(m):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...m}:this.setProtectedHeader(m))}this._iv||(this._iv=(0,fZd.default)(o));let c,u,l;this._protectedHeader?u=Nnt.encoder.encode((0,Fnt.encode)(JSON.stringify(this._protectedHeader))):u=Nnt.encoder.encode(""),this._aad?(l=(0,Fnt.encode)(this._aad),c=(0,Nnt.concat)(u,Nnt.encoder.encode("."),Nnt.encoder.encode(l))):c=u;let p,d;if(n.zip==="DEF"){let m=await(r?.deflateRaw||pZd.deflate)(this._plaintext);({ciphertext:p,tag:d}=await(0,B1u.default)(o,m,a,this._iv,c))}else({ciphertext:p,tag:d}=await(0,B1u.default)(o,this._plaintext,a,this._iv,c));let f={ciphertext:(0,Fnt.encode)(p),iv:(0,Fnt.encode)(this._iv),tag:(0,Fnt.encode)(d)};return s&&(f.encrypted_key=(0,Fnt.encode)(s)),l&&(f.aad=l),this._protectedHeader&&(f.protected=Nnt.decoder.decode(u)),this._sharedUnprotectedHeader&&(f.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(f.header=this._unprotectedHeader),f}};bLe.FlattenedEncrypt=JFo});var P1u=b(Y_r=>{"use strict";Object.defineProperty(Y_r,"__esModule",{value:!0});Y_r.GeneralEncrypt=void 0;var YFo=J_r(),Sve=wl(),gZd=DVt(),AZd=Snt(),yZd=KFo(),bZd=kD(),EZd=Dnt(),XFo=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},ZFo=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new XFo(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,i;if(!this._recipients.length)throw new Sve.JWEInvalid("at least one recipient must be added");if(t={deflateRaw:t?.deflateRaw},this._recipients.length===1){let[c]=this._recipients,u=await new YFo.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(c.unprotectedHeader).encrypt(c.key,{...c.options,...t}),l={ciphertext:u.ciphertext,iv:u.iv,recipients:[{}],tag:u.tag};return u.aad&&(l.aad=u.aad),u.protected&&(l.protected=u.protected),u.unprotected&&(l.unprotected=u.unprotected),u.encrypted_key&&(l.recipients[0].encrypted_key=u.encrypted_key),u.header&&(l.recipients[0].header=u.header),l}let o;for(let c=0;c<this._recipients.length;c++){let u=this._recipients[c];if(!(0,AZd.default)(this._protectedHeader,this._unprotectedHeader,u.unprotectedHeader))throw new Sve.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let l={...this._protectedHeader,...this._unprotectedHeader,...u.unprotectedHeader},{alg:p}=l;if(typeof p!="string"||!p)throw new Sve.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new Sve.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof l.enc!="string"||!l.enc)throw new Sve.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!o)o=l.enc;else if(o!==l.enc)throw new Sve.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if((0,EZd.default)(Sve.JWEInvalid,new Map,u.options.crit,this._protectedHeader,l),l.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new Sve.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let s=(0,gZd.default)(o),a={ciphertext:"",iv:"",recipients:[],tag:""};for(let c=0;c<this._recipients.length;c++){let u=this._recipients[c],l={};a.recipients.push(l);let d={...this._protectedHeader,...this._unprotectedHeader,...u.unprotectedHeader}.alg.startsWith("PBES2")?2048+c:void 0;if(c===0){let g=await new YFo.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(s).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).setKeyManagementParameters({p2c:d}).encrypt(u.key,{...u.options,...t,[YFo.unprotected]:!0});a.ciphertext=g.ciphertext,a.iv=g.iv,a.tag=g.tag,g.aad&&(a.aad=g.aad),g.protected&&(a.protected=g.protected),g.unprotected&&(a.unprotected=g.unprotected),l.encrypted_key=g.encrypted_key,g.header&&(l.header=g.header);continue}let{encryptedKey:f,parameters:m}=await(0,yZd.default)(((r=u.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),o,u.key,s,{p2c:d});l.encrypted_key=(0,bZd.encode)(f),(u.unprotectedHeader||m)&&(l.header={...u.unprotectedHeader,...m})}return a}};Y_r.GeneralEncrypt=ZFo});var e2o=b($Fo=>{"use strict";Object.defineProperty($Fo,"__esModule",{value:!0});var IZd=wl();function vZd(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new IZd.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}$Fo.default=vZd});var n2o=b(r2o=>{"use strict";Object.defineProperty(r2o,"__esModule",{value:!0});var D1u=require("crypto"),xZd=SVt(),CZd=wl(),t2o=OVt(),jnt=RVt(),R1u={padding:D1u.constants.RSA_PKCS1_PSS_PADDING,saltLength:D1u.constants.RSA_PSS_SALTLEN_DIGEST},wZd=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function SZd(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return(0,t2o.default)(t,e),t;case(jnt.rsaPssParams&&"PS256"):case(jnt.rsaPssParams&&"PS384"):case(jnt.rsaPssParams&&"PS512"):if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:n,saltLength:i}=t.asymmetricKeyDetails,o=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${o}`||n!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(i!==void 0&&i>o>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return(0,t2o.default)(t,e),{key:t,...R1u};case(!jnt.rsaPssParams&&"PS256"):case(!jnt.rsaPssParams&&"PS384"):case(!jnt.rsaPssParams&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return(0,t2o.default)(t,e),{key:t,...R1u};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=(0,xZd.default)(t),n=wZd.get(e);if(r!==n)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${n}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new CZd.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}r2o.default=SZd});var k1u=b(i2o=>{"use strict";Object.defineProperty(i2o,"__esModule",{value:!0});var TZd=wl();function OZd(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new TZd.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}i2o.default=OZd});var a2o=b(s2o=>{"use strict";Object.defineProperty(s2o,"__esModule",{value:!0});var o2o=require("crypto"),BZd=S_(),PZd=Ive(),F1u=T_(),N1u=O_();function DZd(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,F1u.default)(t,...N1u.types));return(0,o2o.createSecretKey)(t)}if(t instanceof o2o.KeyObject)return t;if((0,BZd.isCryptoKey)(t))return(0,PZd.checkSigCryptoKey)(t,e,r),o2o.KeyObject.from(t);throw new TypeError((0,F1u.default)(t,...N1u.types,"Uint8Array"))}s2o.default=DZd});var l2o=b(u2o=>{"use strict";Object.defineProperty(u2o,"__esModule",{value:!0});var X_r=require("crypto"),RZd=require("util"),kZd=e2o(),FZd=k1u(),NZd=n2o(),jZd=a2o(),c2o;X_r.sign.length>3?c2o=(0,RZd.promisify)(X_r.sign):c2o=X_r.sign;var QZd=async(e,t,r)=>{let n=(0,jZd.default)(e,t,"sign");if(e.startsWith("HS")){let i=X_r.createHmac((0,FZd.default)(e),n);return i.update(r),i.digest()}return c2o((0,kZd.default)(e),r,(0,NZd.default)(e,n))};u2o.default=QZd});var j1u=b(f2o=>{"use strict";Object.defineProperty(f2o,"__esModule",{value:!0});var Z_r=require("crypto"),zZd=require("util"),MZd=e2o(),LZd=n2o(),VZd=l2o(),UZd=a2o(),_Zd=RVt(),p2o;Z_r.verify.length>4&&_Zd.oneShotCallback?p2o=(0,zZd.promisify)(Z_r.verify):p2o=Z_r.verify;var qZd=async(e,t,r,n)=>{let i=(0,UZd.default)(e,t,"verify");if(e.startsWith("HS")){let a=await(0,VZd.default)(e,i,n),c=r;try{return Z_r.timingSafeEqual(c,a)}catch{return!1}}let o=(0,MZd.default)(e),s=(0,LZd.default)(e,i);try{return await p2o(o,n,s,r)}catch{return!1}};f2o.default=qZd});var e5r=b($_r=>{"use strict";Object.defineProperty($_r,"__esModule",{value:!0});$_r.flattenedVerify=void 0;var d2o=kD(),GZd=j1u(),TB=wl(),Qnt=QI(),WZd=Snt(),Q1u=JQ(),HZd=FVt(),KZd=Dnt(),JZd=zFo();async function YZd(e,t,r){var n;if(!(0,Q1u.default)(e))throw new TB.JWSInvalid("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new TB.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new TB.JWSInvalid("JWS Protected Header incorrect type");if(e.payload===void 0)throw new TB.JWSInvalid("JWS Payload missing");if(typeof e.signature!="string")throw new TB.JWSInvalid("JWS Signature missing or incorrect type");if(e.header!==void 0&&!(0,Q1u.default)(e.header))throw new TB.JWSInvalid("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let A=(0,d2o.decode)(e.protected);i=JSON.parse(Qnt.decoder.decode(A))}catch{throw new TB.JWSInvalid("JWS Protected Header is invalid")}if(!(0,WZd.default)(i,e.header))throw new TB.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...i,...e.header},s=(0,KZd.default)(TB.JWSInvalid,new Map([["b64",!0]]),r?.crit,i,o),a=!0;if(s.has("b64")&&(a=i.b64,typeof a!="boolean"))throw new TB.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=o;if(typeof c!="string"||!c)throw new TB.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');let u=r&&(0,JZd.default)("algorithms",r.algorithms);if(u&&!u.has(c))throw new TB.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(a){if(typeof e.payload!="string")throw new TB.JWSInvalid("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new TB.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof t=="function"&&(t=await t(i,e),l=!0),(0,HZd.default)(c,t,"verify");let p=(0,Qnt.concat)(Qnt.encoder.encode((n=e.protected)!==null&&n!==void 0?n:""),Qnt.encoder.encode("."),typeof e.payload=="string"?Qnt.encoder.encode(e.payload):e.payload),d;try{d=(0,d2o.decode)(e.signature)}catch{throw new TB.JWSInvalid("Failed to base64url decode the signature")}if(!await(0,GZd.default)(c,t,d,p))throw new TB.JWSSignatureVerificationFailed;let m;if(a)try{m=(0,d2o.decode)(e.payload)}catch{throw new TB.JWSInvalid("Failed to base64url decode the payload")}else typeof e.payload=="string"?m=Qnt.encoder.encode(e.payload):m=e.payload;let g={payload:m};return e.protected!==void 0&&(g.protectedHeader=i),e.header!==void 0&&(g.unprotectedHeader=e.header),l?{...g,key:t}:g}$_r.flattenedVerify=YZd});var m2o=b(t5r=>{"use strict";Object.defineProperty(t5r,"__esModule",{value:!0});t5r.compactVerify=void 0;var XZd=e5r(),z1u=wl(),ZZd=QI();async function $Zd(e,t,r){if(e instanceof Uint8Array&&(e=ZZd.decoder.decode(e)),typeof e!="string")throw new z1u.JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new z1u.JWSInvalid("Invalid Compact JWS");let a=await(0,XZd.flattenedVerify)({payload:i,protected:n,signature:o},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...c,key:a.key}:c}t5r.compactVerify=$Zd});var L1u=b(r5r=>{"use strict";Object.defineProperty(r5r,"__esModule",{value:!0});r5r.generalVerify=void 0;var e$d=e5r(),h2o=wl(),M1u=JQ();async function t$d(e,t,r){if(!(0,M1u.default)(e))throw new h2o.JWSInvalid("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(M1u.default))throw new h2o.JWSInvalid("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await(0,e$d.flattenedVerify)({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new h2o.JWSSignatureVerificationFailed}r5r.generalVerify=t$d});var A2o=b(g2o=>{"use strict";Object.defineProperty(g2o,"__esModule",{value:!0});g2o.default=e=>Math.floor(e.getTime()/1e3)});var E2o=b(b2o=>{"use strict";Object.defineProperty(b2o,"__esModule",{value:!0});var V1u=60,U1u=V1u*60,y2o=U1u*24,r$d=y2o*7,n$d=y2o*365.25,i$d=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;b2o.default=e=>{let t=i$d.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*V1u);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*U1u);case"day":case"days":case"d":return Math.round(r*y2o);case"week":case"weeks":case"w":return Math.round(r*r$d);default:return Math.round(r*n$d)}}});var n5r=b(I2o=>{"use strict";Object.defineProperty(I2o,"__esModule",{value:!0});var s3=wl(),o$d=QI(),s$d=A2o(),_1u=E2o(),a$d=JQ(),q1u=e=>e.toLowerCase().replace(/^application\//,""),c$d=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;I2o.default=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||q1u(e.typ)!==q1u(n)))throw new s3.JWTClaimValidationFailed('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(o$d.decoder.decode(t))}catch{}if(!(0,a$d.default)(i))throw new s3.JWTInvalid("JWT Claims Set must be a top-level JSON object");let{requiredClaims:o=[],issuer:s,subject:a,audience:c,maxTokenAge:u}=r;u!==void 0&&o.push("iat"),c!==void 0&&o.push("aud"),a!==void 0&&o.push("sub"),s!==void 0&&o.push("iss");for(let f of new Set(o.reverse()))if(!(f in i))throw new s3.JWTClaimValidationFailed(`missing required "${f}" claim`,f,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(i.iss))throw new s3.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");if(a&&i.sub!==a)throw new s3.JWTClaimValidationFailed('unexpected "sub" claim value',"sub","check_failed");if(c&&!c$d(i.aud,typeof c=="string"?[c]:c))throw new s3.JWTClaimValidationFailed('unexpected "aud" claim value',"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=(0,_1u.default)(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,d=(0,s$d.default)(p||new Date);if((i.iat!==void 0||u)&&typeof i.iat!="number")throw new s3.JWTClaimValidationFailed('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new s3.JWTClaimValidationFailed('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>d+l)throw new s3.JWTClaimValidationFailed('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new s3.JWTClaimValidationFailed('"exp" claim must be a number',"exp","invalid");if(i.exp<=d-l)throw new s3.JWTExpired('"exp" claim timestamp check failed',"exp","check_failed")}if(u){let f=d-i.iat,m=typeof u=="number"?u:(0,_1u.default)(u);if(f-l>m)throw new s3.JWTExpired('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(f<0-l)throw new s3.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i}});var G1u=b(i5r=>{"use strict";Object.defineProperty(i5r,"__esModule",{value:!0});i5r.jwtVerify=void 0;var u$d=m2o(),l$d=n5r(),p$d=wl();async function f$d(e,t,r){var n;let i=await(0,u$d.compactVerify)(e,t,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new p$d.JWTInvalid("JWTs MUST NOT use unencoded payload");let s={payload:(0,l$d.default)(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof t=="function"?{...s,key:i.key}:s}i5r.jwtVerify=f$d});var W1u=b(o5r=>{"use strict";Object.defineProperty(o5r,"__esModule",{value:!0});o5r.jwtDecrypt=void 0;var d$d=LFo(),m$d=n5r(),v2o=wl();async function h$d(e,t,r){let n=await(0,d$d.compactDecrypt)(e,t,r),i=(0,m$d.default)(n.protectedHeader,n.plaintext,r),{protectedHeader:o}=n;if(o.iss!==void 0&&o.iss!==i.iss)throw new v2o.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(o.sub!==void 0&&o.sub!==i.sub)throw new v2o.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(o.aud!==void 0&&JSON.stringify(o.aud)!==JSON.stringify(i.aud))throw new v2o.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch',"aud","mismatch");let s={payload:i,protectedHeader:o};return typeof t=="function"?{...s,key:n.key}:s}o5r.jwtDecrypt=h$d});var C2o=b(s5r=>{"use strict";Object.defineProperty(s5r,"__esModule",{value:!0});s5r.CompactEncrypt=void 0;var g$d=J_r(),x2o=class{constructor(t){this._flattened=new g$d.FlattenedEncrypt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};s5r.CompactEncrypt=x2o});var c5r=b(a5r=>{"use strict";Object.defineProperty(a5r,"__esModule",{value:!0});a5r.FlattenedSign=void 0;var w2o=kD(),A$d=l2o(),y$d=Snt(),QVt=wl(),ELe=QI(),b$d=FVt(),E$d=Dnt(),S2o=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new QVt.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,y$d.default)(this._protectedHeader,this._unprotectedHeader))throw new QVt.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=(0,E$d.default)(QVt.JWSInvalid,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(i.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new QVt.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new QVt.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,b$d.default)(s,t,"sign");let a=this._payload;o&&(a=ELe.encoder.encode((0,w2o.encode)(a)));let c;this._protectedHeader?c=ELe.encoder.encode((0,w2o.encode)(JSON.stringify(this._protectedHeader))):c=ELe.encoder.encode("");let u=(0,ELe.concat)(c,ELe.encoder.encode("."),a),l=await(0,A$d.default)(s,t,u),p={signature:(0,w2o.encode)(l),payload:""};return o&&(p.payload=ELe.decoder.decode(a)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ELe.decoder.decode(c)),p}};a5r.FlattenedSign=S2o});var O2o=b(u5r=>{"use strict";Object.defineProperty(u5r,"__esModule",{value:!0});u5r.CompactSign=void 0;var I$d=c5r(),T2o=class{constructor(t){this._flattened=new I$d.FlattenedSign(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};u5r.CompactSign=T2o});var K1u=b(l5r=>{"use strict";Object.defineProperty(l5r,"__esModule",{value:!0});l5r.GeneralSign=void 0;var v$d=c5r(),H1u=wl(),B2o=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},P2o=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new B2o(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new H1u.JWSInvalid("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new v$d.FlattenedSign(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...s}=await i.sign(n.key,n.options);if(r===0)t.payload=o;else if(t.payload!==o)throw new H1u.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(s)}return t}};l5r.GeneralSign=P2o});var f5r=b(p5r=>{"use strict";Object.defineProperty(p5r,"__esModule",{value:!0});p5r.ProduceJWT=void 0;var D2o=A2o(),x$d=JQ(),J1u=E2o(),R2o=class{constructor(t){if(!(0,x$d.default)(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:(0,D2o.default)(new Date)+(0,J1u.default)(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:(0,D2o.default)(new Date)+(0,J1u.default)(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:(0,D2o.default)(new Date)}:this._payload={...this._payload,iat:t},this}};p5r.ProduceJWT=R2o});var Y1u=b(d5r=>{"use strict";Object.defineProperty(d5r,"__esModule",{value:!0});d5r.SignJWT=void 0;var C$d=O2o(),w$d=wl(),S$d=QI(),T$d=f5r(),k2o=class extends T$d.ProduceJWT{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let i=new C$d.CompactSign(S$d.encoder.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new w$d.JWTInvalid("JWTs MUST NOT use unencoded payload");return i.sign(t,r)}};d5r.SignJWT=k2o});var X1u=b(m5r=>{"use strict";Object.defineProperty(m5r,"__esModule",{value:!0});m5r.EncryptJWT=void 0;var O$d=C2o(),B$d=QI(),P$d=f5r(),F2o=class extends P$d.ProduceJWT{setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new O$d.CompactEncrypt(B$d.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};m5r.EncryptJWT=F2o});var eTu=b(znt=>{"use strict";Object.defineProperty(znt,"__esModule",{value:!0});znt.calculateJwkThumbprintUri=znt.calculateJwkThumbprint=void 0;var D$d=kko(),R$d=kD(),Z1u=wl(),k$d=QI(),F$d=JQ(),Tve=(e,t)=>{if(typeof e!="string"||!e)throw new Z1u.JWKInvalid(`${t} missing or invalid`)};async function $1u(e,t){if(!(0,F$d.default)(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":Tve(e.crv,'"crv" (Curve) Parameter'),Tve(e.x,'"x" (X Coordinate) Parameter'),Tve(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Tve(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Tve(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Tve(e.e,'"e" (Exponent) Parameter'),Tve(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Tve(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new Z1u.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}let n=k$d.encoder.encode(JSON.stringify(r));return(0,R$d.encode)(await(0,D$d.default)(t,n))}znt.calculateJwkThumbprint=$1u;async function N$d(e,t){t??(t="sha256");let r=await $1u(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}znt.calculateJwkThumbprintUri=N$d});var rTu=b(h5r=>{"use strict";Object.defineProperty(h5r,"__esModule",{value:!0});h5r.EmbeddedJWK=void 0;var j$d=kVt(),Q$d=JQ(),tTu=wl();async function z$d(e,t){let r={...e,...t?.header};if(!(0,Q$d.default)(r.jwk))throw new tTu.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await(0,j$d.importJWK)({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new tTu.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}h5r.EmbeddedJWK=z$d});var N2o=b(Ove=>{"use strict";Object.defineProperty(Ove,"__esModule",{value:!0});Ove.createLocalJWKSet=Ove.LocalJWKSet=Ove.isJWKSLike=void 0;var M$d=kVt(),zVt=wl(),L$d=JQ();function V$d(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new zVt.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}function iTu(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(U$d)}Ove.isJWKSLike=iTu;function U$d(e){return(0,L$d.default)(e)}function _$d(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var g5r=class{constructor(t){if(this._cached=new WeakMap,!iTu(t))throw new zVt.JWKSInvalid("JSON Web Key Set malformed");this._jwks=_$d(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},o=V$d(n),s=this._jwks.keys.filter(u=>{let l=o===u.kty;if(l&&typeof i=="string"&&(l=i===u.kid),l&&typeof u.alg=="string"&&(l=n===u.alg),l&&typeof u.use=="string"&&(l=u.use==="sig"),l&&Array.isArray(u.key_ops)&&(l=u.key_ops.includes("verify")),l&&n==="EdDSA"&&(l=u.crv==="Ed25519"||u.crv==="Ed448"),l)switch(n){case"ES256":l=u.crv==="P-256";break;case"ES256K":l=u.crv==="secp256k1";break;case"ES384":l=u.crv==="P-384";break;case"ES512":l=u.crv==="P-521";break}return l}),{0:a,length:c}=s;if(c===0)throw new zVt.JWKSNoMatchingKey;if(c!==1){let u=new zVt.JWKSMultipleMatchingKeys,{_cached:l}=this;throw u[Symbol.asyncIterator]=async function*(){for(let p of s)try{yield await nTu(l,p,n)}catch{continue}},u}return nTu(this._cached,a,n)}};Ove.LocalJWKSet=g5r;async function nTu(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await(0,M$d.importJWK)({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new zVt.JWKSInvalid("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function q$d(e){let t=new g5r(e);return async function(r,n){return t.getKey(r,n)}}Ove.createLocalJWKSet=q$d});var aTu=b(Q2o=>{"use strict";Object.defineProperty(Q2o,"__esModule",{value:!0});var G$d=require("http"),W$d=require("https"),oTu=require("events"),j2o=wl(),sTu=QI(),H$d=async(e,t,r)=>{let n;switch(e.protocol){case"https:":n=W$d.get;break;case"http:":n=G$d.get;break;default:throw new TypeError("Unsupported URL protocol.")}let{agent:i,headers:o}=r,s=n(e.href,{agent:i,timeout:t,headers:o}),[a]=await Promise.race([(0,oTu.once)(s,"response"),(0,oTu.once)(s,"timeout")]);if(!a)throw s.destroy(),new j2o.JWKSTimeout;if(a.statusCode!==200)throw new j2o.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");let c=[];for await(let u of a)c.push(u);try{return JSON.parse(sTu.decoder.decode((0,sTu.concat)(...c)))}catch{throw new j2o.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};Q2o.default=H$d});var lTu=b(A5r=>{"use strict";Object.defineProperty(A5r,"__esModule",{value:!0});A5r.createRemoteJWKSet=void 0;var K$d=aTu(),cTu=wl(),uTu=N2o();function J$d(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var z2o=class extends uTu.LocalJWKSet{constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof cTu.JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&J$d()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=(0,K$d.default)(this._url,this._timeoutDuration,this._options).then(t=>{if(!(0,uTu.isJWKSLike)(t))throw new cTu.JWKSInvalid("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};function Y$d(e,t){let r=new z2o(e,t);return async function(n,i){return r.getKey(n,i)}}A5r.createRemoteJWKSet=Y$d});var pTu=b(b5r=>{"use strict";Object.defineProperty(b5r,"__esModule",{value:!0});b5r.UnsecuredJWT=void 0;var y5r=kD(),X$d=QI(),M2o=wl(),Z$d=n5r(),$$d=f5r(),L2o=class extends $$d.ProduceJWT{encode(){let t=y5r.encode(JSON.stringify({alg:"none"})),r=y5r.encode(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new M2o.JWTInvalid("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:s}=t.split(".");if(s!==3||o!=="")throw new M2o.JWTInvalid("Invalid Unsecured JWT");let a;try{if(a=JSON.parse(X$d.decoder.decode(y5r.decode(n))),a.alg!=="none")throw new Error}catch{throw new M2o.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,Z$d.default)(a,y5r.decode(i),r),header:a}}};b5r.UnsecuredJWT=L2o});var E5r=b(Mnt=>{"use strict";Object.defineProperty(Mnt,"__esModule",{value:!0});Mnt.decode=Mnt.encode=void 0;var fTu=kD();Mnt.encode=fTu.encode;Mnt.decode=fTu.decode});var dTu=b(I5r=>{"use strict";Object.defineProperty(I5r,"__esModule",{value:!0});I5r.decodeProtectedHeader=void 0;var eem=E5r(),tem=QI(),rem=JQ();function nem(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(tem.decoder.decode((0,eem.decode)(t)));if(!(0,rem.default)(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}I5r.decodeProtectedHeader=nem});var mTu=b(v5r=>{"use strict";Object.defineProperty(v5r,"__esModule",{value:!0});v5r.decodeJwt=void 0;var iem=E5r(),oem=QI(),sem=JQ(),ILe=wl();function aem(e){if(typeof e!="string")throw new ILe.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new ILe.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ILe.JWTInvalid("Invalid JWT");if(!t)throw new ILe.JWTInvalid("JWTs must contain a payload");let n;try{n=(0,iem.decode)(t)}catch{throw new ILe.JWTInvalid("Failed to base64url decode the payload")}let i;try{i=JSON.parse(oem.decoder.decode(n))}catch{throw new ILe.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,sem.default)(i))throw new ILe.JWTInvalid("Invalid JWT Claims Set");return i}v5r.decodeJwt=aem});var V2o=b(Lnt=>{"use strict";Object.defineProperty(Lnt,"__esModule",{value:!0});Lnt.generateKeyPair=Lnt.generateSecret=void 0;var gTu=require("crypto"),cem=require("util"),uem=IVt(),hTu=OVt(),MVt=wl(),mee=(0,cem.promisify)(gTu.generateKeyPair);async function lem(e,t){let r;switch(e){case"HS256":case"HS384":case"HS512":case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128KW":case"A192KW":case"A256KW":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new MVt.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return(0,gTu.createSecretKey)((0,uem.default)(new Uint8Array(r>>3)))}Lnt.generateSecret=lem;async function pem(e,t){var r,n;switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{let o=(r=t?.modulusLength)!==null&&r!==void 0?r:2048;if(typeof o!="number"||o<2048)throw new MVt.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");let s=await mee("rsa",{modulusLength:o,publicExponent:65537});return(0,hTu.setModulusLength)(s.privateKey,o),(0,hTu.setModulusLength)(s.publicKey,o),s}case"ES256":return mee("ec",{namedCurve:"P-256"});case"ES256K":return mee("ec",{namedCurve:"secp256k1"});case"ES384":return mee("ec",{namedCurve:"P-384"});case"ES512":return mee("ec",{namedCurve:"P-521"});case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return mee("ed25519");case"Ed448":return mee("ed448");default:throw new MVt.JOSENotSupported("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":let i=(n=t?.crv)!==null&&n!==void 0?n:"P-256";switch(i){case void 0:case"P-256":case"P-384":case"P-521":return mee("ec",{namedCurve:i});case"X25519":return mee("x25519");case"X448":return mee("x448");default:throw new MVt.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}default:throw new MVt.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}Lnt.generateKeyPair=pem});var ATu=b(x5r=>{"use strict";Object.defineProperty(x5r,"__esModule",{value:!0});x5r.generateKeyPair=void 0;var fem=V2o();async function dem(e,t){return(0,fem.generateKeyPair)(e,t)}x5r.generateKeyPair=dem});var yTu=b(C5r=>{"use strict";Object.defineProperty(C5r,"__esModule",{value:!0});C5r.generateSecret=void 0;var mem=V2o();async function hem(e,t){return(0,mem.generateSecret)(e,t)}C5r.generateSecret=hem});var bTu=b(U2o=>{"use strict";Object.defineProperty(U2o,"__esModule",{value:!0});U2o.default="node:crypto"});var ETu=b(_2o=>{"use strict";Object.defineProperty(_2o,"__esModule",{value:!0});var gem=bTu();_2o.default=gem.default});var G2o=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.cryptoRuntime=Mo.base64url=Mo.generateSecret=Mo.generateKeyPair=Mo.errors=Mo.decodeJwt=Mo.decodeProtectedHeader=Mo.importJWK=Mo.importX509=Mo.importPKCS8=Mo.importSPKI=Mo.exportJWK=Mo.exportSPKI=Mo.exportPKCS8=Mo.UnsecuredJWT=Mo.createRemoteJWKSet=Mo.createLocalJWKSet=Mo.EmbeddedJWK=Mo.calculateJwkThumbprintUri=Mo.calculateJwkThumbprint=Mo.EncryptJWT=Mo.SignJWT=Mo.GeneralSign=Mo.FlattenedSign=Mo.CompactSign=Mo.FlattenedEncrypt=Mo.CompactEncrypt=Mo.jwtDecrypt=Mo.jwtVerify=Mo.generalVerify=Mo.flattenedVerify=Mo.compactVerify=Mo.GeneralEncrypt=Mo.generalDecrypt=Mo.flattenedDecrypt=Mo.compactDecrypt=void 0;var Aem=LFo();Object.defineProperty(Mo,"compactDecrypt",{enumerable:!0,get:function(){return Aem.compactDecrypt}});var yem=U_r();Object.defineProperty(Mo,"flattenedDecrypt",{enumerable:!0,get:function(){return yem.flattenedDecrypt}});var bem=x1u();Object.defineProperty(Mo,"generalDecrypt",{enumerable:!0,get:function(){return bem.generalDecrypt}});var Eem=P1u();Object.defineProperty(Mo,"GeneralEncrypt",{enumerable:!0,get:function(){return Eem.GeneralEncrypt}});var Iem=m2o();Object.defineProperty(Mo,"compactVerify",{enumerable:!0,get:function(){return Iem.compactVerify}});var vem=e5r();Object.defineProperty(Mo,"flattenedVerify",{enumerable:!0,get:function(){return vem.flattenedVerify}});var xem=L1u();Object.defineProperty(Mo,"generalVerify",{enumerable:!0,get:function(){return xem.generalVerify}});var Cem=G1u();Object.defineProperty(Mo,"jwtVerify",{enumerable:!0,get:function(){return Cem.jwtVerify}});var wem=W1u();Object.defineProperty(Mo,"jwtDecrypt",{enumerable:!0,get:function(){return wem.jwtDecrypt}});var Sem=C2o();Object.defineProperty(Mo,"CompactEncrypt",{enumerable:!0,get:function(){return Sem.CompactEncrypt}});var Tem=J_r();Object.defineProperty(Mo,"FlattenedEncrypt",{enumerable:!0,get:function(){return Tem.FlattenedEncrypt}});var Oem=O2o();Object.defineProperty(Mo,"CompactSign",{enumerable:!0,get:function(){return Oem.CompactSign}});var Bem=c5r();Object.defineProperty(Mo,"FlattenedSign",{enumerable:!0,get:function(){return Bem.FlattenedSign}});var Pem=K1u();Object.defineProperty(Mo,"GeneralSign",{enumerable:!0,get:function(){return Pem.GeneralSign}});var Dem=Y1u();Object.defineProperty(Mo,"SignJWT",{enumerable:!0,get:function(){return Dem.SignJWT}});var Rem=X1u();Object.defineProperty(Mo,"EncryptJWT",{enumerable:!0,get:function(){return Rem.EncryptJWT}});var ITu=eTu();Object.defineProperty(Mo,"calculateJwkThumbprint",{enumerable:!0,get:function(){return ITu.calculateJwkThumbprint}});Object.defineProperty(Mo,"calculateJwkThumbprintUri",{enumerable:!0,get:function(){return ITu.calculateJwkThumbprintUri}});var kem=rTu();Object.defineProperty(Mo,"EmbeddedJWK",{enumerable:!0,get:function(){return kem.EmbeddedJWK}});var Fem=N2o();Object.defineProperty(Mo,"createLocalJWKSet",{enumerable:!0,get:function(){return Fem.createLocalJWKSet}});var Nem=lTu();Object.defineProperty(Mo,"createRemoteJWKSet",{enumerable:!0,get:function(){return Nem.createRemoteJWKSet}});var jem=pTu();Object.defineProperty(Mo,"UnsecuredJWT",{enumerable:!0,get:function(){return jem.UnsecuredJWT}});var q2o=GFo();Object.defineProperty(Mo,"exportPKCS8",{enumerable:!0,get:function(){return q2o.exportPKCS8}});Object.defineProperty(Mo,"exportSPKI",{enumerable:!0,get:function(){return q2o.exportSPKI}});Object.defineProperty(Mo,"exportJWK",{enumerable:!0,get:function(){return q2o.exportJWK}});var w5r=kVt();Object.defineProperty(Mo,"importSPKI",{enumerable:!0,get:function(){return w5r.importSPKI}});Object.defineProperty(Mo,"importPKCS8",{enumerable:!0,get:function(){return w5r.importPKCS8}});Object.defineProperty(Mo,"importX509",{enumerable:!0,get:function(){return w5r.importX509}});Object.defineProperty(Mo,"importJWK",{enumerable:!0,get:function(){return w5r.importJWK}});var Qem=dTu();Object.defineProperty(Mo,"decodeProtectedHeader",{enumerable:!0,get:function(){return Qem.decodeProtectedHeader}});var zem=mTu();Object.defineProperty(Mo,"decodeJwt",{enumerable:!0,get:function(){return zem.decodeJwt}});Mo.errors=wl();var Mem=ATu();Object.defineProperty(Mo,"generateKeyPair",{enumerable:!0,get:function(){return Mem.generateKeyPair}});var Lem=yTu();Object.defineProperty(Mo,"generateSecret",{enumerable:!0,get:function(){return Lem.generateSecret}});Mo.base64url=E5r();var Vem=ETu();Object.defineProperty(Mo,"cryptoRuntime",{enumerable:!0,get:function(){return Vem.default}})});var T5r=b((bwI,vTu)=>{"use strict";function S5r(e){Error.call(this,e),Error.captureStackTrace(this,this.constructor),this.name="JwksError",this.message=e}S5r.prototype=Object.create(Error.prototype);S5r.prototype.constructor=S5r;vTu.exports=S5r});var W2o=b((EwI,CTu)=>{"use strict";var xTu=G2o(),Uem=T5r();function _em(e){if(e.alg)return e.alg;if(e.kty==="RSA")return"RS256";if(e.kty==="EC")switch(e.crv){case"P-256":return"ES256";case"secp256k1":return"ES256K";case"P-384":return"ES384";case"P-521":return"ES512"}if(e.kty==="OKP")switch(e.crv){case"Ed25519":case"Ed448":return"EdDSA"}throw new Uem("Unsupported JWK")}async function qem(e){let t=[];e=e.filter(({use:r})=>r==="sig"||r===void 0).filter(({kty:r})=>r==="RSA"||r==="EC"||r==="OKP");for(let r of e)try{let n=await xTu.importJWK({...r,ext:!0},_em(r));if(n.type!=="public")continue;let i;if(n[Symbol.toStringTag]==="CryptoKey"){let o=await xTu.exportSPKI(n);i=()=>o}else i=()=>n.export({format:"pem",type:"spki"});t.push({get publicKey(){return i()},get rsaPublicKey(){return i()},getPublicKey(){return i()},...typeof r.kid=="string"&&r.kid?{kid:r.kid}:void 0,...typeof r.alg=="string"&&r.alg?{alg:r.alg}:void 0})}catch{continue}return t}CTu.exports={retrieveSigningKeys:qem}});var H2o=b((IwI,wTu)=>{"use strict";function O5r(e){Error.call(this,e),Error.captureStackTrace(this,this.constructor),this.name="ArgumentError",this.message=e}O5r.prototype=Object.create(Error.prototype);O5r.prototype.constructor=O5r;wTu.exports=O5r});var TTu=b((vwI,STu)=>{"use strict";var Gem=require("http"),Wem=require("https"),Hem=H2o();STu.exports.default=e=>e.fetcher?e.fetcher(e.uri):new Promise((t,r)=>{let n;try{n=new URL(e.uri)}catch{throw new Hem("Invalid JWKS URI: The provided URI is not a valid URL.")}let{hostname:i,port:o,protocol:s,pathname:a,search:c}=n,u=a+c,l={hostname:i,path:u,port:o,method:"GET",...e.headers&&{headers:{...e.headers}},...e.timeout&&{timeout:e.timeout},...e.agent&&{agent:e.agent}},d=(s==="https:"?Wem:Gem).request(l,f=>{let m="";f.setEncoding("utf8"),f.on("data",g=>{m+=g}),f.on("end",()=>{if(f.statusCode<200||f.statusCode>=300){let g=f.body&&(f.body.message||f.body)||f.statusMessage||`Http Error ${f.statusCode}`;r({errorMsg:g})}else try{t(m&&JSON.parse(m))}catch(g){r(g)}})});d.on("timeout",()=>d.destroy()).on("error",f=>r(f)).end()})});var BTu=b((xwI,OTu)=>{"use strict";OTu.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let t=this.head;t;t=t.next)yield t.value}}});var DTu=b((CwI,PTu)=>{"use strict";PTu.exports=eh;eh.Node=vLe;eh.create=eh;function eh(e){var t=this;if(t instanceof eh||(t=new eh),t.tail=null,t.head=null,t.length=0,e&&typeof e.forEach=="function")e.forEach(function(i){t.push(i)});else if(arguments.length>0)for(var r=0,n=arguments.length;r<n;r++)t.push(arguments[r]);return t}eh.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t};eh.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}};eh.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}};eh.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)Jem(this,arguments[e]);return this.length};eh.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)Yem(this,arguments[e]);return this.length};eh.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}};eh.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}};eh.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,n=0;r!==null;n++)e.call(t,r.value,n,this),r=r.next};eh.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,n=this.length-1;r!==null;n--)e.call(t,r.value,n,this),r=r.prev};eh.prototype.get=function(e){for(var t=0,r=this.head;r!==null&&t<e;t++)r=r.next;if(t===e&&r!==null)return r.value};eh.prototype.getReverse=function(e){for(var t=0,r=this.tail;r!==null&&t<e;t++)r=r.prev;if(t===e&&r!==null)return r.value};eh.prototype.map=function(e,t){t=t||this;for(var r=new eh,n=this.head;n!==null;)r.push(e.call(t,n.value,this)),n=n.next;return r};eh.prototype.mapReverse=function(e,t){t=t||this;for(var r=new eh,n=this.tail;n!==null;)r.push(e.call(t,n.value,this)),n=n.prev;return r};eh.prototype.reduce=function(e,t){var r,n=this.head;if(arguments.length>1)r=t;else if(this.head)n=this.head.next,r=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var i=0;n!==null;i++)r=e(r,n.value,i),n=n.next;return r};eh.prototype.reduceReverse=function(e,t){var r,n=this.tail;if(arguments.length>1)r=t;else if(this.tail)n=this.tail.prev,r=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var i=this.length-1;n!==null;i--)r=e(r,n.value,i),n=n.prev;return r};eh.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;r!==null;t++)e[t]=r.value,r=r.next;return e};eh.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;r!==null;t++)e[t]=r.value,r=r.prev;return e};eh.prototype.slice=function(e,t){t=t||this.length,t<0&&(t+=this.length),e=e||0,e<0&&(e+=this.length);var r=new eh;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var n=0,i=this.head;i!==null&&n<e;n++)i=i.next;for(;i!==null&&n<t;n++,i=i.next)r.push(i.value);return r};eh.prototype.sliceReverse=function(e,t){t=t||this.length,t<0&&(t+=this.length),e=e||0,e<0&&(e+=this.length);var r=new eh;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var n=this.length,i=this.tail;i!==null&&n>t;n--)i=i.prev;for(;i!==null&&n>e;n--,i=i.prev)r.push(i.value);return r};eh.prototype.splice=function(e,t,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var n=0,i=this.head;i!==null&&n<e;n++)i=i.next;for(var o=[],n=0;i&&n<t;n++)o.push(i.value),i=this.removeNode(i);i===null&&(i=this.tail),i!==this.head&&i!==this.tail&&(i=i.prev);for(var n=0;n<r.length;n++)i=Kem(this,i,r[n]);return o};eh.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;r!==null;r=r.prev){var n=r.prev;r.prev=r.next,r.next=n}return this.head=t,this.tail=e,this};function Kem(e,t,r){var n=t===e.head?new vLe(r,null,t,e):new vLe(r,t,t.next,e);return n.next===null&&(e.tail=n),n.prev===null&&(e.head=n),e.length++,n}function Jem(e,t){e.tail=new vLe(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function Yem(e,t){e.head=new vLe(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function vLe(e,t,r,n){if(!(this instanceof vLe))return new vLe(e,t,r,n);this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}try{BTu()(eh)}catch{}});var Z2o=b((wwI,NTu)=>{"use strict";var Xem=DTu(),xLe=Symbol("max"),xfe=Symbol("length"),Vnt=Symbol("lengthCalculator"),VVt=Symbol("allowStale"),CLe=Symbol("maxAge"),vfe=Symbol("dispose"),RTu=Symbol("noDisposeOnSet"),q1=Symbol("lruList"),aH=Symbol("cache"),FTu=Symbol("updateAgeOnGet"),K2o=()=>1,Y2o=class{constructor(t){if(typeof t=="number"&&(t={max:t}),t||(t={}),t.max&&(typeof t.max!="number"||t.max<0))throw new TypeError("max must be a non-negative number");let r=this[xLe]=t.max||1/0,n=t.length||K2o;if(this[Vnt]=typeof n!="function"?K2o:n,this[VVt]=t.stale||!1,t.maxAge&&typeof t.maxAge!="number")throw new TypeError("maxAge must be a number");this[CLe]=t.maxAge||0,this[vfe]=t.dispose,this[RTu]=t.noDisposeOnSet||!1,this[FTu]=t.updateAgeOnGet||!1,this.reset()}set max(t){if(typeof t!="number"||t<0)throw new TypeError("max must be a non-negative number");this[xLe]=t||1/0,LVt(this)}get max(){return this[xLe]}set allowStale(t){this[VVt]=!!t}get allowStale(){return this[VVt]}set maxAge(t){if(typeof t!="number")throw new TypeError("maxAge must be a non-negative number");this[CLe]=t,LVt(this)}get maxAge(){return this[CLe]}set lengthCalculator(t){typeof t!="function"&&(t=K2o),t!==this[Vnt]&&(this[Vnt]=t,this[xfe]=0,this[q1].forEach(r=>{r.length=this[Vnt](r.value,r.key),this[xfe]+=r.length})),LVt(this)}get lengthCalculator(){return this[Vnt]}get length(){return this[xfe]}get itemCount(){return this[q1].length}rforEach(t,r){r=r||this;for(let n=this[q1].tail;n!==null;){let i=n.prev;kTu(this,t,n,r),n=i}}forEach(t,r){r=r||this;for(let n=this[q1].head;n!==null;){let i=n.next;kTu(this,t,n,r),n=i}}keys(){return this[q1].toArray().map(t=>t.key)}values(){return this[q1].toArray().map(t=>t.value)}reset(){this[vfe]&&this[q1]&&this[q1].length&&this[q1].forEach(t=>this[vfe](t.key,t.value)),this[aH]=new Map,this[q1]=new Xem,this[xfe]=0}dump(){return this[q1].map(t=>B5r(this,t)?!1:{k:t.key,v:t.value,e:t.now+(t.maxAge||0)}).toArray().filter(t=>t)}dumpLru(){return this[q1]}set(t,r,n){if(n=n||this[CLe],n&&typeof n!="number")throw new TypeError("maxAge must be a number");let i=n?Date.now():0,o=this[Vnt](r,t);if(this[aH].has(t)){if(o>this[xLe])return Unt(this,this[aH].get(t)),!1;let c=this[aH].get(t).value;return this[vfe]&&(this[RTu]||this[vfe](t,c.value)),c.now=i,c.maxAge=n,c.value=r,this[xfe]+=o-c.length,c.length=o,this.get(t),LVt(this),!0}let s=new X2o(t,r,o,i,n);return s.length>this[xLe]?(this[vfe]&&this[vfe](t,r),!1):(this[xfe]+=s.length,this[q1].unshift(s),this[aH].set(t,this[q1].head),LVt(this),!0)}has(t){if(!this[aH].has(t))return!1;let r=this[aH].get(t).value;return!B5r(this,r)}get(t){return J2o(this,t,!0)}peek(t){return J2o(this,t,!1)}pop(){let t=this[q1].tail;return t?(Unt(this,t),t.value):null}del(t){Unt(this,this[aH].get(t))}load(t){this.reset();let r=Date.now();for(let n=t.length-1;n>=0;n--){let i=t[n],o=i.e||0;if(o===0)this.set(i.k,i.v);else{let s=o-r;s>0&&this.set(i.k,i.v,s)}}}prune(){this[aH].forEach((t,r)=>J2o(this,r,!1))}},J2o=(e,t,r)=>{let n=e[aH].get(t);if(n){let i=n.value;if(B5r(e,i)){if(Unt(e,n),!e[VVt])return}else r&&(e[FTu]&&(n.value.now=Date.now()),e[q1].unshiftNode(n));return i.value}},B5r=(e,t)=>{if(!t||!t.maxAge&&!e[CLe])return!1;let r=Date.now()-t.now;return t.maxAge?r>t.maxAge:e[CLe]&&r>e[CLe]},LVt=e=>{if(e[xfe]>e[xLe])for(let t=e[q1].tail;e[xfe]>e[xLe]&&t!==null;){let r=t.prev;Unt(e,t),t=r}},Unt=(e,t)=>{if(t){let r=t.value;e[vfe]&&e[vfe](r.key,r.value),e[xfe]-=r.length,e[aH].delete(r.key),e[q1].removeNode(t)}},X2o=class{constructor(t,r,n,i,o){this.key=t,this.value=r,this.length=n,this.now=i,this.maxAge=o||0}},kTu=(e,t,r,n)=>{let i=r.value;B5r(e,i)&&(Unt(e,r),e[VVt]||(i=void 0)),i&&t.call(n,i.value,i.key,e)};NTu.exports=Y2o});var dNo=b((UVt,_nt)=>{"use strict";var Zem=200,HTu="__lodash_hash_undefined__",KTu=9007199254740991,sNo="[object Arguments]",$em="[object Array]",JTu="[object Boolean]",YTu="[object Date]",etm="[object Error]",aNo="[object Function]",XTu="[object GeneratorFunction]",P5r="[object Map]",ZTu="[object Number]",cNo="[object Object]",jTu="[object Promise]",$Tu="[object RegExp]",D5r="[object Set]",eOu="[object String]",tOu="[object Symbol]",eNo="[object WeakMap]",rOu="[object ArrayBuffer]",R5r="[object DataView]",nOu="[object Float32Array]",iOu="[object Float64Array]",oOu="[object Int8Array]",sOu="[object Int16Array]",aOu="[object Int32Array]",cOu="[object Uint8Array]",uOu="[object Uint8ClampedArray]",lOu="[object Uint16Array]",pOu="[object Uint32Array]",ttm=/[\\^$.*+?()[\]{}|]/g,rtm=/\w*$/,ntm=/^\[object .+?Constructor\]$/,itm=/^(?:0|[1-9]\d*)$/,wy={};wy[sNo]=wy[$em]=wy[rOu]=wy[R5r]=wy[JTu]=wy[YTu]=wy[nOu]=wy[iOu]=wy[oOu]=wy[sOu]=wy[aOu]=wy[P5r]=wy[ZTu]=wy[cNo]=wy[$Tu]=wy[D5r]=wy[eOu]=wy[tOu]=wy[cOu]=wy[uOu]=wy[lOu]=wy[pOu]=!0;wy[etm]=wy[aNo]=wy[eNo]=!1;var otm=typeof global=="object"&&global&&global.Object===Object&&global,stm=typeof self=="object"&&self&&self.Object===Object&&self,Cfe=otm||stm||Function("return this")(),fOu=typeof UVt=="object"&&UVt&&!UVt.nodeType&&UVt,QTu=fOu&&typeof _nt=="object"&&_nt&&!_nt.nodeType&&_nt,atm=QTu&&QTu.exports===fOu;function ctm(e,t){return e.set(t[0],t[1]),e}function utm(e,t){return e.add(t),e}function ltm(e,t){for(var r=-1,n=e?e.length:0;++r<n&&t(e[r],r,e)!==!1;);return e}function ptm(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}function dOu(e,t,r,n){var i=-1,o=e?e.length:0;for(n&&o&&(r=e[++i]);++i<o;)r=t(r,e[i],i,e);return r}function ftm(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function dtm(e,t){return e?.[t]}function mOu(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}function zTu(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}function uNo(e,t){return function(r){return e(t(r))}}function MTu(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var mtm=Array.prototype,htm=Function.prototype,k5r=Object.prototype,$2o=Cfe["__core-js_shared__"],LTu=(function(){var e=/[^.]+$/.exec($2o&&$2o.keys&&$2o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})(),hOu=htm.toString,Bve=k5r.hasOwnProperty,F5r=k5r.toString,gtm=RegExp("^"+hOu.call(Bve).replace(ttm,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),VTu=atm?Cfe.Buffer:void 0,UTu=Cfe.Symbol,_Tu=Cfe.Uint8Array,Atm=uNo(Object.getPrototypeOf,Object),ytm=Object.create,btm=k5r.propertyIsEnumerable,Etm=mtm.splice,qTu=Object.getOwnPropertySymbols,Itm=VTu?VTu.isBuffer:void 0,vtm=uNo(Object.keys,Object),tNo=Wnt(Cfe,"DataView"),_Vt=Wnt(Cfe,"Map"),rNo=Wnt(Cfe,"Promise"),nNo=Wnt(Cfe,"Set"),iNo=Wnt(Cfe,"WeakMap"),qVt=Wnt(Object,"create"),xtm=TLe(tNo),Ctm=TLe(_Vt),wtm=TLe(rNo),Stm=TLe(nNo),Ttm=TLe(iNo),GTu=UTu?UTu.prototype:void 0,WTu=GTu?GTu.valueOf:void 0;function SLe(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Otm(){this.__data__=qVt?qVt(null):{}}function Btm(e){return this.has(e)&&delete this.__data__[e]}function Ptm(e){var t=this.__data__;if(qVt){var r=t[e];return r===HTu?void 0:r}return Bve.call(t,e)?t[e]:void 0}function Dtm(e){var t=this.__data__;return qVt?t[e]!==void 0:Bve.call(t,e)}function Rtm(e,t){var r=this.__data__;return r[e]=qVt&&t===void 0?HTu:t,this}SLe.prototype.clear=Otm;SLe.prototype.delete=Btm;SLe.prototype.get=Ptm;SLe.prototype.has=Dtm;SLe.prototype.set=Rtm;function wfe(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function ktm(){this.__data__=[]}function Ftm(e){var t=this.__data__,r=N5r(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Etm.call(t,r,1),!0}function Ntm(e){var t=this.__data__,r=N5r(t,e);return r<0?void 0:t[r][1]}function jtm(e){return N5r(this.__data__,e)>-1}function Qtm(e,t){var r=this.__data__,n=N5r(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}wfe.prototype.clear=ktm;wfe.prototype.delete=Ftm;wfe.prototype.get=Ntm;wfe.prototype.has=jtm;wfe.prototype.set=Qtm;function qnt(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function ztm(){this.__data__={hash:new SLe,map:new(_Vt||wfe),string:new SLe}}function Mtm(e){return j5r(this,e).delete(e)}function Ltm(e){return j5r(this,e).get(e)}function Vtm(e){return j5r(this,e).has(e)}function Utm(e,t){return j5r(this,e).set(e,t),this}qnt.prototype.clear=ztm;qnt.prototype.delete=Mtm;qnt.prototype.get=Ltm;qnt.prototype.has=Vtm;qnt.prototype.set=Utm;function Gnt(e){this.__data__=new wfe(e)}function _tm(){this.__data__=new wfe}function qtm(e){return this.__data__.delete(e)}function Gtm(e){return this.__data__.get(e)}function Wtm(e){return this.__data__.has(e)}function Htm(e,t){var r=this.__data__;if(r instanceof wfe){var n=r.__data__;if(!_Vt||n.length<Zem-1)return n.push([e,t]),this;r=this.__data__=new qnt(n)}return r.set(e,t),this}Gnt.prototype.clear=_tm;Gnt.prototype.delete=qtm;Gnt.prototype.get=Gtm;Gnt.prototype.has=Wtm;Gnt.prototype.set=Htm;function Ktm(e,t){var r=pNo(e)||yrm(e)?ftm(e.length,String):[],n=r.length,i=!!n;for(var o in e)(t||Bve.call(e,o))&&!(i&&(o=="length"||mrm(o,n)))&&r.push(o);return r}function gOu(e,t,r){var n=e[t];(!(Bve.call(e,t)&&EOu(n,r))||r===void 0&&!(t in e))&&(e[t]=r)}function N5r(e,t){for(var r=e.length;r--;)if(EOu(e[r][0],t))return r;return-1}function Jtm(e,t){return e&&AOu(t,fNo(t),e)}function oNo(e,t,r,n,i,o,s){var a;if(n&&(a=o?n(e,i,o,s):n(e)),a!==void 0)return a;if(!Q5r(e))return e;var c=pNo(e);if(c){if(a=prm(e),!t)return crm(e,a)}else{var u=wLe(e),l=u==aNo||u==XTu;if(Erm(e))return trm(e,t);if(u==cNo||u==sNo||l&&!o){if(mOu(e))return o?e:{};if(a=frm(l?{}:e),!t)return urm(e,Jtm(a,e))}else{if(!wy[u])return o?e:{};a=drm(e,u,oNo,t)}}s||(s=new Gnt);var p=s.get(e);if(p)return p;if(s.set(e,a),!c)var d=r?lrm(e):fNo(e);return ltm(d||e,function(f,m){d&&(m=f,f=e[m]),gOu(a,m,oNo(f,t,r,n,m,e,s))}),a}function Ytm(e){return Q5r(e)?ytm(e):{}}function Xtm(e,t,r){var n=t(e);return pNo(e)?n:ptm(n,r(e))}function Ztm(e){return F5r.call(e)}function $tm(e){if(!Q5r(e)||grm(e))return!1;var t=vOu(e)||mOu(e)?gtm:ntm;return t.test(TLe(e))}function erm(e){if(!bOu(e))return vtm(e);var t=[];for(var r in Object(e))Bve.call(e,r)&&r!="constructor"&&t.push(r);return t}function trm(e,t){if(t)return e.slice();var r=new e.constructor(e.length);return e.copy(r),r}function lNo(e){var t=new e.constructor(e.byteLength);return new _Tu(t).set(new _Tu(e)),t}function rrm(e,t){var r=t?lNo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}function nrm(e,t,r){var n=t?r(zTu(e),!0):zTu(e);return dOu(n,ctm,new e.constructor)}function irm(e){var t=new e.constructor(e.source,rtm.exec(e));return t.lastIndex=e.lastIndex,t}function orm(e,t,r){var n=t?r(MTu(e),!0):MTu(e);return dOu(n,utm,new e.constructor)}function srm(e){return WTu?Object(WTu.call(e)):{}}function arm(e,t){var r=t?lNo(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function crm(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}function AOu(e,t,r,n){r||(r={});for(var i=-1,o=t.length;++i<o;){var s=t[i],a=n?n(r[s],e[s],s,r,e):void 0;gOu(r,s,a===void 0?e[s]:a)}return r}function urm(e,t){return AOu(e,yOu(e),t)}function lrm(e){return Xtm(e,fNo,yOu)}function j5r(e,t){var r=e.__data__;return hrm(t)?r[typeof t=="string"?"string":"hash"]:r.map}function Wnt(e,t){var r=dtm(e,t);return $tm(r)?r:void 0}var yOu=qTu?uNo(qTu,Object):xrm,wLe=Ztm;(tNo&&wLe(new tNo(new ArrayBuffer(1)))!=R5r||_Vt&&wLe(new _Vt)!=P5r||rNo&&wLe(rNo.resolve())!=jTu||nNo&&wLe(new nNo)!=D5r||iNo&&wLe(new iNo)!=eNo)&&(wLe=function(e){var t=F5r.call(e),r=t==cNo?e.constructor:void 0,n=r?TLe(r):void 0;if(n)switch(n){case xtm:return R5r;case Ctm:return P5r;case wtm:return jTu;case Stm:return D5r;case Ttm:return eNo}return t});function prm(e){var t=e.length,r=e.constructor(t);return t&&typeof e[0]=="string"&&Bve.call(e,"index")&&(r.index=e.index,r.input=e.input),r}function frm(e){return typeof e.constructor=="function"&&!bOu(e)?Ytm(Atm(e)):{}}function drm(e,t,r,n){var i=e.constructor;switch(t){case rOu:return lNo(e);case JTu:case YTu:return new i(+e);case R5r:return rrm(e,n);case nOu:case iOu:case oOu:case sOu:case aOu:case cOu:case uOu:case lOu:case pOu:return arm(e,n);case P5r:return nrm(e,n,r);case ZTu:case eOu:return new i(e);case $Tu:return irm(e);case D5r:return orm(e,n,r);case tOu:return srm(e)}}function mrm(e,t){return t=t??KTu,!!t&&(typeof e=="number"||itm.test(e))&&e>-1&&e%1==0&&e<t}function hrm(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function grm(e){return!!LTu&&LTu in e}function bOu(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||k5r;return e===r}function TLe(e){if(e!=null){try{return hOu.call(e)}catch{}try{return e+""}catch{}}return""}function Arm(e){return oNo(e,!0,!0)}function EOu(e,t){return e===t||e!==e&&t!==t}function yrm(e){return brm(e)&&Bve.call(e,"callee")&&(!btm.call(e,"callee")||F5r.call(e)==sNo)}var pNo=Array.isArray;function IOu(e){return e!=null&&Irm(e.length)&&!vOu(e)}function brm(e){return vrm(e)&&IOu(e)}var Erm=Itm||Crm;function vOu(e){var t=Q5r(e)?F5r.call(e):"";return t==aNo||t==XTu}function Irm(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=KTu}function Q5r(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function vrm(e){return!!e&&typeof e=="object"}function fNo(e){return IOu(e)?Ktm(e):erm(e)}function xrm(){return[]}function Crm(){return!1}_nt.exports=Arm});var mNo=b(z5r=>{"use strict";Object.defineProperty(z5r,"__esModule",{value:!0});z5r.deepFreeze=void 0;function xOu(e){return e&&(Object.freeze(e),Object.getOwnPropertyNames(e).forEach(function(t){e.hasOwnProperty(t)&&e[t]!==null&&(typeof e[t]=="object"||typeof e[t]=="function")&&e[t].constructor!==Buffer&&!Object.isFrozen(e[t])&&xOu(e[t])})),e}z5r.deepFreeze=xOu});var TOu=b(gee=>{"use strict";var wrm=gee&&gee.__read||function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},hee=gee&&gee.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(wrm(arguments[t]));return e},SOu=gee&&gee.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(gee,"__esModule",{value:!0});gee.syncMemoizer=void 0;var Srm=SOu(Z2o()),Trm=require("events"),COu=SOu(dNo()),wOu=mNo();function Orm(e){var t=new Srm.default(e),r=e.load,n=e.hash,i=e.bypass,o=e.itemMaxAge,s=e.freeze,a=e.clone,c=new Trm.EventEmitter,u=Object.assign({del:l,reset:function(){return t.reset()},keys:t.keys.bind(t),on:c.on.bind(c),once:c.once.bind(c)},e);if(e.disable)return Object.assign(r,u);function l(){var g=n.apply(void 0,hee(arguments));t.del(g)}function p(g){for(var A=[],y=1;y<arguments.length;y++)A[y-1]=arguments[y];c.emit.apply(c,hee([g],A))}function d(g){return g&&g.then&&typeof g.then=="function"}function f(g){var A=g;return a&&(d(A)?A=A.then(COu.default):A=COu.default(A)),s&&(d(A)?A=A.then(wOu.deepFreeze):wOu.deepFreeze(A)),A}var m=function(){for(var g=[],A=0;A<arguments.length;A++)g[A]=arguments[A];if(i&&i.apply(void 0,hee(g)))return p.apply(void 0,hee(["miss"],g)),r.apply(void 0,hee(g));var y=n.apply(void 0,hee(g)),E=t.get(y);if(E)return p.apply(void 0,hee(["hit"],g)),f(E);p.apply(void 0,hee(["miss"],g));var x=r.apply(void 0,hee(g));return o?t.set(y,x,o.apply(void 0,hee(g.concat([x])))):t.set(y,x),f(x)};return Object.assign(m,u)}gee.syncMemoizer=Orm});var POu=b(P_=>{"use strict";var Brm=P_&&P_.__read||function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},YQ=P_&&P_.__spread||function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Brm(arguments[t]));return e},Prm=P_&&P_.__values||function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},OOu=P_&&P_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(P_,"__esModule",{value:!0});P_.asyncMemoizer=void 0;var Drm=OOu(Z2o()),Rrm=require("events"),krm=OOu(dNo()),Frm=mNo(),Nrm=TOu();function BOu(e){var t=new Drm.default(e),r=e.load,n=e.hash,i=e.bypass,o=e.itemMaxAge,s=e.freeze,a=e.clone,c=e.queueMaxAge||1e3,u=new Map,l=new Rrm.EventEmitter,p=Object.assign({del:d,reset:function(){return t.reset()},keys:t.keys.bind(t),on:l.on.bind(l),once:l.once.bind(l)},e);if(e.disable)return Object.assign(r,p);function d(){for(var y=[],E=0;E<arguments.length;E++)y[E]=arguments[E];var x=n.apply(void 0,YQ(y));t.del(x)}function f(y,E,x){s&&x.forEach(Frm.deepFreeze),o?t.set(y,x,o.apply(void 0,YQ(E.concat(x)))):t.set(y,x)}function m(y,E){var x,I;try{for(var C=Prm(y),T=C.next();!T.done;T=C.next()){var P=T.value;a?setImmediate.apply(void 0,YQ([P],E.map(krm.default))):setImmediate.apply(void 0,YQ([P],E))}}catch(D){x={error:D}}finally{try{T&&!T.done&&(I=C.return)&&I.call(C)}finally{if(x)throw x.error}}}function g(y){for(var E=[],x=1;x<arguments.length;x++)E[x-1]=arguments[x];l.emit.apply(l,YQ([y],E))}function A(){for(var y=[],E=0;E<arguments.length;E++)y[E]=arguments[E];var x=y.slice(0,-1),I=y.slice(-1).pop(),C;if(i&&i.apply(void 0,YQ(x)))return g.apply(void 0,YQ(["miss"],x)),r.apply(void 0,YQ(y));x.length===0&&!n?C="_":C=n.apply(void 0,YQ(x));var T=t.get(C);if(T)return g.apply(void 0,YQ(["hit"],x)),m([I],[null].concat(T));var P=u.get(C);if(P&&P.expiresAt>Date.now()){P.queue.push(I),g.apply(void 0,YQ(["queue"],x));return}g.apply(void 0,YQ(["miss"],x));var D=Date.now(),S=[I];u.set(C,{queue:S,expiresAt:D+c});var z=function(){for(var K=[],Y=0;Y<arguments.length;Y++)K[Y]=arguments[Y];var $=K[0];$||f(C,x,K.slice(1)),u.delete(C),g.apply(void 0,YQ(["loaded",Date.now()-D],x)),m(S,K)};r.apply(void 0,YQ(x,[z]))}return Object.assign(A,p)}P_.asyncMemoizer=BOu;BOu.sync=Nrm.syncMemoizer});var ROu=b((BwI,DOu)=>{"use strict";var jrm=POu();DOu.exports=jrm.asyncMemoizer});var FOu=b((PwI,kOu)=>{"use strict";var Qrm=TA()("jwks"),zrm=ROu(),{promisify:Mrm,callbackify:Lrm}=require("util");function Vrm(e,{cacheMaxEntries:t=5,cacheMaxAge:r=6e5}){return Qrm(`Configured caching of signing keys. Max: ${t} / Age: ${r}`),Mrm(zrm({hash:n=>n,load:Lrm(e.getSigningKey.bind(e)),maxAge:r,max:t}))}kOu.exports.default=Vrm});var hNo=b((DwI,jOu)=>{"use strict";var NOu=function(e,t,r,n){if(this.bucketSize=e,this.tokensPerInterval=t,typeof r=="string")switch(r){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=6e4;break;case"hr":case"hour":this.interval=36e5;break;case"day":this.interval=864e5;break;default:throw new Error("Invaid interval "+r)}else this.interval=r;this.parentBucket=n,this.content=0,this.lastDrip=+new Date};NOu.prototype={bucketSize:1,tokensPerInterval:1,interval:1e3,parentBucket:null,content:0,lastDrip:0,removeTokens:function(e,t){var r=this;if(!this.bucketSize)return process.nextTick(t.bind(null,null,e,Number.POSITIVE_INFINITY)),!0;if(e>this.bucketSize)return process.nextTick(t.bind(null,"Requested tokens "+e+" exceeds bucket size "+this.bucketSize,null)),!1;if(this.drip(),e>this.content)return n();if(this.parentBucket)return this.parentBucket.removeTokens(e,function(i,o){if(i)return t(i,null);if(e>r.content)return n();r.content-=e,t(null,Math.min(o,r.content))});return this.content-=e,process.nextTick(t.bind(null,null,this.content)),!0;function n(){var i=Math.ceil((e-r.content)*(r.interval/r.tokensPerInterval));return setTimeout(function(){r.removeTokens(e,t)},i),!1}},tryRemoveTokens:function(e){return this.bucketSize?e>this.bucketSize||(this.drip(),e>this.content)||this.parentBucket&&!this.parentBucket.tryRemoveTokens(e)?!1:(this.content-=e,!0):!0},drip:function(){if(!this.tokensPerInterval){this.content=this.bucketSize;return}var e=+new Date,t=Math.max(e-this.lastDrip,0);this.lastDrip=e;var r=t*(this.tokensPerInterval/this.interval);this.content=Math.min(this.content+r,this.bucketSize)}};jOu.exports=NOu});var zOu=b((RwI,QOu)=>{"use strict";var Urm=function(){if(typeof process<"u"&&process.hrtime){var e=process.hrtime(),t=e[0],r=e[1];return t*1e3+Math.floor(r/1e6)}return new Date().getTime()};QOu.exports=Urm});var VOu=b((kwI,LOu)=>{"use strict";var _rm=hNo(),gNo=zOu(),MOu=function(e,t,r){this.tokenBucket=new _rm(e,e,t,null),this.tokenBucket.content=e,this.curIntervalStart=gNo(),this.tokensThisInterval=0,this.fireImmediately=r};MOu.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(e,t){if(e>this.tokenBucket.bucketSize)return process.nextTick(t.bind(null,"Requested tokens "+e+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var r=this,n=gNo();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)process.nextTick(t.bind(null,null,-1));else{var i=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-n);setTimeout(function(){r.tokenBucket.removeTokens(e,o)},i)}return!1}return this.tokenBucket.removeTokens(e,o);function o(s,a){if(s)return t(s,null);r.tokensThisInterval+=e,t(null,a)}},tryRemoveTokens:function(e){if(e>this.tokenBucket.bucketSize)return!1;var t=gNo();if((t<this.curIntervalStart||t-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=t,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;var r=this.tokenBucket.tryRemoveTokens(e);return r&&(this.tokensThisInterval+=e),r},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}};LOu.exports=MOu});var UOu=b(ANo=>{"use strict";ANo.RateLimiter=VOu();ANo.TokenBucket=hNo()});var yNo=b((NwI,_Ou)=>{"use strict";function M5r(e){Error.call(this,e),Error.captureStackTrace(this,this.constructor),this.name="JwksRateLimitError",this.message=e}M5r.prototype=Object.create(Error.prototype);M5r.prototype.constructor=M5r;_Ou.exports=M5r});var GOu=b((jwI,qOu)=>{"use strict";var bNo=TA()("jwks"),{RateLimiter:qrm}=UOu(),Grm=yNo();function Wrm(e,{jwksRequestsPerMinute:t=10}){let r=e.getSigningKey.bind(e),n=new qrm(t,"minute",!0);return bNo(`Configured rate limiting to JWKS endpoint at ${t}/minute`),async i=>await new Promise((o,s)=>{n.removeTokens(1,async(a,c)=>{if(a&&s(a),bNo("Requests to the JWKS endpoint available for the next minute:",c),c<0)bNo("Too many requests to the JWKS endpoint"),s(new Grm("Too many requests to the JWKS endpoint"));else try{let u=await r(i);o(u)}catch(u){s(u)}})})}qOu.exports.default=Wrm});var HOu=b((QwI,WOu)=>{"use strict";var Hrm=W2o().retrieveSigningKeys;function Krm(e,{getKeysInterceptor:t}){let r=e.getSigningKey.bind(e);return async n=>{let i=await t(),o;if(i&&i.length&&(o=await Hrm(i)),o&&o.length){let s=o.find(a=>!n||a.kid===n);if(s)return s}return r(n)}}WOu.exports.default=Krm});var JOu=b((zwI,KOu)=>{"use strict";var{callbackify:Jrm}=require("util"),Yrm=e=>{let t=e.getSigningKey.bind(e);return(r,n)=>n?Jrm(t)(r,n):t(r)};KOu.exports.default=Yrm});var XOu=b((MwI,YOu)=>{"use strict";YOu.exports={request:TTu().default,cacheSigningKey:FOu().default,rateLimitSigningKey:GOu().default,getKeysInterceptor:HOu().default,callbackSupport:JOu().default}});var ENo=b((LwI,ZOu)=>{"use strict";function L5r(e){Error.call(this,e),Error.captureStackTrace(this,this.constructor),this.name="SigningKeyNotFoundError",this.message=e}L5r.prototype=Object.create(Error.prototype);L5r.prototype.constructor=L5r;ZOu.exports=L5r});var Hnt=b((VwI,eBu)=>{"use strict";var OLe=TA()("jwks"),{retrieveSigningKeys:Xrm}=W2o(),{request:Zrm,cacheSigningKey:$rm,rateLimitSigningKey:enm,getKeysInterceptor:tnm,callbackSupport:rnm}=XOu(),INo=T5r(),$Ou=ENo(),vNo=class{constructor(t){this.options={rateLimit:!1,cache:!0,timeout:3e4,...t},this.options.getKeysInterceptor&&(this.getSigningKey=tnm(this,t)),this.options.rateLimit&&(this.getSigningKey=enm(this,t)),this.options.cache&&(this.getSigningKey=$rm(this,t)),this.getSigningKey=rnm(this,t)}async getKeys(){OLe(`Fetching keys from '${this.options.jwksUri}'`);try{let t=await Zrm({uri:this.options.jwksUri,headers:this.options.requestHeaders,agent:this.options.requestAgent,timeout:this.options.timeout,fetcher:this.options.fetcher});return OLe("Keys:",t.keys),t.keys}catch(t){let{errorMsg:r}=t;throw OLe("Failure:",r||t),r?new INo(r):t}}async getSigningKeys(){let t=await this.getKeys();if(!t||!t.length)throw new INo("The JWKS endpoint did not contain any keys");let r=await Xrm(t);if(!r.length)throw new INo("The JWKS endpoint did not contain any signing keys");return OLe("Signing Keys:",r),r}async getSigningKey(t){OLe(`Fetching signing key for '${t}'`);let r=await this.getSigningKeys(),n=t!=null;if(!n&&r.length>1)throw OLe("No KID specified and JWKS endpoint returned more than 1 key"),new $Ou("No KID specified and JWKS endpoint returned more than 1 key");let i=r.find(o=>!n||o.kid===t);if(i)return i;throw OLe(`Unable to find a signing key that matches '${t}'`),new $Ou(`Unable to find a signing key that matches '${t}'`)}};eBu.exports={JwksClient:vNo}});var Knt=b((UwI,tBu)=>{"use strict";tBu.exports={ArgumentError:H2o(),JwksError:T5r(),JwksRateLimitError:yNo(),SigningKeyNotFoundError:ENo()}});var GVt=b((_wI,rBu)=>{"use strict";var nnm=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES256K","ES384","ES512","EdDSA"];rBu.exports=nnm});var nBu=b((qwI,V5r)=>{"use strict";var{ArgumentError:inm}=Knt(),{JwksClient:onm}=Hnt(),snm=GVt(),anm=(e,t)=>{if(e&&e.name==="SigningKeyNotFoundError"||e)return t(e,null,null)};V5r.exports.hapiJwt2KeyAsync=e=>{let t=V5r.exports.hapiJwt2Key(e);return function(r){return new Promise((n,i)=>{t(r,(s,a)=>{!a||s?i(s):n({key:a})})})}};V5r.exports.hapiJwt2Key=function(e){if(e==null)throw new inm("An options object must be provided when initializing hapiJwt2Key");let t=new onm(e),r=e.handleSigningKeyError||anm;return function(i,o){if(!i||!i.header)return o(new Error("Cannot find a signing certificate if there is no header"),null,null);if(!snm.includes(i.header.alg))return o(new Error("Unsupported algorithm "+i.header.alg+" supplied."),null,null);t.getSigningKey(i.header.kid).then(s=>o(null,s.publicKey||s.rsaPublicKey,s)).catch(s=>r(s,a=>o(a,null,null)))}}});var oBu=b((GwI,iBu)=>{"use strict";var{ArgumentError:cnm}=Knt(),{JwksClient:unm}=Hnt(),lnm=GVt(),pnm=(e,t)=>{if(e&&e.name==="SigningKeyNotFoundError")return t(null);if(e)return t(e)};iBu.exports.expressJwtSecret=function(e){if(e==null)throw new cnm("An options object must be provided when initializing expressJwtSecret");let t=new unm(e),r=e.handleSigningKeyError||pnm,n=async(i,o)=>{if(!o)return;let s=o.header;if(!(!s||!lnm.includes(s.alg)))try{let a=await t.getSigningKey(s.kid);return a.publicKey||a.rsaPublicKey}catch(a){return new Promise((c,u)=>{r(a,l=>{if(!l)return c();u(l)})})}};return function(o,s,a,c){if(arguments.length===4){n(o,{header:s}).then(u=>{setImmediate(c,null,u)}).catch(u=>{setImmediate(c,u)});return}return n(o,arguments[1])}}});var aBu=b((WwI,sBu)=>{"use strict";var{ArgumentError:fnm}=Knt(),{JwksClient:dnm}=Hnt(),mnm=GVt();sBu.exports.koaJwtSecret=function(e={}){if(!e.jwksUri)throw new fnm("No JWKS provided. Please provide a jwksUri");let t=new dnm(e);return function({alg:n,kid:i}={}){return new Promise((o,s)=>{if(!mnm.includes(n))return s(new Error("Missing / invalid token algorithm"));t.getSigningKey(i).then(a=>{o(a.publicKey||a.rsaPublicKey)}).catch(a=>e.handleSigningKeyError?e.handleSigningKeyError(a).then(s):s(a))})}}});var pBu=b((HwI,lBu)=>{"use strict";var cBu=G2o(),{ArgumentError:uBu}=Knt(),{JwksClient:hnm}=Hnt(),gnm=GVt(),Anm=(e,t)=>{if(e&&e.name==="SigningKeyNotFoundError")return t(null);if(e)return t(e)};lBu.exports.passportJwtSecret=function(e){if(e==null)throw new uBu("An options object must be provided when initializing passportJwtSecret");if(!e.jwksUri)throw new uBu("No JWKS provided. Please provide a jwksUri");let t=new hnm(e),r=e.handleSigningKeyError||Anm;return function(i,o,s){let a;try{a={payload:cBu.decodeJwt(o),header:cBu.decodeProtectedHeader(o)}}catch{a=null}if(!a||!gnm.includes(a.header.alg))return s(null,null);t.getSigningKey(a.header.kid).then(c=>{s(null,c.publicKey||c.rsaPublicKey)}).catch(c=>{r(c,u=>s(u,null))})}}});var dBu=b((KwI,D_)=>{"use strict";var{JwksClient:fBu}=Hnt(),U5r=Knt(),{hapiJwt2Key:ynm,hapiJwt2KeyAsync:bnm}=nBu(),{expressJwtSecret:Enm}=oBu(),{koaJwtSecret:Inm}=aBu(),{passportJwtSecret:vnm}=pBu();D_.exports=e=>new fBu(e);D_.exports.JwksClient=fBu;D_.exports.ArgumentError=U5r.ArgumentError;D_.exports.JwksError=U5r.JwksError;D_.exports.JwksRateLimitError=U5r.JwksRateLimitError;D_.exports.SigningKeyNotFoundError=U5r.SigningKeyNotFoundError;D_.exports.expressJwtSecret=Enm;D_.exports.hapiJwt2Key=ynm;D_.exports.hapiJwt2KeyAsync=bnm;D_.exports.koaJwtSecret=Inm;D_.exports.passportJwtSecret=vnm});var KVt=b((dSI,CNo)=>{"use strict";var fd=CNo.exports;CNo.exports.default=fd;var Mg="\x1B[",HVt="\x1B]",Jnt="\x07",_5r=";",ABu=process.env.TERM_PROGRAM==="Apple_Terminal";fd.cursorTo=(e,t)=>{if(typeof e!="number")throw new TypeError("The `x` argument is required");return typeof t!="number"?Mg+(e+1)+"G":Mg+(t+1)+";"+(e+1)+"H"};fd.cursorMove=(e,t)=>{if(typeof e!="number")throw new TypeError("The `x` argument is required");let r="";return e<0?r+=Mg+-e+"D":e>0&&(r+=Mg+e+"C"),t<0?r+=Mg+-t+"A":t>0&&(r+=Mg+t+"B"),r};fd.cursorUp=(e=1)=>Mg+e+"A";fd.cursorDown=(e=1)=>Mg+e+"B";fd.cursorForward=(e=1)=>Mg+e+"C";fd.cursorBackward=(e=1)=>Mg+e+"D";fd.cursorLeft=Mg+"G";fd.cursorSavePosition=ABu?"\x1B7":Mg+"s";fd.cursorRestorePosition=ABu?"\x1B8":Mg+"u";fd.cursorGetPosition=Mg+"6n";fd.cursorNextLine=Mg+"E";fd.cursorPrevLine=Mg+"F";fd.cursorHide=Mg+"?25l";fd.cursorShow=Mg+"?25h";fd.eraseLines=e=>{let t="";for(let r=0;r<e;r++)t+=fd.eraseLine+(r<e-1?fd.cursorUp():"");return e&&(t+=fd.cursorLeft),t};fd.eraseEndLine=Mg+"K";fd.eraseStartLine=Mg+"1K";fd.eraseLine=Mg+"2K";fd.eraseDown=Mg+"J";fd.eraseUp=Mg+"1J";fd.eraseScreen=Mg+"2J";fd.scrollUp=Mg+"S";fd.scrollDown=Mg+"T";fd.clearScreen="\x1Bc";fd.clearTerminal=process.platform==="win32"?`${fd.eraseScreen}${Mg}0f`:`${fd.eraseScreen}${Mg}3J${Mg}H`;fd.beep=Jnt;fd.link=(e,t)=>[HVt,"8",_5r,_5r,t,Jnt,e,HVt,"8",_5r,_5r,Jnt].join("");fd.image=(e,t={})=>{let r=`${HVt}1337;File=inline=1`;return t.width&&(r+=`;width=${t.width}`),t.height&&(r+=`;height=${t.height}`),t.preserveAspectRatio===!1&&(r+=";preserveAspectRatio=0"),r+":"+e.toString("base64")+Jnt};fd.iTerm={setCwd:(e=process.cwd())=>`${HVt}50;CurrentDir=${e}${Jnt}`,annotation:(e,t={})=>{let r=`${HVt}1337;`,n=typeof t.x<"u",i=typeof t.y<"u";if((n||i)&&!(n&&i&&typeof t.length<"u"))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return e=e.replace(/\|/g,""),r+=t.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",t.length>0?r+=(n?[e,t.length,t.x,t.y]:[t.length,e]).join("|"):r+=e,r+Jnt}}});var Vw=b((mSI,yBu)=>{"use strict";var Cnm=require("tty"),wnm=Cnm?.WriteStream?.prototype?.hasColors?.()??!1,Cp=(e,t)=>{if(!wnm)return i=>i;let r=`\x1B[${e}m`,n=`\x1B[${t}m`;return i=>{let o=i+"",s=o.indexOf(n);if(s===-1)return r+o+n;let a=r,c=0,l=(t===22?n:"")+r;for(;s!==-1;)a+=o.slice(c,s)+l,c=s+n.length,s=o.indexOf(n,c);return a+=o.slice(c)+n,a}},up={};up.reset=Cp(0,0);up.bold=Cp(1,22);up.dim=Cp(2,22);up.italic=Cp(3,23);up.underline=Cp(4,24);up.overline=Cp(53,55);up.inverse=Cp(7,27);up.hidden=Cp(8,28);up.strikethrough=Cp(9,29);up.black=Cp(30,39);up.red=Cp(31,39);up.green=Cp(32,39);up.yellow=Cp(33,39);up.blue=Cp(34,39);up.magenta=Cp(35,39);up.cyan=Cp(36,39);up.white=Cp(37,39);up.gray=Cp(90,39);up.bgBlack=Cp(40,49);up.bgRed=Cp(41,49);up.bgGreen=Cp(42,49);up.bgYellow=Cp(43,49);up.bgBlue=Cp(44,49);up.bgMagenta=Cp(45,49);up.bgCyan=Cp(46,49);up.bgWhite=Cp(47,49);up.bgGray=Cp(100,49);up.redBright=Cp(91,39);up.greenBright=Cp(92,39);up.yellowBright=Cp(93,39);up.blueBright=Cp(94,39);up.magentaBright=Cp(95,39);up.cyanBright=Cp(96,39);up.whiteBright=Cp(97,39);up.bgRedBright=Cp(101,49);up.bgGreenBright=Cp(102,49);up.bgYellowBright=Cp(103,49);up.bgBlueBright=Cp(104,49);up.bgMagentaBright=Cp(105,49);up.bgCyanBright=Cp(106,49);up.bgWhiteBright=Cp(107,49);yBu.exports=up});var JVt=b((ASI,xBu)=>{"use strict";function IBu(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}var vBu=xBu.exports=function(e,t,r="async"){return typeof t=="string"&&(r=t,t=void 0),t=t||function(){},function(){var n=arguments,i=this,o=new Promise(function(s,a){var c=!1;let u=function(E){c&&console.warn("Run-async promise already resolved."),c=!0,s(E)};var l=!1;let p=function(E){l&&console.warn("Run-async promise already rejected."),l=!0,a(E)};var d=!1,f=!1,m=!1,g=function(){return m?(console.warn("Run-async async() called outside a valid run-async context, callback will be ignored."),function(){}):(f&&console.warn(`Run-async wrapped function (async) returned a promise.
943
943
  Calls to async() callback can have unexpected results.`),d=!0,function(E,x){E?p(E):u(x)})},A;i&&r&&Proxy?A=new Proxy(i,{get(E,x){return x===r?(x in E&&console.warn(`${r} property is been shadowed by run-sync`),g):Reflect.get(...arguments)}}):A={[r]:g};var y=e.apply(A,Array.prototype.slice.call(n));d?IBu(y)&&console.warn("Run-async wrapped function (sync) returned a promise but async() callback must be executed to resolve."):IBu(y)?(f=!0,y.then(u,p)):u(y),m=!0});return o.then(t.bind(null,null),t),o}};vBu.cb=function(e,t){return vBu(function(){var r=Array.prototype.slice.call(arguments);return r.length===e.length-1&&r.push(this.async()),e.apply(this,r)},t)}});var Lg=b(q5r=>{"use strict";Object.defineProperty(q5r,"__esModule",{value:!0});q5r.isFunction=void 0;function Rnm(e){return typeof e=="function"}q5r.isFunction=Rnm});var Dve=b(G5r=>{"use strict";Object.defineProperty(G5r,"__esModule",{value:!0});G5r.createErrorClass=void 0;function knm(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}G5r.createErrorClass=knm});var wNo=b(W5r=>{"use strict";Object.defineProperty(W5r,"__esModule",{value:!0});W5r.UnsubscriptionError=void 0;var Fnm=Dve();W5r.UnsubscriptionError=Fnm.createErrorClass(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
@@ -3360,7 +3360,7 @@ ${f2u.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&fQo(th
3360
3360
  `+_Le.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?_Le.default.cyan(I2u(t,this.opt.mask)):_Le.default.italic(_Le.default.dim("[hidden]")):this.opt.mask?I2u(t,this.opt.mask):_Le.default.italic(_Le.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 GGr=ye(Vw(),1);var ENu=ye(HQo(),1),_Gr=require("child_process"),Wit=require("fs"),UGr=ye(require("path"),1),INu=ye(require("os"),1),vNu=require("crypto"),Dzo=ye(yNu(),1);var MGr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var kUt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var LGr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var VGr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function qGr(e="",t,r){let n=new Rzo(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function bNu(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function NIm(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var Rzo=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=NIm(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??INu.default.tmpdir(),r=(0,vNu.randomUUID)(),n=bNu(this.fileOptions.prefix),i=bNu(this.fileOptions.postfix),o=`${n}${r}${i}`,s=UGr.default.resolve(t,o),a=UGr.default.resolve(t)+UGr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,Wit.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new MGr(t)}}readTemporaryFile(){try{let t=(0,Wit.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,ENu.detect)(t)??"utf8";Dzo.default.encodingExists(r)||(r="utf8"),this.text=Dzo.default.decode(t,r)}}catch(t){throw new LGr(t)}}removeTemporaryFile(){try{(0,Wit.unlinkSync)(this.tempFile)}catch(t){throw new VGr(t)}}launchEditor(){try{let t=(0,_Gr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new kUt(t)}}launchEditorAsync(t){try{(0,_Gr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new kUt(r)}}};var xNu=ye(c3(),1);var FUt=class extends Uw{_run(t){this.done=t,this.editorResult=new xNu.Subject;let r=DB(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?GGr.default.dim("Received"):GGr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=GGr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),qGr(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 ONu=require("stream");var SNu=ye(require("readline"),1),TNu=ye(wNu(),1),HLe=class{constructor(t){this.rl||=SNu.default.createInterface(QIm(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 QIm(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new TNu.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var NUt=class extends HLe{constructor(t={}){super(t),this.log=new ONu.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return yUt(this.rl,this.bottomBar.split(`
3361
3361
  `).length),this}updateBottomBar(t){return yUt(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+`
3362
3362
  `}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&&dGr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Qd=ye(c3(),1),DNu=ye(JVt(),1);var WGr=ye(c3(),1),BNu=ye(JVt(),1),HGr=function(e,t,r){return typeof e[t]!="function"?(0,WGr.of)(e):(0,WGr.from)((0,BNu.default)(e[t])(r).then(n=>(e[t]=n,e)))};var PNu={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Hit=class extends HLe{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,Qd.from)(t):(0,Qd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Qd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Qd.from)([t]),this.process=n.pipe((0,Qd.concatMap)(this.processQuestion.bind(this)),(0,Qd.publish)()),this.process.connect(),this.process.pipe((0,Qd.reduce)((i,o)=>(PNu.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Qd.defer)(()=>(0,Qd.of)(t).pipe((0,Qd.concatMap)(this.setDefaultType.bind(this)),(0,Qd.concatMap)(this.filterIfRunnable.bind(this)),(0,Qd.concatMap)(()=>HGr(t,"message",this.answers)),(0,Qd.concatMap)(()=>HGr(t,"default",this.answers)),(0,Qd.concatMap)(()=>HGr(t,"choices",this.answers)),(0,Qd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Qd.defer)(()=>(0,Qd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Qd.defer)(()=>(0,Qd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&PNu.get(this.answers,t.name)!==void 0)return Qd.EMPTY;if(t.when===!1)return Qd.EMPTY;if(typeof t.when!="function")return(0,Qd.of)(t);let{answers:r}=this;return(0,Qd.defer)(()=>(0,Qd.from)((0,DNu.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Qd.filter)(n=>n!=null)))}};function RNu(e){let t=function(r,n){let i;try{i=new Hit(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",EUt),this.registerPrompt("input",ULe),this.registerPrompt("number",IUt),this.registerPrompt("confirm",vUt),this.registerPrompt("rawlist",xUt),this.registerPrompt("expand",CUt),this.registerPrompt("checkbox",wUt),this.registerPrompt("password",SUt),this.registerPrompt("editor",FUt)},t.restoreDefaultPrompts(),t}var Fzo=RNu();function MIm(e,t){Fzo.registerPrompt(e,t)}function LIm(){Fzo.restoreDefaultPrompts()}var VIm={prompt:Fzo,ui:{BottomBar:NUt,Prompt:Hit},createPromptModule:RNu,registerPrompt:MIm,restoreDefaultPrompts:LIm,Separator:ez},lu=VIm;var Kit=require("path");function FNu(){let e=UIm();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function UIm(e=process.argv[1]?(0,Kit.dirname)(process.argv[1]):process.cwd(),t=Kit.sep==="\\"){let r=t?kNu(e):e;return n=>{if(!n)return;let i=t?kNu(n):n,{dir:o,base:s,ext:a}=Kit.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function kNu(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Nzo=e=>{if("flags"in e){let t=NNu(e.flags),r=jNu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,jzo(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,_Im(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function _Im(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 NNu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,jUt(r)]).filter(([,t])=>t!==void 0)),jNu=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?jzo(n):void 0]}))};var jUt=e=>e===void 0?void 0:e.variant??e.enabled,jzo=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var a2=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function Qzo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var GIm="NativeGzipValidationError",WIm=31,HIm=139,KIm=8,JIm=e=>e.length>=2&&e[0]===WIm&&e[1]===HIm;var QUt,YIm=()=>{if(QUt)return QUt;QUt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;QUt[e]=t>>>0}return QUt},XIm=e=>{let t=YIm(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},KGr=e=>{let t=new Error(`Native gzip produced invalid output: ${e}`);throw t.name=GIm,t},ZIm=async(e,t)=>{e.size<18&&KGr("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!JIm(r)||r[2]!==KIm)&&KGr("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==XIm(t)&&KGr("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&KGr("invalid-size")};async function zUt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await ZIm(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var $Im=["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"],QNu=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return $Im.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var tvm=Array.isArray,zNu=Object.prototype,fRI=zNu.hasOwnProperty,zzo=zNu.toString,Jit=tvm||function(e){return zzo.call(e)==="[object Array]"};var MUt=e=>e===Object(e)&&!Jit(e);var Yit=e=>e===void 0,ixe=e=>zzo.call(e)=="[object String]",MNu=e=>ixe(e)&&e.trim().length===0;var LUt=e=>zzo.call(e)=="[object Number]"&&e===e;var Mzo=e=>e instanceof Error;function JGr(e){return e===null||typeof e!="object"}function KLe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function LNu(e){return KLe(e,"ErrorEvent")}function Xit(e){return typeof Event<"u"&&rvm(e,Event)}function VNu(e){return KLe(e,"Object")}function rvm(e,t){try{return e instanceof t}catch{return!1}}function VUt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),LUt(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),VUt(i||r,t,r,n))}var nvm=864e5,YGr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=VUt(t.bucketSize,0,100,t._logger),this._refillRate=VUt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=VUt(t.refillInterval,0,nvm,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var XGr="0123456789abcdef",ZGr=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=XGr.charAt(this.bytes[r]>>>4),t+=XGr.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+=XGr.charAt(this.bytes[r]>>>4),t+=XGr.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Lzo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??ivm()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return ZGr.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,ZGr.ofInner(t)}},ivm=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),UNu,Tee=()=>ovm().toString(),ovm=()=>(UNu||(UNu=new Lzo)).generate();var $Gr=class{add(t){let r=Tee();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 svm(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var _Nu=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>_Nu(`${e} ${o}`,t,r)}},avm=e=>e();function qNu(e,t=avm){return _Nu(e,t,svm())}var $it="Mobile",t7r="iOS",Zit="Android",GNu="Tablet",CRI=Zit+" "+GNu;var uvm="Apple",wRI=uvm+" Watch",WNu="Safari",r7r="BlackBerry",HNu="Samsung",lvm=HNu+"Browser",pvm=HNu+" Internet",n7r="Chrome",fvm=n7r+" OS",dvm=n7r+" "+t7r,KNu="Internet Explorer",mvm=KNu+" "+$it,Uzo="Opera",SRI=Uzo+" Mini",JNu="Edge",hvm="Microsoft "+JNu,_zo="Firefox",gvm=_zo+" "+t7r,qzo="Nintendo",Gzo="PlayStation",e7r="Xbox",Avm=Zit+" "+$it,yvm=$it+" "+WNu,UUt="Windows",bvm=UUt+" Phone";var YNu="Generic",TRI=YNu+" "+$it.toLowerCase(),ORI=YNu+" "+GNu.toLowerCase(),Evm="Konqueror",Ivm="Oculus Browser",ND="(\\d+(\\.\\d+)?)",Vzo=new RegExp("Version/"+ND),BRI=new RegExp(e7r,"i"),PRI=new RegExp(Gzo+" \\w+","i"),DRI=new RegExp(qzo+" \\w+","i"),vvm=new RegExp(r7r+"|PlayBook|BB10","i"),xvm={"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 RRI={[mvm]:[new RegExp("rv:"+ND)],[hvm]:[new RegExp(JNu+"?\\/"+ND)],[n7r]:[new RegExp("("+n7r+"|CrMo)\\/"+ND)],[dvm]:[new RegExp("CriOS\\/"+ND)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ND)],[WNu]:[Vzo],[yvm]:[Vzo],[Uzo]:[new RegExp("("+Uzo+"|OPR)\\/"+ND)],[_zo]:[new RegExp(_zo+"\\/"+ND)],[gvm]:[new RegExp("FxiOS\\/"+ND)],[Evm]:[new RegExp("Konqueror[:/]?"+ND,"i")],[r7r]:[new RegExp(r7r+" "+ND),Vzo],[Avm]:[new RegExp("android\\s"+ND,"i")],[pvm]:[new RegExp(lvm+"\\/"+ND)],[Ivm]:[new RegExp("OculusBrowser\\/"+ND)],[KNu]:[new RegExp("(rv:|MSIE )"+ND)],Mozilla:[new RegExp("rv:"+ND)]};var kRI=[[new RegExp(e7r+"; "+e7r+" (.*?)[);]","i"),e=>[e7r,e&&e[1]||""]],[new RegExp(qzo,"i"),[qzo,""]],[new RegExp(Gzo,"i"),[Gzo,""]],[vvm,[r7r,""]],[new RegExp(UUt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[bvm,""];if(new RegExp($it).test(t)&&!/IEMobile\b/.test(t))return[UUt+" "+$it,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=xvm[n]||"";return/arm/i.test(t)&&(i="RT"),[UUt,i]}return[UUt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[t7r,t.join(".")]}return[t7r,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Yit(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Zit+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Zit+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Zit,t.join(".")]}return[Zit,""]}],[/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/,[fvm,""]],[/Linux|debian/i,["Linux",""]]];var XNu="utf8";function ZNu(e){return e?.replace(/\/+$/,"")}async function $Nu(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function i7r(){return new Date().toISOString()}function Oee(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var eju=e=>e instanceof Error;function Wzo(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Cvm={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},HRI=Cvm.info;var o7r=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};var YLe=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()}},JLe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function tju(e){if(e instanceof YLe){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 s7r(e){return typeof e=="object"&&(e instanceof YLe||e instanceof JLe)}function a7r(e){return typeof e=="object"&&e instanceof YLe&&e.status===413}var _Ut=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new $Gr,this._events=new o7r,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=qNu("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=ZNu(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:s7r},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)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Qzo()||(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(a2.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(a2.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(a2.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:Nzo(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof YLe)return{type:"api_error",statusCode:t.status};if(t instanceof JLe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=jUt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={};(o??this.disableGeoip)&&(a.geoip_disable=!0),s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let u=c.response;return u.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),u.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(a2.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(a2.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(a2.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(a2.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(a2.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Oee(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:i7r()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,c=this.disableCompression?null:await zUt(s,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||s};try{await(await this.fetchWithRetry(a,u)).body?.cancel()?.catch(()=>{})}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:i7r(),uuid:n?.uuid?n.uuid:Tee()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await tju(t)})}async flush(){if(this.disabled)return;let t=Wzo([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Wzo([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(a2.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(a2.Queue)||[]).slice(i.length);this.setPersistedProperty(a2.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:i7r()};this.historicalMigration&&(a.historical_migration=!0);let c=JSON.stringify(a),u=`${this.host}/batch/`,l=this.disableCompression?null:await zUt(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||c},d={retryCheck:f=>a7r(f)?!1:s7r(f)};try{await(await this.fetchWithRetry(u,p,d)).body?.cancel()?.catch(()=>{})}catch(f){if(a7r(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof JLe||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async _sendLogsBatch(t){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let r=JSON.stringify(t),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await zUt(r,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||r};try{return await this.fetchWithRetry(n,o,{retryCheck:s=>a7r(s)?!1:s7r(s)}),{kind:"ok"}}catch(s){return a7r(s)?{kind:"too-large"}:s instanceof JLe?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(t,r,n,i){let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,XNu)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await $Nu(async()=>{let a=new AbortController,c=i??this.requestTimeout,u=Oee(()=>a.abort(),c),l=null;try{l=await this.fetch(t,{signal:a.signal,...r})}catch(d){throw new JLe(d)}finally{clearTimeout(u)}if(!(r.mode==="no-cors")&&(l.status<200||l.status>=400))throw new YLe(l,s);return l},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(a2.Queue)||[]).length===0||(await this.flush(),r)););}catch(o){if(!s7r(o))throw o;await tju(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=Oee(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}finally{clearTimeout(i)}}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var rz={};X(rz,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>f7r,DOMExceptionCoercer:()=>Yzo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>qUt,ErrorCoercer:()=>Xzo,ErrorEventCoercer:()=>Zzo,ErrorPropertiesBuilder:()=>Hzo,EventCoercer:()=>tMo,ExceptionStepsBuffer:()=>sMo,ObjectCoercer:()=>eMo,PrimitiveCoercer:()=>rMo,PromiseRejectionEventCoercer:()=>nMo,ReduceableCache:()=>iMo,StringCoercer:()=>$zo,chromeStackLineParser:()=>Kzo,createDefaultStackParser:()=>Vvm,createStackParser:()=>fju,geckoStackLineParser:()=>Jzo,getUtf8ByteLength:()=>mju,nodeStackLineParser:()=>cju,opera10StackLineParser:()=>oju,opera11StackLineParser:()=>sju,resolveExceptionStepsConfig:()=>oMo,reverseAndStripFrames:()=>pju,stripReservedExceptionStepFields:()=>qvm,winjsStackLineParser:()=>iju});var c7r,rju,u7r;function nju(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return u7r&&r.length===rju||(rju=r.length,u7r=r.reduce((n,i)=>{c7r||(c7r={});let o=c7r[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,c7r[i]=[u,l];break}}}return n},{})),u7r}var Ovm=4,Hzo=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&Jit(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:nju(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=Ovm){let c=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var kB="?";function Bee(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?kB:r,in_app:!0};return Yit(n)||(o.lineno=n),Yit(i)||(o.colno=i),o}var l7r=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:kB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Bvm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Pvm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Dvm=/\((\S*)(?::(\d+))(?::(\d+))\)/,Kzo=(e,t)=>{let r=Bvm.exec(e);if(r){let[,i,o,s]=r;return Bee(t,i,kB,+o,+s)}let n=Pvm.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Dvm.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=l7r(n[1]||kB,n[2]);return Bee(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Rvm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,kvm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Jzo=(e,t)=>{let r=Rvm.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=kvm.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||kB;return[o,i]=l7r(o,i),Bee(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Fvm=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,iju=(e,t)=>{let r=Fvm.exec(e);return r?Bee(t,r[2],r[1]||kB,+r[3],r[4]?+r[4]:void 0):void 0};var Nvm=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,oju=(e,t)=>{let r=Nvm.exec(e);return r?Bee(t,r[2],r[3]||kB,+r[1]):void 0},jvm=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,sju=(e,t)=>{let r=jvm.exec(e);return r?Bee(t,r[5],r[3]||r[4]||kB,+r[1],+r[2]):void 0};var Qvm=/^\s*[-]{4,}$/,zvm=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,cju=(e,t)=>{let r=e.match(zvm);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||kB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:aju(r[3]),colno:aju(r[4]),in_app:Mvm(c||"",u),platform:t}}if(e.match(Qvm))return{filename:e,platform:t}};function Mvm(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 aju(e){return parseInt(e||"",10)||void 0}var uju=/\(error: (.*)\)/,lju=50;function pju(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,lju).map(r=>({...r,filename:r.filename||Lvm(t).filename,function:r.function||kB}))}function Lvm(e){return e[e.length-1]||{}}function Vvm(){return fju("web:javascript",Kzo,Jzo)}function fju(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
3363
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=uju.test(a)?a.replace(uju,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=lju)break}}return pju(i)}}var Yzo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ixe(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return KLe(t,"DOMException")}isDOMError(t){return KLe(t,"DOMError")}};var Xzo=class{match(t){return Mzo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var Zzo=class{constructor(){}match(t){return LNu(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Uvm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$zo=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Uvm);return i&&(r=i[1],n=i[2]),[r,n]}};var dju=["fatal","error","warning","log","info","debug"];function p7r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var eMo=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Xit(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=p7r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ixe(t)&&!MNu(t)&&dju.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(eju(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var tMo=class{match(t){return Xit(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${p7r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var rMo=class{match(t){return JGr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var nMo=class{match(t){return KLe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xit(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return JGr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var iMo=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 qUt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},_vm=new Set([qUt.MESSAGE,qUt.TIMESTAMP]),f7r={enabled:!0,max_bytes:32768};function oMo(e){return e?{enabled:e.enabled??f7r.enabled,max_bytes:Gvm(e.max_bytes,f7r.max_bytes)}:{...f7r}}function qvm(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>_vm.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var sMo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=oMo(t)}setConfig(t){this._config=oMo(t),this._trimToMaxBytes()}add(t){let r=Wvm(t);if(!r)return;let n=mju(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function Gvm(e,t){if(!LUt(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function Wvm(e){let t=Hvm(e);if(t)try{let r=JSON.parse(t);if(!MUt(r))return;let n=r,i=n[qUt.MESSAGE],o=n[qUt.TIMESTAMP];return!ixe(i)||i.trim().length===0||!ixe(o)&&!LUt(o)?void 0:{step:n,json:t}}catch{return}}function Hvm(e){let t=new WeakSet;try{return JSON.stringify(e,(r,n)=>{if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Date)return n.toISOString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){if(t.has(n))return"[Circular]";t.add(n)}return n}})}catch{return}}function mju(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}var Aju=require("fs"),yju=require("readline"),d7r=new rz.ReduceableCache(25),bju=new rz.ReduceableCache(20),aMo=7,Kvm=1e3,Jvm=1e4;async function Eju(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||$vm(s)||exm(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(bju.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=rxm(o);if(s.every(c=>txm(i,c)))continue;let a=nxm(d7r,i,{});n.push(Yvm(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Xvm(e,d7r),d7r.reduce(),e}function Yvm(e,t,r){return new Promise(n=>{let i=(0,Aju.createReadStream)(e),o=(0,yju.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){bju.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=ixm(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Xvm(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;Zvm(r.lineno,r,n)}}function Zvm(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Iju(e);i<e;i++){let o=r[i];if(o===void 0)return void hju(t);t.pre_context.push(o)}if(r[e]===void 0)return void hju(t);t.context_line=r[e];let n=vju(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function hju(e){delete e.pre_context,delete e.context_line,delete e.post_context}function $vm(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function exm(e){return e.lineno!==void 0&&e.lineno>Jvm||e.colno!==void 0&&e.colno>Kvm}function txm(e,t){let r=d7r.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function rxm(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=gju(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+aMo:(i.push(n),n=gju(o)),t++}return i}function gju(e){return[Iju(e),vju(e)]}function Iju(e){return Math.max(1,e-aMo)}function vju(e){return e+aMo}function nxm(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function ixm(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var eot=require("path");function xju(e=process.cwd()){let t=eot.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,eot.isAbsolute)(o.filename)&&(o.filename=r((0,eot.relative)(n,r(o.filename))));return i}}function oxm(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Cju(e,t){globalThis.process?.on("uncaughtException",oxm(e,t))}function wju(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var sxm=2e3,hH=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new YGr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return MUt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Cju(this.onException.bind(this),this.onFatalError.bind(this)),wju(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(sxm),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Sju="5.35.1";var Nfe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var tot=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t){let r=this._flags[t];return this._recordAccess(t),r?.enabled??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Nfe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Nfe.QUOTA_LIMITED),r===void 0&&o.push(Nfe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};async function Tju(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var axm=6e4,cxm=1152921504606847e3,uxm=["is_not","is_set"],rot=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},zd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Pee=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},m7r=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof Pee||u instanceof zd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Pee||u instanceof zd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new zd("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new zd("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new zd(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new zd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new zd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new zd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new zd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new zd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new zd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new zd(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=o.aggregation_group_type_index,{groups:c,groupProperties:u}=i,l=!1,p;for(let d of s)try{let f=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,m=n,g=r;if(f!==a&&f!=null){let A=this.groupTypeMapping[String(f)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${f} not available`));continue}if(!(A in u)){l=!0;continue}m=u[A],g=c[A]}if(await this.isConditionMatch(t,g,d,m,i)){let A=d.variant,y=o.multivariate?.variants||[];p=A&&y.some(E=>E.key===A)?A:await this.getMatchingVariant(t,g)||!0;break}}catch(f){if(f instanceof Pee)throw f;if(f instanceof zd)l=!0;else throw f}if(p!==void 0)return p;if(l)throw new zd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?await Rju(c,i,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,i,o)):u==="flag"?await this.evaluateFlagDependency(c,i,o):Dju(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await Oju(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await Oju(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(axm,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rot(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new rot(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rot(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof rot&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=Oee(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Oju(e,t,r=""){let n=await Tju(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/cxm}function Dju(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new zd(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!uxm.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return Bju(String(i))&&String(s).match(String(i))!==null;case"not_regex":return Bju(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:parseFloat(String(i)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(u)&&Number.isFinite(l)?c(l,u,o):c(String(s),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new zd("Date operations cannot be performed on boolean values");let u=mxm(String(i));if(u==null&&(u=Pju(i)),u==null)throw new zd(`Invalid date: ${i}`);let l=Pju(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return M_(FB(String(s)),FB(String(i)))===0;case"semver_neq":return M_(FB(String(s)),FB(String(i)))!==0;case"semver_gt":return M_(FB(String(s)),FB(String(i)))>0;case"semver_gte":return M_(FB(String(s)),FB(String(i)))>=0;case"semver_lt":return M_(FB(String(s)),FB(String(i)))<0;case"semver_lte":return M_(FB(String(s)),FB(String(i)))<=0;case"semver_tilde":{let u=FB(String(s)),{lower:l,upper:p}=pxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}case"semver_caret":{let u=FB(String(s)),{lower:l,upper:p}=fxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}case"semver_wildcard":{let u=FB(String(s)),{lower:l,upper:p}=dxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}default:throw new zd(`Unknown operator: ${o}`)}}function lxm(e,t){if(!(e in t))throw new Pee(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Rju(e,t,r,n=!1,i){let o=String(e.value);lxm(o,r);let s=r[o];return kju(s,t,r,n,i)}async function kju(e,t,r,n=!1,i){if(!e)return!0;let o=e.type,s=e.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let c of s)try{let u=await kju(c,t,r,n,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Pee)throw u;if(u instanceof zd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new zd("Can't match cohort without a given cohort property value");return o==="AND"}for(let c of s)try{let u;if(c.type==="cohort")u=await Rju(c,t,r,n,i);else if(c.type==="flag"){if(!i)throw new zd(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(c)}else u=Dju(c,t);let l=c.negation||!1;if(o==="AND"){if(!u&&!l||u&&l)return!1}else if(u&&!l||!u&&l)return!0}catch(u){if(u instanceof Pee)throw u;if(u instanceof zd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new zd("can't match cohort without a given cohort property value");return o==="AND"}function Bju(e){try{return new RegExp(e),!0}catch{return!1}}function Fju(e,t){if(!/^\d+$/.test(e))throw new zd(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new zd(`Invalid semver: ${t}`);return parseInt(e,10)}function FB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new zd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>c===void 0||c===""?0:Fju(c,e),o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function M_(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function pxm(e){let t=FB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function fxm(e){let t=FB(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function dxm(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new zd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=c=>{try{return Fju(c,e)}catch{throw new zd(`Invalid wildcard semver: ${e}`)}},o=i(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let c=i(n[1]);s=[o,c,0],a=[o,c+1,0]}return{lower:s,upper:a}}function Pju(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 zd(`${e} is in an invalid date format`)}throw new zd(`The date provided ${e} must be a string, number, or date object`)}function mxm(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var h7r=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var hxm=100,Nju=3e4,gxm=5e4,Axm=50,yxm=500,bxm="https://us.i.posthog.com",jju=new Set;function g7r(e,t){jju.has(e)||(jju.add(e),console.warn(`[PostHog] ${t}`))}function Exm(e){return typeof e=="string"?e.trim():""}function Ixm(e){return(typeof e=="string"?e.trim():"")||void 0}function vxm(e){return(typeof e=="string"?e.trim():"")||bxm}function xxm(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var A7r=class extends _Ut{constructor(t,r={}){let n=Exm(t),i={...r,host:vxm(r.host),personalApiKey:Ixm(r.personalApiKey)};if(super(n,i),this._memoryStorage=new h7r,this.options=i,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,hxm):Nju,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new m7r({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new hH(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||gxm}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??yxm,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Axm;this._waitUntilCycle.timer=Oee(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return Sju}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=Nju){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let T=this._flagOverrides[t];if(T===void 0)return;let P=this._payloadOverrides?.[t];return{key:t,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:P}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,E,x,I;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let T=this.featureFlagsPoller?.featureFlagsByKey[t];if(T)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(T,d,{matchValue:i});if(P){m=!0;let D=P.value;E=T.id,I="Evaluated locally",f={key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof Pee||P instanceof zd)this._logger?.info(`${P.name} when computing flag locally: ${t}: ${P.message}`);else throw P}}if(!m&&!c){let T=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(T===void 0)y=Nfe.UNKNOWN_ERROR;else{g=T.requestId,A=T.evaluatedAt;let P=[];T.errorsWhileComputingFlags&&P.push(Nfe.ERRORS_WHILE_COMPUTING),T.quotaLimited?.includes("feature_flags")&&P.push(Nfe.QUOTA_LIMITED);let D=T.flags[t];if(D===void 0)P.push(Nfe.FLAG_MISSING);else{E=D.metadata?.id,x=D.metadata?.version,I=D.reason?.description??D.reason?.code;let S;if(D.metadata?.payload!==void 0)try{S=JSON.parse(D.metadata.payload)}catch{S=D.metadata.payload}f={key:t,enabled:D.enabled,variant:D.variant,payload:S}}P.length>0&&(y=P.join(","))}}if(o){let T=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,P={$feature_flag:t,$feature_flag_response:T,$feature_flag_id:E,$feature_flag_version:x,$feature_flag_reason:I,locally_evaluated:m,[`$feature/${t}`]:T,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let D=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();D!==void 0&&(P.$feature_flag_definitions_loaded_at=D)}y&&(P.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:T,groups:s,disableGeoip:a,properties:P})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){g7r("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(g7r("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){g7r("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...y.flags||{}},g={...g,...y.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new tot({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f={},m,g,A=!1,y=!1,E=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(E)for(let[C,T]of Object.entries(E.response)){let P=this.featureFlagsPoller?.featureFlagsByKey[C];f[C]={key:C,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:E.payloads[C],id:P?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0},x.add(C)}if((E?E.fallbackToFlags:!0)&&!c){let C=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);if(C){m=C.requestId,g=C.evaluatedAt,A=!!C.errorsWhileComputingFlags,y=Array.isArray(C.quotaLimited)&&C.quotaLimited.includes("feature_flags");for(let[T,P]of Object.entries(C.flags)){if(x.has(T))continue;let D;if(P.metadata?.payload!==void 0)try{D=JSON.parse(P.metadata.payload)}catch{D=P.metadata.payload}f[T]={key:T,enabled:P.enabled,variant:P.variant,payload:D,id:P.metadata?.id,version:P.metadata?.version,reason:P.reason?.description??P.reason?.code,locallyEvaluated:!1}}}}if(this._flagOverrides!==void 0)for(let[C,T]of Object.entries(this._flagOverrides)){if(T===void 0){delete f[C];continue}let P=f[C];f[C]={key:C,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:P?.payload,id:P?.id,version:P?.version,reason:P?.reason,locallyEvaluated:P?.locallyEvaluated??!1}}if(this._payloadOverrides!==void 0)for(let[C,T]of Object.entries(this._payloadOverrides)){let P=f[C];P&&(f[C]={...P,payload:T})}return new tot({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:f,requestId:m,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:A,quotaLimited:y})}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=`${n}_${i}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].includes(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(c):this.distinctIdHasSentFlagCalls[r]=[c],this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=Oee(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(VNu(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!hH.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(hH.buildEventMessage(t,{syntheticException:s},r,n).then(a=>this.capture({...a,uuid:i,flags:o})))}}async captureExceptionImmediate(t,r,n,i){if(!hH.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(hH.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=t,p=this.context?.get(),d=r||p?.distinctId,f={...this.props,...p?.properties||{},...i||{}};d||(d=Tee(),f.$process_person_profile=!1),p?.sessionId&&!f.$session_id&&(f.$session_id=p.sessionId);let m=this._runBeforeSend({distinctId:d,event:n,properties:f,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!m)return Promise.reject(null);let g=await Promise.resolve().then(async()=>{if(s)return a&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),s._getEventProperties();if(a){g7r("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let A=typeof a=="object"?a:void 0,y=await this.getFeatureFlagsForEvent(m.distinctId,o,u,A);return xxm(y)}return{}}).catch(()=>({})).then(A=>({...A,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof g.$raw_user_agent=="string"&&QNu(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",g.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:g,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var Qju=require("async_hooks"),y7r=class{constructor(){this.storage=new Qju.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var zju="posthog-node";function Cxm(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[cMo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(g=>({...g,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var cMo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=zju,this.name=zju,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Cxm(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};hH.errorPropertiesBuilder=new rz.ErrorPropertiesBuilder([new rz.EventCoercer,new rz.ErrorCoercer,new rz.ObjectCoercer,new rz.StringCoercer,new rz.PrimitiveCoercer],rz.createStackParser("node:javascript",rz.nodeStackLineParser),[FNu(),Eju,xju()]);var oxe=class extends A7r{getLibraryId(){return"posthog-node"}initializeContext(){return new y7r}};var b7r=class{posthog;constructor({posthogApiKey:t}){this.posthog=new oxe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.110.0",usingAccessToken:!0,...Ace()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var GUt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Fd();Yt();var not=require("fs/promises"),Mju=require("os"),Lju=require("path");Vrt();var wxm="id",Sxm=".fern",WUt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new oxe(r),this.userId=t==null?void 0:Dko(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.110.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{},...Ace()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Of({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=PD(),r=Me(Ut.of((0,Mju.homedir)()),ve.of(Sxm),ve.of(wxm));try{await Xt(r)?this.persistedDistinctId=(await(0,not.readFile)(r)).toString():(await(0,not.mkdir)((0,Lju.dirname)(r),{recursive:!0}),await(0,not.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var uMo;async function HUt(){return uMo==null&&(uMo=await Txm()),uMo}async function Txm(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new GUt;let r=await ynt();return r!=null?new WUt({token:r,posthogApiKey:e}):await KQ()!=null?new b7r({posthogApiKey:e}):new WUt({token:void 0,posthogApiKey:e})}catch{return new GUt}}En();Tt();Qt();m_();var KUt=ye(require("process"),1);ZGe();var _ju=ye(gwo(),1),qju=ye(Uju(),1);function H1(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=YG(e),e.length===0))return 0;e=e.replace((0,qju.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(_ju.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function E7r(e){let t=0;for(let r of e.split(`
3363
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=uju.test(a)?a.replace(uju,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=lju)break}}return pju(i)}}var Yzo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ixe(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return KLe(t,"DOMException")}isDOMError(t){return KLe(t,"DOMError")}};var Xzo=class{match(t){return Mzo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var Zzo=class{constructor(){}match(t){return LNu(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Uvm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$zo=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Uvm);return i&&(r=i[1],n=i[2]),[r,n]}};var dju=["fatal","error","warning","log","info","debug"];function p7r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var eMo=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Xit(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=p7r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ixe(t)&&!MNu(t)&&dju.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(eju(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var tMo=class{match(t){return Xit(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${p7r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var rMo=class{match(t){return JGr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var nMo=class{match(t){return KLe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xit(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return JGr(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var iMo=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 qUt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},_vm=new Set([qUt.MESSAGE,qUt.TIMESTAMP]),f7r={enabled:!0,max_bytes:32768};function oMo(e){return e?{enabled:e.enabled??f7r.enabled,max_bytes:Gvm(e.max_bytes,f7r.max_bytes)}:{...f7r}}function qvm(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>_vm.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var sMo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=oMo(t)}setConfig(t){this._config=oMo(t),this._trimToMaxBytes()}add(t){let r=Wvm(t);if(!r)return;let n=mju(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function Gvm(e,t){if(!LUt(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function Wvm(e){let t=Hvm(e);if(t)try{let r=JSON.parse(t);if(!MUt(r))return;let n=r,i=n[qUt.MESSAGE],o=n[qUt.TIMESTAMP];return!ixe(i)||i.trim().length===0||!ixe(o)&&!LUt(o)?void 0:{step:n,json:t}}catch{return}}function Hvm(e){let t=new WeakSet;try{return JSON.stringify(e,(r,n)=>{if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Date)return n.toISOString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){if(t.has(n))return"[Circular]";t.add(n)}return n}})}catch{return}}function mju(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}var Aju=require("fs"),yju=require("readline"),d7r=new rz.ReduceableCache(25),bju=new rz.ReduceableCache(20),aMo=7,Kvm=1e3,Jvm=1e4;async function Eju(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||$vm(s)||exm(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(bju.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=rxm(o);if(s.every(c=>txm(i,c)))continue;let a=nxm(d7r,i,{});n.push(Yvm(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Xvm(e,d7r),d7r.reduce(),e}function Yvm(e,t,r){return new Promise(n=>{let i=(0,Aju.createReadStream)(e),o=(0,yju.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){bju.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=ixm(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Xvm(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;Zvm(r.lineno,r,n)}}function Zvm(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Iju(e);i<e;i++){let o=r[i];if(o===void 0)return void hju(t);t.pre_context.push(o)}if(r[e]===void 0)return void hju(t);t.context_line=r[e];let n=vju(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function hju(e){delete e.pre_context,delete e.context_line,delete e.post_context}function $vm(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function exm(e){return e.lineno!==void 0&&e.lineno>Jvm||e.colno!==void 0&&e.colno>Kvm}function txm(e,t){let r=d7r.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function rxm(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=gju(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+aMo:(i.push(n),n=gju(o)),t++}return i}function gju(e){return[Iju(e),vju(e)]}function Iju(e){return Math.max(1,e-aMo)}function vju(e){return e+aMo}function nxm(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function ixm(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var eot=require("path");function xju(e=process.cwd()){let t=eot.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,eot.isAbsolute)(o.filename)&&(o.filename=r((0,eot.relative)(n,r(o.filename))));return i}}function oxm(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Cju(e,t){globalThis.process?.on("uncaughtException",oxm(e,t))}function wju(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var sxm=2e3,hH=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new YGr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return MUt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Cju(this.onException.bind(this),this.onFatalError.bind(this)),wju(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(sxm),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Sju="5.35.1";var Nfe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var tot=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t){let r=this._flags[t];return this._recordAccess(t),r?.enabled??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Nfe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Nfe.QUOTA_LIMITED),r===void 0&&o.push(Nfe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};async function Tju(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var axm=6e4,cxm=1152921504606847e3,uxm=["is_not","is_set"],rot=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},zd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Pee=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},m7r=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof Pee||u instanceof zd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Pee||u instanceof zd?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new zd("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new zd("Flag has unknown group type index");if(!(u in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new zd(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new zd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new zd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new zd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new zd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new zd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new zd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new zd(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){let o=t.filters||{},s=o.groups||[],a=o.aggregation_group_type_index,{groups:c,groupProperties:u}=i,l=!1,p;for(let d of s)try{let f=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,m=n,g=r;if(f!==a&&f!=null){let A=this.groupTypeMapping[String(f)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${f} not available`));continue}if(!(A in u)){l=!0;continue}m=u[A],g=c[A]}if(await this.isConditionMatch(t,g,d,m,i)){let A=d.variant,y=o.multivariate?.variants||[];p=A&&y.some(E=>E.key===A)?A:await this.getMatchingVariant(t,g)||!0;break}}catch(f){if(f instanceof Pee)throw f;if(f instanceof zd)l=!0;else throw f}if(p!==void 0)return p;if(l)throw new zd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?await Rju(c,i,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,i,o)):u==="flag"?await this.evaluateFlagDependency(c,i,o):Dju(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await Oju(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await Oju(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(axm,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rot(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new rot(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rot(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof rot&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=Oee(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Oju(e,t,r=""){let n=await Tju(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/cxm}function Dju(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new zd(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!uxm.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return Bju(String(i))&&String(s).match(String(i))!==null;case"not_regex":return Bju(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:parseFloat(String(i)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(u)&&Number.isFinite(l)?c(l,u,o):c(String(s),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new zd("Date operations cannot be performed on boolean values");let u=mxm(String(i));if(u==null&&(u=Pju(i)),u==null)throw new zd(`Invalid date: ${i}`);let l=Pju(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return M_(FB(String(s)),FB(String(i)))===0;case"semver_neq":return M_(FB(String(s)),FB(String(i)))!==0;case"semver_gt":return M_(FB(String(s)),FB(String(i)))>0;case"semver_gte":return M_(FB(String(s)),FB(String(i)))>=0;case"semver_lt":return M_(FB(String(s)),FB(String(i)))<0;case"semver_lte":return M_(FB(String(s)),FB(String(i)))<=0;case"semver_tilde":{let u=FB(String(s)),{lower:l,upper:p}=pxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}case"semver_caret":{let u=FB(String(s)),{lower:l,upper:p}=fxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}case"semver_wildcard":{let u=FB(String(s)),{lower:l,upper:p}=dxm(String(i));return M_(u,l)>=0&&M_(u,p)<0}default:throw new zd(`Unknown operator: ${o}`)}}function lxm(e,t){if(!(e in t))throw new Pee(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Rju(e,t,r,n=!1,i){let o=String(e.value);lxm(o,r);let s=r[o];return kju(s,t,r,n,i)}async function kju(e,t,r,n=!1,i){if(!e)return!0;let o=e.type,s=e.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let c of s)try{let u=await kju(c,t,r,n,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Pee)throw u;if(u instanceof zd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new zd("Can't match cohort without a given cohort property value");return o==="AND"}for(let c of s)try{let u;if(c.type==="cohort")u=await Rju(c,t,r,n,i);else if(c.type==="flag"){if(!i)throw new zd(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(c)}else u=Dju(c,t);let l=c.negation||!1;if(o==="AND"){if(!u&&!l||u&&l)return!1}else if(u&&!l||!u&&l)return!0}catch(u){if(u instanceof Pee)throw u;if(u instanceof zd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new zd("can't match cohort without a given cohort property value");return o==="AND"}function Bju(e){try{return new RegExp(e),!0}catch{return!1}}function Fju(e,t){if(!/^\d+$/.test(e))throw new zd(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new zd(`Invalid semver: ${t}`);return parseInt(e,10)}function FB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new zd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>c===void 0||c===""?0:Fju(c,e),o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function M_(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function pxm(e){let t=FB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function fxm(e){let t=FB(e),[r,n,i]=t,o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function dxm(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new zd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=c=>{try{return Fju(c,e)}catch{throw new zd(`Invalid wildcard semver: ${e}`)}},o=i(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let c=i(n[1]);s=[o,c,0],a=[o,c+1,0]}return{lower:s,upper:a}}function Pju(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 zd(`${e} is in an invalid date format`)}throw new zd(`The date provided ${e} must be a string, number, or date object`)}function mxm(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var h7r=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var hxm=100,Nju=3e4,gxm=5e4,Axm=50,yxm=500,bxm="https://us.i.posthog.com",jju=new Set;function g7r(e,t){jju.has(e)||(jju.add(e),console.warn(`[PostHog] ${t}`))}function Exm(e){return typeof e=="string"?e.trim():""}function Ixm(e){return(typeof e=="string"?e.trim():"")||void 0}function vxm(e){return(typeof e=="string"?e.trim():"")||bxm}function xxm(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var A7r=class extends _Ut{constructor(t,r={}){let n=Exm(t),i={...r,host:vxm(r.host),personalApiKey:Ixm(r.personalApiKey)};if(super(n,i),this._memoryStorage=new h7r,this.options=i,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,hxm):Nju,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new m7r({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new hH(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||gxm}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??yxm,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Axm;this._waitUntilCycle.timer=Oee(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return Sju}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=Nju){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let T=this._flagOverrides[t];if(T===void 0)return;let P=this._payloadOverrides?.[t];return{key:t,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:P}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,E,x,I;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let T=this.featureFlagsPoller?.featureFlagsByKey[t];if(T)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(T,d,{matchValue:i});if(P){m=!0;let D=P.value;E=T.id,I="Evaluated locally",f={key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof Pee||P instanceof zd)this._logger?.info(`${P.name} when computing flag locally: ${t}: ${P.message}`);else throw P}}if(!m&&!c){let T=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(T===void 0)y=Nfe.UNKNOWN_ERROR;else{g=T.requestId,A=T.evaluatedAt;let P=[];T.errorsWhileComputingFlags&&P.push(Nfe.ERRORS_WHILE_COMPUTING),T.quotaLimited?.includes("feature_flags")&&P.push(Nfe.QUOTA_LIMITED);let D=T.flags[t];if(D===void 0)P.push(Nfe.FLAG_MISSING);else{E=D.metadata?.id,x=D.metadata?.version,I=D.reason?.description??D.reason?.code;let S;if(D.metadata?.payload!==void 0)try{S=JSON.parse(D.metadata.payload)}catch{S=D.metadata.payload}f={key:t,enabled:D.enabled,variant:D.variant,payload:S}}P.length>0&&(y=P.join(","))}}if(o){let T=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,P={$feature_flag:t,$feature_flag_response:T,$feature_flag_id:E,$feature_flag_version:x,$feature_flag_reason:I,locally_evaluated:m,[`$feature/${t}`]:T,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let D=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();D!==void 0&&(P.$feature_flag_definitions_loaded_at=D)}y&&(P.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:T,groups:s,disableGeoip:a,properties:P})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){g7r("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(g7r("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){g7r("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...y.flags||{}},g={...g,...y.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new tot({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f={},m,g,A=!1,y=!1,E=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(E)for(let[C,T]of Object.entries(E.response)){let P=this.featureFlagsPoller?.featureFlagsByKey[C];f[C]={key:C,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:E.payloads[C],id:P?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0},x.add(C)}if((E?E.fallbackToFlags:!0)&&!c){let C=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);if(C){m=C.requestId,g=C.evaluatedAt,A=!!C.errorsWhileComputingFlags,y=Array.isArray(C.quotaLimited)&&C.quotaLimited.includes("feature_flags");for(let[T,P]of Object.entries(C.flags)){if(x.has(T))continue;let D;if(P.metadata?.payload!==void 0)try{D=JSON.parse(P.metadata.payload)}catch{D=P.metadata.payload}f[T]={key:T,enabled:P.enabled,variant:P.variant,payload:D,id:P.metadata?.id,version:P.metadata?.version,reason:P.reason?.description??P.reason?.code,locallyEvaluated:!1}}}}if(this._flagOverrides!==void 0)for(let[C,T]of Object.entries(this._flagOverrides)){if(T===void 0){delete f[C];continue}let P=f[C];f[C]={key:C,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:P?.payload,id:P?.id,version:P?.version,reason:P?.reason,locallyEvaluated:P?.locallyEvaluated??!1}}if(this._payloadOverrides!==void 0)for(let[C,T]of Object.entries(this._payloadOverrides)){let P=f[C];P&&(f[C]={...P,payload:T})}return new tot({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:f,requestId:m,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:A,quotaLimited:y})}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=`${n}_${i}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].includes(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(c):this.distinctIdHasSentFlagCalls[r]=[c],this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=Oee(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(VNu(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!hH.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(hH.buildEventMessage(t,{syntheticException:s},r,n).then(a=>this.capture({...a,uuid:i,flags:o})))}}async captureExceptionImmediate(t,r,n,i){if(!hH.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(hH.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=t,p=this.context?.get(),d=r||p?.distinctId,f={...this.props,...p?.properties||{},...i||{}};d||(d=Tee(),f.$process_person_profile=!1),p?.sessionId&&!f.$session_id&&(f.$session_id=p.sessionId);let m=this._runBeforeSend({distinctId:d,event:n,properties:f,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!m)return Promise.reject(null);let g=await Promise.resolve().then(async()=>{if(s)return a&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),s._getEventProperties();if(a){g7r("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let A=typeof a=="object"?a:void 0,y=await this.getFeatureFlagsForEvent(m.distinctId,o,u,A);return xxm(y)}return{}}).catch(()=>({})).then(A=>({...A,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof g.$raw_user_agent=="string"&&QNu(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",g.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:g,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var Qju=require("async_hooks"),y7r=class{constructor(){this.storage=new Qju.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var zju="posthog-node";function Cxm(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[cMo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(g=>({...g,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var cMo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=zju,this.name=zju,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Cxm(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};hH.errorPropertiesBuilder=new rz.ErrorPropertiesBuilder([new rz.EventCoercer,new rz.ErrorCoercer,new rz.ObjectCoercer,new rz.StringCoercer,new rz.PrimitiveCoercer],rz.createStackParser("node:javascript",rz.nodeStackLineParser),[FNu(),Eju,xju()]);var oxe=class extends A7r{getLibraryId(){return"posthog-node"}initializeContext(){return new y7r}};var b7r=class{posthog;constructor({posthogApiKey:t}){this.posthog=new oxe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.110.1",usingAccessToken:!0,...Ace()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var GUt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Fd();Yt();var not=require("fs/promises"),Mju=require("os"),Lju=require("path");Vrt();var wxm="id",Sxm=".fern",WUt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new oxe(r),this.userId=t==null?void 0:Dko(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.110.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{},...Ace()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Of({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=PD(),r=Me(Ut.of((0,Mju.homedir)()),ve.of(Sxm),ve.of(wxm));try{await Xt(r)?this.persistedDistinctId=(await(0,not.readFile)(r)).toString():(await(0,not.mkdir)((0,Lju.dirname)(r),{recursive:!0}),await(0,not.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var uMo;async function HUt(){return uMo==null&&(uMo=await Txm()),uMo}async function Txm(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new GUt;let r=await ynt();return r!=null?new WUt({token:r,posthogApiKey:e}):await KQ()!=null?new b7r({posthogApiKey:e}):new WUt({token:void 0,posthogApiKey:e})}catch{return new GUt}}En();Tt();Qt();m_();var KUt=ye(require("process"),1);ZGe();var _ju=ye(gwo(),1),qju=ye(Uju(),1);function H1(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=YG(e),e.length===0))return 0;e=e.replace((0,qju.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(_ju.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function E7r(e){let t=0;for(let r of e.split(`
3364
3364
  `))t=Math.max(t,H1(r));return t}var lQu=ye(pMo(),1);var Bxm=/[\p{Lu}]/u,Pxm=/[\p{Ll}]/u,Hju=/^[\p{Lu}](?![\p{Lu}])/gu,Yju=/([\p{Alpha}\p{N}_]|$)/u,fMo=/[_.\- ]+/,Dxm=new RegExp("^"+fMo.source),Kju=new RegExp(fMo.source+Yju.source,"gu"),Jju=new RegExp("\\d+"+Yju.source,"gu"),Rxm=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&Bxm.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Pxm.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},kxm=(e,t)=>(Hju.lastIndex=0,e.replace(Hju,r=>t(r))),Fxm=(e,t)=>(Kju.lastIndex=0,Jju.lastIndex=0,e.replace(Kju,(r,n)=>t(n)).replace(Jju,r=>t(r)));function dMo(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?fMo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Rxm(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Dxm,""),e=t.preserveConsecutiveUppercase?kxm(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Fxm(e,n))}var AMo=ye(Zju(),1);ZGe();var $ju=(e=0)=>t=>`\x1B[${t+e}m`,eQu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,tQu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,k0={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},MNI=Object.keys(k0.modifier),zxm=Object.keys(k0.color),Mxm=Object.keys(k0.bgColor),LNI=[...zxm,...Mxm];function Lxm(){let e=new Map;for(let[t,r]of Object.entries(k0)){for(let[n,i]of Object.entries(r))k0[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=k0[n],e.set(i[0],i[1]);Object.defineProperty(k0,t,{value:r,enumerable:!1})}return Object.defineProperty(k0,"codes",{value:e,enumerable:!1}),k0.color.close="\x1B[39m",k0.bgColor.close="\x1B[49m",k0.color.ansi=$ju(),k0.color.ansi256=eQu(),k0.color.ansi16m=tQu(),k0.bgColor.ansi=$ju(10),k0.bgColor.ansi256=eQu(10),k0.bgColor.ansi16m=tQu(10),Object.defineProperties(k0,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>k0.rgbToAnsi256(...k0.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>k0.ansi256ToAnsi(k0.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>k0.ansi256ToAnsi(k0.hexToAnsi256(t)),enumerable:!1}}),k0}var Vxm=Lxm(),rQu=Vxm;var I7r=new Set(["\x1B","\x9B"]),Uxm=39,hMo="\x07",oQu="[",_xm="]",sQu="m",gMo=`${_xm}8;;`,nQu=e=>`${I7r.values().next().value}${oQu}${e}${sQu}`,iQu=e=>`${I7r.values().next().value}${gMo}${e}${hMo}`,qxm=e=>e.split(" ").map(t=>H1(t)),mMo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=H1(YG(e[e.length-1]));for(let[a,c]of n.entries()){let u=H1(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),I7r.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(gMo)),i){o?c===hMo&&(i=!1,o=!1):c===sQu&&(i=!1);continue}s+=u,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Gxm=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(H1(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Wxm=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=qxm(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=H1(a[a.length-1]);if(u!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),mMo(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){mMo(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){mMo(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>Gxm(u)));let c=[...a.join(`
3365
3365
  `)];for(let[u,l]of c.entries()){if(n+=l,I7r.has(l)){let{groups:d}=new RegExp(`(?:\\${oQu}(?<code>\\d+)m|\\${gMo}(?<uri>.*)${hMo})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Uxm?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=rQu.codes.get(Number(i));c[u+1]===`
3366
3366
  `?(o&&(n+=iQu("")),i&&p&&(n+=nQu(p))):l===`
@@ -3934,7 +3934,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
3934
3934
  Add a 'docs:' section to your fern.yml to get started.`,code:O.Code.ConfigError});let o=await new RPe({context:t}).check({workspace:n,strict:r.strict}),s=new Set(o.mdxParseErrors.map(p=>p.displayRelativeFilepath)),a=new Set(o.mdxParseErrors.map(p=>p.rawMessage)),c=o.violations.filter(p=>!(s.size>0&&tlh(p,s,a))),u=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let p=this.buildJsonResponse({result:o,filteredViolations:c,hasErrors:u});if(t.stdout.info(JSON.stringify(p,null,2)),u)throw new O({code:O.Code.ValidationError});return}if(c.length>0)for(let p of c){let d=p.severity==="warning"?fe.yellow:fe.red;process.stderr.write(`${d(`${p.displayRelativeFilepath}:${p.line}:${p.column}: ${p.message}`)}
3935
3935
  `)}let l=0;if(o.mdxParseErrors.length>0){for(let p of o.mdxParseErrors)t.stderr.info(`
3936
3936
  ${p.toString()}
3937
- `);r.fix?l+=await Hri(t,o.mdxParseErrors):process.stdout.isTTY===!0&&!p$n()&&await Kri(t,o.mdxParseErrors)}if(r.fix&&c.length>0){let d=await new d0t({context:t}).fix({workspace:n,violations:c});l+=d.fixedCount}if(u&&(!r.fix||l===0))throw new O({code:O.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${Dr.warning} ${fe.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(fe.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Dr.success} ${fe.green("All checks passed")}`)}buildJsonResponse({result:t,filteredViolations:r,hasErrors:n}){let i={};return(r.length>0||t.mdxParseErrors.length>0)&&(i.docs=[...r.map(o=>Nee(o)),...t.mdxParseErrors.map(o=>({severity:"error",rule:o.code.code,filepath:o.displayRelativeFilepath,...o.line!=null?{line:o.line}:{},...o.column!=null?{column:o.column}:{},message:`[${o.code.code}] ${o.code.title}: ${o.rawMessage}`}))]),{success:!n,results:i}}};function tlh(e,t,r){if(!/failed to parse|failed to initialize/i.test(e.message))return!1;for(let n of r)if(n.length>0&&e.message.includes(n))return!0;for(let n of t){if(e.message.includes(n))return!0;let i=n.split("/").filter(Boolean);for(let o=i.length;o>=2;o--){let s=i.slice(i.length-o).join("/");if(e.message.includes(s))return!0}if(i.length===1){let o=i[0];if(o!=null&&e.message.includes(o))return!0}}return!1}function z$o(e){let t=new Q$o;ti(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}).option("fix",{type:"boolean",description:"Automatically fix issues that have a known resolution",default:!1}))}vb();Qt();var Rll=ye(require("net"),1),kll=ye(require("os"),1),Xri=class extends Error{constructor(t){super(`${t} is locked`)}},A0t={old:new Set,young:new Set},rlh=1e3*15,Fll=new Set;var Lqt,nlh=()=>{let e=kll.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},Pll=e=>new Promise((t,r)=>{let n=Rll.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),Dll=async(e,t)=>{if(e.host||e.port===0)return Pll(e);for(let r of t)try{await Pll({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},ilh=e=>A0t.old.has(e)||A0t.young.has(e)||Fll.has(e),olh=function*(e){e&&(yield*e),yield 0};async function FPe(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};Lqt===void 0&&(Lqt=setTimeout(()=>{Lqt=void 0,A0t.old=A0t.young,A0t.young=new Set},rlh),Lqt.unref&&Lqt.unref());let o=nlh();for(let s of olh(t))try{if(r.has(s))continue;let a=await Dll({...i,port:s},o);for(;ilh(a);){if(s!==0)throw new Xri(s);a=await Dll({...i,port:s},o)}return n?Fll.add(a):A0t.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Xri))throw a}throw new Error("No available ports found")}Qt();var Qll=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Nll="docs.buildwithfern.com",jll=62;function iVe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),Qll.test(t)}function zll(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function Vqt({orgId:e,previewId:t}){let r=zll(t),n=`${e}-preview-${r}.${Nll}`;if(n.length<=jll)return n;let i=`${e}-preview-`,o=jll-i.length;if(o<8)throw new O({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:O.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Nll}`}Tt();sx();Jm();Yt();PI();Qt();En();var Cns=require("child_process"),cvl=ye(V$o(),1),wns=ye(Qni(),1),Sns=ye(require("fs"),1),eDe=require("fs/promises"),uvl=ye(require("http"),1),lvl=ye(require("os"),1),Soi=ye(require("path"),1);Zni();Yt();var q9=require("fs/promises"),vgl=require("os"),Ots=ye(require("path"),1),Wyh=".fern",Hyh="logs",Tts=100*1024*1024;function Kyh(){return"cli@5.110.0"}var yVe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Me(Me(Ut.of((0,vgl.homedir)()),ve.of(Wyh)),ve.of(Hyh));await Xt(n)||await(0,q9.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Me(n,ve.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Ots.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
3937
+ `);r.fix?l+=await Hri(t,o.mdxParseErrors):process.stdout.isTTY===!0&&!p$n()&&await Kri(t,o.mdxParseErrors)}if(r.fix&&c.length>0){let d=await new d0t({context:t}).fix({workspace:n,violations:c});l+=d.fixedCount}if(u&&(!r.fix||l===0))throw new O({code:O.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${Dr.warning} ${fe.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(fe.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Dr.success} ${fe.green("All checks passed")}`)}buildJsonResponse({result:t,filteredViolations:r,hasErrors:n}){let i={};return(r.length>0||t.mdxParseErrors.length>0)&&(i.docs=[...r.map(o=>Nee(o)),...t.mdxParseErrors.map(o=>({severity:"error",rule:o.code.code,filepath:o.displayRelativeFilepath,...o.line!=null?{line:o.line}:{},...o.column!=null?{column:o.column}:{},message:`[${o.code.code}] ${o.code.title}: ${o.rawMessage}`}))]),{success:!n,results:i}}};function tlh(e,t,r){if(!/failed to parse|failed to initialize/i.test(e.message))return!1;for(let n of r)if(n.length>0&&e.message.includes(n))return!0;for(let n of t){if(e.message.includes(n))return!0;let i=n.split("/").filter(Boolean);for(let o=i.length;o>=2;o--){let s=i.slice(i.length-o).join("/");if(e.message.includes(s))return!0}if(i.length===1){let o=i[0];if(o!=null&&e.message.includes(o))return!0}}return!1}function z$o(e){let t=new Q$o;ti(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}).option("fix",{type:"boolean",description:"Automatically fix issues that have a known resolution",default:!1}))}vb();Qt();var Rll=ye(require("net"),1),kll=ye(require("os"),1),Xri=class extends Error{constructor(t){super(`${t} is locked`)}},A0t={old:new Set,young:new Set},rlh=1e3*15,Fll=new Set;var Lqt,nlh=()=>{let e=kll.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},Pll=e=>new Promise((t,r)=>{let n=Rll.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),Dll=async(e,t)=>{if(e.host||e.port===0)return Pll(e);for(let r of t)try{await Pll({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},ilh=e=>A0t.old.has(e)||A0t.young.has(e)||Fll.has(e),olh=function*(e){e&&(yield*e),yield 0};async function FPe(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};Lqt===void 0&&(Lqt=setTimeout(()=>{Lqt=void 0,A0t.old=A0t.young,A0t.young=new Set},rlh),Lqt.unref&&Lqt.unref());let o=nlh();for(let s of olh(t))try{if(r.has(s))continue;let a=await Dll({...i,port:s},o);for(;ilh(a);){if(s!==0)throw new Xri(s);a=await Dll({...i,port:s},o)}return n?Fll.add(a):A0t.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Xri))throw a}throw new Error("No available ports found")}Qt();var Qll=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Nll="docs.buildwithfern.com",jll=62;function iVe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),Qll.test(t)}function zll(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function Vqt({orgId:e,previewId:t}){let r=zll(t),n=`${e}-preview-${r}.${Nll}`;if(n.length<=jll)return n;let i=`${e}-preview-`,o=jll-i.length;if(o<8)throw new O({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:O.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Nll}`}Tt();sx();Jm();Yt();PI();Qt();En();var Cns=require("child_process"),cvl=ye(V$o(),1),wns=ye(Qni(),1),Sns=ye(require("fs"),1),eDe=require("fs/promises"),uvl=ye(require("http"),1),lvl=ye(require("os"),1),Soi=ye(require("path"),1);Zni();Yt();var q9=require("fs/promises"),vgl=require("os"),Ots=ye(require("path"),1),Wyh=".fern",Hyh="logs",Tts=100*1024*1024;function Kyh(){return"cli@5.110.1"}var yVe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Me(Me(Ut.of((0,vgl.homedir)()),ve.of(Wyh)),ve.of(Hyh));await Xt(n)||await(0,q9.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Me(n,ve.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Ots.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
3938
3938
  `);await(0,q9.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
3939
3939
  `;try{await(0,q9.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:Kyh(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}async enforceLogSizeLimit(t){try{let n=(await(0,q9.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=Ots.default.join(t,c);try{let l=await(0,q9.stat)(u);i.push({name:c,fullPath:u,size:l.size,mtimeMs:l.mtimeMs})}catch{}}let o=i.reduce((c,u)=>c+u.size,0),s=Math.round(o/1024/1024*100)/100,a=Tts/1024/1024;if(o<=Tts){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,u)=>c.mtimeMs-u.mtimeMs);for(let c of i){if(o<=Tts)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,q9.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var $ni={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function xgl(e){let t=Jyh();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(u){let l=JSON.stringify(u),p=[];for(let[d]of s)try{d.send(l)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(u,l){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:$ni});let p=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){l.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await u.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...$ni}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...$ni}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return u.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:$ni}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:l}=u.data,p=setInterval(()=>{let d=s.get(u);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:f}))}catch{u.close()}},3e4);s.set(u,{pingInterval:p,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:l}))}catch{}},message(u,l){try{let p=JSON.parse(l.toString());if(p.type==="pong"){let d=s.get(u);d&&(d.lastPong=Date.now())}else yVe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(u){let l=s.get(u);l&&(clearInterval(l.pingInterval),s.delete(u))}}});return{sendData:a,stop:u=>c.stop(u)}}function Jyh(){return globalThis.Bun}Qt();var Ugl=require("events"),iii=ye(require("fs"),1),EVe=ye(require("path"),1);var Cgl=ye(require("os"),1),wgl=300,_Pe=20,EGt=1e7,Sgl=Cgl.default.platform();var Yyh=Sgl==="darwin",Bts=Sgl==="win32",qPe=Yyh||Bts,Tgl=3e3,Ogl=2e4,Pts=1250;var Lie;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Lie||(Lie={}));var bVe;(function(e){e.CHANGE="change",e.RENAME="rename"})(bVe||(bVe={}));var IGt;(function(e){e.CHANGE="change",e.ERROR="error"})(IGt||(IGt={}));var Tc;(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"})(Tc||(Tc={}));var hN;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(hN||(hN={}));var Xyh=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let I=Date.now(),C=I-c,T=I-u,P=C>=t||T>=o;return[I,P]},p=I=>{if(u=I,!s)return;let C=s;s=void 0,e.apply(void 0,C)},d=()=>{E(0)},f=()=>{a&&(d(),p(Date.now()))},m=I=>{if(u=I,n)return p(I)},g=I=>{if(i&&s)return p(I);s=void 0},A=()=>{a=void 0;let[I,C]=l();return C?g(I):y(I)},y=I=>{let C=I-c,T=I-u,P=t-C,D=o-T,S=Math.min(P,D);return E(S)},E=I=>{a&&clearTimeout(a),!(I<=0)&&(a=setTimeout(A,I))},x=(...I)=>{let[C,T]=l(),P=!!a;if(s=I,c=C,(T||!a)&&E(t),T)return P?p(C):m(C)};return x.cancel=d,x.flush=f,x},eii=Xyh;var Fts=ye(require("fs"),1),rii=ye(require("path"),1);var Ud=ye(require("fs"),1),YB=require("util");var dme=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Vie=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Dts=ye(require("process"),1),Bgl=Dts.default.getuid?!Dts.default.getuid():!1,Pgl=1e4,IM=()=>{};var vGt={isChangeErrorOk:e=>{if(!vGt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Bgl&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!vGt.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(!vGt.isNodeError(e))throw e;if(!vGt.isChangeErrorOk(e))throw e}},ax=vGt;var Rts=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Pgl,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Dgl=new Rts;var mme=(e,t)=>function(n){return function i(...o){return Dgl.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},hme=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var Zyh={attempt:{chmod:dme((0,YB.promisify)(Ud.default.chmod),ax.onChangeError),chown:dme((0,YB.promisify)(Ud.default.chown),ax.onChangeError),close:dme((0,YB.promisify)(Ud.default.close),IM),fsync:dme((0,YB.promisify)(Ud.default.fsync),IM),mkdir:dme((0,YB.promisify)(Ud.default.mkdir),IM),realpath:dme((0,YB.promisify)(Ud.default.realpath),IM),stat:dme((0,YB.promisify)(Ud.default.stat),IM),unlink:dme((0,YB.promisify)(Ud.default.unlink),IM),chmodSync:Vie(Ud.default.chmodSync,ax.onChangeError),chownSync:Vie(Ud.default.chownSync,ax.onChangeError),closeSync:Vie(Ud.default.closeSync,IM),existsSync:Vie(Ud.default.existsSync,IM),fsyncSync:Vie(Ud.default.fsync,IM),mkdirSync:Vie(Ud.default.mkdirSync,IM),realpathSync:Vie(Ud.default.realpathSync,IM),statSync:Vie(Ud.default.statSync,IM),unlinkSync:Vie(Ud.default.unlinkSync,IM)},retry:{close:mme((0,YB.promisify)(Ud.default.close),ax.isRetriableError),fsync:mme((0,YB.promisify)(Ud.default.fsync),ax.isRetriableError),open:mme((0,YB.promisify)(Ud.default.open),ax.isRetriableError),readFile:mme((0,YB.promisify)(Ud.default.readFile),ax.isRetriableError),rename:mme((0,YB.promisify)(Ud.default.rename),ax.isRetriableError),stat:mme((0,YB.promisify)(Ud.default.stat),ax.isRetriableError),write:mme((0,YB.promisify)(Ud.default.write),ax.isRetriableError),writeFile:mme((0,YB.promisify)(Ud.default.writeFile),ax.isRetriableError),closeSync:hme(Ud.default.closeSync,ax.isRetriableError),fsyncSync:hme(Ud.default.fsyncSync,ax.isRetriableError),openSync:hme(Ud.default.openSync,ax.isRetriableError),readFileSync:hme(Ud.default.readFileSync,ax.isRetriableError),renameSync:hme(Ud.default.renameSync,ax.isRetriableError),statSync:hme(Ud.default.statSync,ax.isRetriableError),writeSync:hme(Ud.default.writeSync,ax.isRetriableError),writeFileSync:hme(Ud.default.writeFileSync,ax.isRetriableError)}},Rgl=Zyh;var tii=ye(require("fs"),1),xGt=ye(require("path"),1);var kts=()=>{};var $yh=()=>{let e=kts,t=kts,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},kgl=$yh;var ebh=()=>{let{promise:e,resolve:t,isPending:r}=kgl(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},Fgl=ebh;var Ngl={then:e=>{e()}};var jgl=e=>Array.isArray(e)?e:[e],Qgl=e=>typeof e=="function";var tbh=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=jgl(o).map(se=>Qgl(se)?se:de=>se.test(de)),a=se=>s.some(de=>de(se)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,g={},A=[],y=new Set,E={},x={},I=new Set,C={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},T={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:g,symlinks:A,symlinksNames:y,symlinksNamesToPaths:E,map:x},{promise:P,increment:D,decrement:S}=Fgl(),z=0,K=(se,de,Te,xe)=>{I.has(de)||z>=i||(z+=1,se.directories.push(de),se.directoriesNames.add(Te),l.push(de),p.add(Te),d.propertyIsEnumerable(Te)||(d[Te]=[]),d[Te].push(de),I.add(de),!(xe>=n)&&(z>=i||le(de,xe+1)))},Y=(se,de,Te)=>{I.has(de)||z>=i||(z+=1,se.files.push(de),se.filesNames.add(Te),f.push(de),m.add(Te),g.propertyIsEnumerable(Te)||(g[Te]=[]),g[Te].push(de),I.add(de))},$=(se,de,Te,xe)=>{I.has(de)||z>=i||(z+=1,se.symlinks.push(de),se.symlinksNames.add(Te),A.push(de),y.add(Te),E.propertyIsEnumerable(Te)||(E[Te]=[]),E[Te].push(de),I.add(de),r&&(xe>=n||z>=i||Oe(de,xe+1)))},ie=(se,de,Te,xe,je)=>{c.aborted||a(de)||(xe.isDirectory()?K(se,de,Te,je):xe.isFile()?Y(se,de,Te):xe.isSymbolicLink()&&$(se,de,Te,je))},pe=(se,de,Te,xe)=>{if(c.aborted)return;let je=de===xGt.default.sep?"":xGt.default.sep,Ke=Te.name,ot=`${de}${je}${Ke}`;a(ot)||(Te.isDirectory()?K(se,ot,Ke,xe):Te.isFile()?Y(se,ot,Ke):Te.isSymbolicLink()&&$(se,ot,Ke,xe))},ne=(se,de,Te,xe)=>{for(let je=0,Ke=Te.length;je<Ke;je++)pe(se,de,Te[je],xe)},le=(se,de)=>{c.aborted||de>n||z>=i||(D(),tii.default.readdir(se,{withFileTypes:!0},(Te,xe)=>{if(Te||c.aborted||!xe.length)return S();(u(xe)||Ngl).then(()=>{let Ke=x[se]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ne(Ke,se,xe,de),S()})}))},Oe=(se,de)=>{D(),tii.default.realpath(se,(Te,xe)=>{if(Te||c.aborted)return S();tii.default.stat(xe,(je,Ke)=>{if(je||c.aborted)return S();let ot=xGt.default.basename(xe),At=x[se]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ie(At,xe,ot,Ke,de),S()})})};return(async(se,de=1)=>(se=xGt.default.normalize(se),I.add(se),le(se,de),await P,c.aborted?C:T))(e)},zgl=tbh;var Uie={lang:{debounce:eii,attempt:e=>{try{return e()}catch(t){return Uie.lang.castError(t)}},castArray:e=>Uie.lang.isArray(e)?e:[e],castError:e=>Uie.lang.isError(e)?e:Uie.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(Uie.lang.isNaN(e))return Uie.lang.isNaN(t);if(Uie.lang.isPrimitive(e)||Uie.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(rii.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Fts.default.realpathSync.native(e):Fts.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===rii.default.sep&&t.length-e.length>rii.default.sep.length,poll:(e,t=Ogl)=>Rgl.retry.stat(t)(e,{bigint:!0}).catch(Uie.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await zgl(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},ep=Uie;var nii=ye(require("path"),1);var Nts=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||ep.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=wgl){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=ep.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===Tc.CHANGE&&a===Tc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===Tc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===Tc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??_Pe:Math.min(1,this.options.depth??_Pe),s=this.options.limit??EGt,[a,c]=await ep.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())ep.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Tc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!qPe&&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(Tc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Tc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(nii.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Tc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(nii.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(Tc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Tc.ADD?this.onTargetAdd(n):r===Tc.ADD_DIR?this.onTargetAddDir(n):r===Tc.CHANGE?this.onTargetChange(n):r===Tc.UNLINK?this.onTargetUnlink(n):r===Tc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=bVe.CHANGE,r){if(this.watcher.isClosed())return;let n=nii.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){Bts&&t.code==="EPERM"?this.onWatcherChange(bVe.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(IGt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(IGt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(bVe.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&qPe&&this.options.native!==!1?this.options.depth??_Pe:Math.min(1,this.options.depth??_Pe),n=this.options.limit??EGt,[i,o]=await ep.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(bVe.CHANGE,a,t)}))}}},Mgl=Nts;var gN={interval:100,intervalId:void 0,fns:new Map,init:()=>{gN.intervalId||(gN.intervalId=setInterval(gN.resolve,gN.interval))},reset:()=>{gN.intervalId&&(clearInterval(gN.intervalId),delete gN.intervalId)},add:(e,t)=>{gN.fns.set(e,Date.now()+t),gN.init()},remove:e=>{gN.fns.delete(e)},resolve:()=>{if(!gN.fns.size)return gN.reset();let e=Date.now();for(let[t,r]of gN.fns)r>=e||(gN.remove(t),t())}},CGt=gN;var wGt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Pts){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(ep.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),CGt.remove(u)},u=()=>{c(),a()};CGt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Pts){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),CGt.remove(u)},u=()=>{c(),a()};CGt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Tc.ADD,Lie.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Tc.ADD_DIR,Lie.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Tc.UNLINK,Lie.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Tc.UNLINK_DIR,Lie.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};wGt.DIR_EVENTS={add:Tc.ADD_DIR,rename:Tc.RENAME_DIR,unlink:Tc.UNLINK_DIR};wGt.FILE_EVENTS={add:Tc.ADD,change:Tc.CHANGE,rename:Tc.RENAME,unlink:Tc.UNLINK};var Lgl=wGt;var jts=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(ep.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(ep.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(ep.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(ep.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return ep.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);ep.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},Qts=jts;var zts=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}},Vgl=zts;var Mts=class{constructor(){this.inos={},this.paths=new Qts,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await ep.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new Vgl(n)}reset(){this.inos={},this.paths=new Qts,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Tc.ADD,i),[Tc.ADD];if(i.isDirectory())return this.updateIno(t,Tc.ADD_DIR,i),[Tc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Tc.UNLINK,n),[Tc.UNLINK];if(n.isDirectory())return this.updateIno(t,Tc.UNLINK_DIR,n),[Tc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Tc.CHANGE,i),[Tc.CHANGE]);if(i.isDirectory())return this.updateIno(t,Tc.UNLINK,n),this.updateIno(t,Tc.ADD_DIR,i),[Tc.UNLINK,Tc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Tc.UNLINK_DIR,n),this.updateIno(t,Tc.ADD,i),[Tc.UNLINK_DIR,Tc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Tc.UNLINK_DIR,n),this.updateIno(t,Tc.ADD_DIR,i),[Tc.UNLINK_DIR,Tc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?Lie.FILE:Lie.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},Lts=Mts;var Vts=class e extends Ugl.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(hN.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(hN.CLOSE,i)),this._readyWait=new Promise(i=>this.on(hN.READY,i)),this._locker=new Lgl(this),this._roots=new Set,this._poller=new Lts,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(ep.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(hN.CLOSE))}error(t){if(this.isClosed())return!1;let r=ep.lang.castError(t);return this.emit(hN.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(hN.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(hN.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&ep.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&ep.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)ep.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new Mgl(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=ep.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=EVe.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??_Pe))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&qPe&&l.options.native!==!1)))return!0;if(!qPe)break;let u=EVe.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=ep.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||qPe&&r.native!==!1?r:{...r,recursive:!1},l={watcher:iii.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=EVe.default.dirname(a),g=a;await this.watchDirectories([m],f,n,g,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||qPe&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??_Pe,a=r.limit??EGt,[c]=await ep.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=ep.fs.getDepth(t);for(let p of c){let d=ep.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(hN.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(hN.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=EVe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new Lts,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return ep.lang.noop;if(this.pollerExists(t,r))return ep.lang.noop;let i={...r,interval:r.pollingInterval??Tgl},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(hN.CLOSE,a),iii.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(hN.CLOSE,a),iii.default.unwatchFile(t,n)};return ep.lang.attempt(s),()=>ep.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=ep.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!ep.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=EVe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await ep.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=EVe.default.dirname(t);return(await ep.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=ep.lang.noop){if(ep.lang.isFunction(t))return this.watch([],{},t);if(ep.lang.isUndefined(t))return this.watch([],r,n);if(ep.lang.isFunction(r))return this.watch(t,{},r);if(ep.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=ep.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==ep.lang.noop&&this.on(hN.ALL,n),r.readdirMap=void 0,this.ready())}},_gl=Vts;function rbh(e){return"code"in e&&typeof e.code=="string"}function qgl(e){return e instanceof Error?e:new Error(String(e))}function Ggl(e){return rbh(e)&&e.code==="ENOSPC"?"Unable to watch Fern docs files for changes because the system limit for file watchers was reached. Close other file-watching processes or increase the file watcher limit, then restart `fern docs dev`.":`Unable to watch Fern docs files for changes: ${e.message}`}async function oii({absoluteFilePathToFern:e,additionalFilepaths:t,context:r}){let n=new _gl([e,...t],{recursive:!0,ignoreInitial:!0,debounce:100,renameDetection:!0}),i=await new Promise(o=>{let s=()=>{n.off("error",a),o(void 0)},a=c=>{n.off("ready",s),o(qgl(c))};n.once("ready",s),n.once("error",a)});return i!=null&&(n.close(),r.failAndThrow(Ggl(i),i,{code:O.Code.EnvironmentError})),n.on("error",o=>{let s=qgl(o);r.failWithoutThrowing(Ggl(s),s,{code:O.Code.EnvironmentError}),n.close()}),n}Yt();PI();Qt();En();var HIl=require("child_process"),yoi=ye(Yts(),1),KIl=ye(uns(),1),YE=require("fs"),tP=require("fs/promises"),JIl=require("os"),yN=ye(require("path"),1),YIl=ye(dE(),1),XIl=ye(WIl(),1),BVe=process.platform==="win32",Aoi=fe.cyan("[docs]:"),Rvh="etag",kvh=23,Ens=e=>e.padEnd(kvh," "),Fvh="preview",Nvh="app-preview",jvh="bundle",Qvh=".next",zvh="standalone",Mvh=".fern",Lvh="packages/fern-docs/bundle/.next/server/instrumentation.js",Vvh='Cannot find matching keyid: {"signatures":',Uvh="ERR_PNPM_IGNORED_BUILDS";function _vh(e){try{let r=(0,HIl.execSync)('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem" /v LongPathsEnabled',{encoding:"utf-8",timeout:5e3}).match(/LongPathsEnabled\s+REG_DWORD\s+0x(\d+)/i);if(r!=null&&r[1]==="1")return}catch(t){e.debug(`Registry query for LongPathsEnabled failed: ${t}`)}throw new O({message:`Windows long path support is not enabled. The docs bundle contains deeply nested .pnpm paths that exceed the 260-character MAX_PATH limit.
3940
3940
 
@@ -4284,7 +4284,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
4284
4284
  `);i.failAndThrow(s!=null?`No docs instance found matching '${s}'.
4285
4285
 
4286
4286
  Available instances:
4287
- ${I}`:"No docs instance found. Failed to register.",void 0,{code:O.Code.ConfigError});return}let E=(typeof y.customDomain=="string"?[y.customDomain]:y.customDomain??[]).map(i9l);o9l(y.url,E,i),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${y.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let x;return await i.runInteractiveTask({name:y.url},async()=>{let I=performance.now(),C=()=>GYl({docsWorkspace:n,customDomains:E,domain:y.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:y.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:y.audiences?Array.isArray(y.audiences)?y.audiences:[y.audiences]:void 0,docsUrl:y.url,cliVersion:p,ciSource:d,deployerAuthor:f,loginCommand:m,multiSource:y.multiSource??!1});for(let P=0;;P++)try{x=await C();break}catch(D){if(!(D instanceof aCt)||P>=CKt.length){if(D instanceof aCt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:O.Code.NetworkError});throw D}let S=CKt[P]??CKt[CKt.length-1]??6e4,z=S/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${z} minute${z===1?"":"s"} (attempt ${P+1}/${CKt.length})...`),await new Promise(K=>setTimeout(K,S))}let T=performance.now()-I;i.logger.debug(`Docs publishing completed in ${T.toFixed(0)}ms`)}),x}Qt();var Zhi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new dd({context:this.context,task:this.task});try{let s=await wKt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.110.0",loginCommand:"fern auth login"});return o.getResult()===Qf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:Nn(s)}}}};Tt();En();var cCt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4287
+ ${I}`:"No docs instance found. Failed to register.",void 0,{code:O.Code.ConfigError});return}let E=(typeof y.customDomain=="string"?[y.customDomain]:y.customDomain??[]).map(i9l);o9l(y.url,E,i),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${y.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let x;return await i.runInteractiveTask({name:y.url},async()=>{let I=performance.now(),C=()=>GYl({docsWorkspace:n,customDomains:E,domain:y.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:y.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:y.audiences?Array.isArray(y.audiences)?y.audiences:[y.audiences]:void 0,docsUrl:y.url,cliVersion:p,ciSource:d,deployerAuthor:f,loginCommand:m,multiSource:y.multiSource??!1});for(let P=0;;P++)try{x=await C();break}catch(D){if(!(D instanceof aCt)||P>=CKt.length){if(D instanceof aCt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:O.Code.NetworkError});throw D}let S=CKt[P]??CKt[CKt.length-1]??6e4,z=S/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${z} minute${z===1?"":"s"} (attempt ${P+1}/${CKt.length})...`),await new Promise(K=>setTimeout(K,S))}let T=performance.now()-I;i.logger.debug(`Docs publishing completed in ${T.toFixed(0)}ms`)}),x}Qt();var Zhi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new dd({context:this.context,task:this.task});try{let s=await wKt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.110.1",loginCommand:"fern auth login"});return o.getResult()===Qf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:Nn(s)}}}};Tt();En();var cCt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4288
4288
  `),this.stream.write(`${fe.cyan("\u25C6")} ${fe.bold(t.title)}
4289
4289
  `),t.subtitle!=null&&this.stream.write(` ${fe.dim(t.subtitle)}
4290
4290
  `),this.stream.write(`
@@ -4938,7 +4938,7 @@ ${r}`}function hEi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
4938
4938
  `),g="";return c&&(g=l.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
4939
4939
  `)]});var JHg=Ox((e,t)=>{let{validate:r=()=>!0}=e,n=lI(e.theme),[i,o]=$c("idle"),[s,a]=$c(),[c,u]=$c(""),l=Sx({status:i,theme:n});Tx(async(g,A)=>{if(i==="idle")if(wx(g)){let y=c;o("loading");let E=await r(y);E===!0?(u(y),o("done"),t(y)):(A.write(c),a(E||"You must provide a valid value"),o("idle"))}else u(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${$St}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[l,p,e.mask?d:f].join(" "),m]});var M8e=ye(Vw(),1);var YHg={icon:{cursor:yC.pointer},style:{disabled:e=>M8e.default.dim(`- ${e}`),searchTerm:e=>M8e.default.cyan(e),description:e=>M8e.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${M8e.default.bold(t)} ${M8e.default.dim(r)}`).join(M8e.default.dim(" \u2022 "))},helpMode:"always"};function rQs(e){return!Ed.isSeparator(e)&&!e.disabled}function XHg(e){return e.map(t=>{if(Ed.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var ZHg=Ox((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=lI(YHg,e.theme),[o,s]=$c("loading"),[a,c]=$c(""),[u,l]=$c([]),[p,d]=$c(),f=Sx({status:o,theme:i}),m=y6(()=>{let z=u.findIndex(rQs),K=u.findLastIndex(rQs);return{first:z,last:K}},[u]),[g=m.first,A]=$c();A4(()=>{let z=new AbortController;return s("loading"),d(void 0),(async()=>{try{let Y=await e.source(a||void 0,{signal:z.signal});z.signal.aborted||(A(void 0),d(void 0),l(XHg(Y)),s("idle"))}catch(Y){!z.signal.aborted&&Y instanceof Error&&d(Y.message)}})(),()=>{z.abort()}},[a]);let y=u[g];Tx(async(z,K)=>{if(wx(z))if(y){s("loading");let Y=await n(y.value);s("idle"),Y===!0?(s("done"),t(y.value)):y.name===a?d(Y||"You must provide a valid value"):(K.write(y.name),c(y.name))}else K.write(a);else if(rge(z)&&y)K.clearLine(0),K.write(y.name),c(y.name);else if(o!=="loading"&&(hP(z)||A6(z))){if(K.clearLine(0),hP(z)&&g!==m.first||A6(z)&&g!==m.last){let Y=hP(z)?-1:1,$=g;do $=($+Y+u.length)%u.length;while(!rQs(u[$]));A($)}}else c(K.line)});let E=i.style.message(e.message,o),x;if(i.helpMode!=="never")if(e.instructions){let{pager:z,navigation:K}=e.instructions;x=i.style.help(u.length>r?z:K)}else x=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let I=N8e({items:u,active:g,renderItem({item:z,isActive:K}){if(Ed.isSeparator(z))return` ${z.separator}`;if(z.disabled){let ie=typeof z.disabled=="string"?z.disabled:"(disabled)";return i.style.disabled(`${z.name} ${ie}`)}let Y=K?i.style.highlight:ie=>ie,$=K?i.icon.cursor:" ";return Y(`${$} ${z.name}`)},pageSize:r,loop:!1}),C;p?C=i.style.error(p):u.length===0&&a!==""&&o==="idle"&&(C=i.style.error("No results found"));let T;if(o==="done"&&y)return[f,E,i.style.answer(y.short)].filter(Boolean).join(" ").trimEnd();T=i.style.searchTerm(a);let P=y?.description,D=[f,E,T].filter(Boolean).join(" ").trimEnd(),S=[C??I," ",P?i.style.description(P):"",x].filter(Boolean).join(`
4940
4940
  `).trimEnd();return[D,S]});var t1t=ye(Vw(),1);var $Hg={icon:{cursor:yC.pointer},style:{disabled:e=>t1t.default.dim(`- ${e}`),description:e=>t1t.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${t1t.default.bold(t)} ${t1t.default.dim(r)}`).join(t1t.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function e1t(e){return!Ed.isSeparator(e)&&!e.disabled}function eKg(e){return e.map(t=>{if(Ed.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var nQs=Ox((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=lI($Hg,e.theme),{keybindings:o}=i,[s,a]=$c("idle"),c=Sx({status:s,theme:i}),u=F8e(),l=!o.includes("vim"),p=y6(()=>eKg(e.choices),[e.choices]),d=y6(()=>{let P=p.findIndex(e1t),D=p.findLastIndex(e1t);if(P===-1)throw new zae("[select prompt] No selectable choices. All choices are disabled.");return{first:P,last:D}},[p]),f=y6(()=>"default"in e?p.findIndex(P=>e1t(P)&&P.value===e.default):-1,[e.default,p]),[m,g]=$c(f===-1?d.first:f),A=p[m];Tx((P,D)=>{if(clearTimeout(u.current),wx(P))a("done"),t(A.value);else if(hP(P,o)||A6(P,o)){if(D.clearLine(0),r||hP(P,o)&&m!==d.first||A6(P,o)&&m!==d.last){let S=hP(P,o)?-1:1,z=m;do z=(z+S+p.length)%p.length;while(!e1t(p[z]));g(z)}}else if(PXt(P)&&!Number.isNaN(Number(D.line))){let S=Number(D.line)-1,z=-1,K=p.findIndex($=>Ed.isSeparator($)?!1:(z++,z===S)),Y=p[K];Y!=null&&e1t(Y)&&g(K),u.current=setTimeout(()=>{D.clearLine(0)},700)}else if(D8e(P))D.clearLine(0);else if(l){let S=D.line.toLowerCase(),z=p.findIndex(K=>Ed.isSeparator(K)||!e1t(K)?!1:K.name.toLowerCase().startsWith(S));z!==-1&&g(z),u.current=setTimeout(()=>{D.clearLine(0)},700)}}),A4(()=>()=>{clearTimeout(u.current)},[]);let y=i.style.message(e.message,s),E;if(i.helpMode!=="never")if(e.instructions){let{pager:P,navigation:D}=e.instructions;E=i.style.help(p.length>n?P:D)}else E=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=0,I=N8e({items:p,active:m,renderItem({item:P,isActive:D,index:S}){if(Ed.isSeparator(P))return x++,` ${P.separator}`;let z=i.indexMode==="number"?`${S+1-x}. `:"";if(P.disabled){let $=typeof P.disabled=="string"?P.disabled:"(disabled)";return i.style.disabled(`${z}${P.name} ${$}`)}let K=D?i.style.highlight:$=>$,Y=D?i.icon.cursor:" ";return K(`${Y} ${z}${P.name}`)},pageSize:n,loop:r});if(s==="done")return[c,y,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:C}=A;return`${[[c,y].filter(Boolean).join(" "),I," ",C?i.style.description(C):"",E].filter(Boolean).join(`
4941
- `).trimEnd()}${$St}`});En();Wi();var Mae={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},tKg={[Mae.GENERATION_STARTED]:!1,[Mae.GENERATION_COMPLETED]:!1,[Mae.GENERATION_FAILED]:!0,[Mae.VERIFICATION_FAILED]:!0,[Mae.SDK_PR_CREATED]:!1,[Mae.UPGRADE_APPLIED]:!1,[Mae.MAJOR_VERSION_BUMP]:!1};function zdp(e){return tKg[e]}function Mdp(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function Ldp(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function Vdp(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function Udp(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function _dp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Mae.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Mae.VERIFICATION_FAILED:Mae.GENERATION_FAILED}var rKg="",nKg="FERN_AUTOMATION_EVENTS_ORIGIN",iKg=3e3,XEi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[nKg]??rKg)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),iKg);try{let s={"content-type":"application/json"},a=await KQ();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(Udp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function qdp(){let{fern_run_id:e,github_run_id:t}=Ace();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.110.0"}}function Gdp(){return process.env.FERN_AUTOMATION==="true"}var ZEi=class{constructor(t,r=XEi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=qdp()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){await this.automationEventApiClient.shutdown()}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:Mdp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!zdp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:Ldp(t,r),context:{automation:Vdp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Qt();function $Ei(e,t,r){if(t instanceof ru)return;let n=C2e(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new O({message:s,code:n});Gdp()?sKg(i,e,n,s,a):oKg(e,o,n,a)}function oKg(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),xPt(r)&&e.captureException(n,{tags:{"error.code":r}})}function sKg(e,t,r,n,i){let o=_dp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Qt();function L8e(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function eIi({cliName:e,packageVersion:t,isLocal:r}){return L8e()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var tIi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(eIi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new O({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:O.Code.ConfigError});this.sentry=hPt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[kqe(),sAe(),aAe(),qge(),oAe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),gPt()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):vO(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Qt();var rIi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new O({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:O.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};jpe();Tt();vb();Qt();En();var FXt=class{result=Qf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:u}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=u}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new ru}failWithoutThrowing(t,r,n){this.result=Qf.Failure,!(r instanceof ru)&&(t!=null&&(this.lastFailureMessage=t),nLt({message:t,error:r,logger:this.logger}),$Ei(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=Av(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new iQs({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${fe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(i){n.failWithoutThrowing(void 0,i)}finally{n.finish()}return n.getResult()===Qf.Success}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
4941
+ `).trimEnd()}${$St}`});En();Wi();var Mae={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},tKg={[Mae.GENERATION_STARTED]:!1,[Mae.GENERATION_COMPLETED]:!1,[Mae.GENERATION_FAILED]:!0,[Mae.VERIFICATION_FAILED]:!0,[Mae.SDK_PR_CREATED]:!1,[Mae.UPGRADE_APPLIED]:!1,[Mae.MAJOR_VERSION_BUMP]:!1};function zdp(e){return tKg[e]}function Mdp(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function Ldp(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function Vdp(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function Udp(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function _dp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Mae.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Mae.VERIFICATION_FAILED:Mae.GENERATION_FAILED}var rKg="",nKg="FERN_AUTOMATION_EVENTS_ORIGIN",iKg=3e3,XEi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[nKg]??rKg)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),iKg);try{let s={"content-type":"application/json"},a=await KQ();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(Udp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function qdp(){let{fern_run_id:e,github_run_id:t}=Ace();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.110.1"}}function Gdp(){return process.env.FERN_AUTOMATION==="true"}var ZEi=class{constructor(t,r=XEi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=qdp()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){await this.automationEventApiClient.shutdown()}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:Mdp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!zdp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:Ldp(t,r),context:{automation:Vdp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Qt();function $Ei(e,t,r){if(t instanceof ru)return;let n=C2e(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new O({message:s,code:n});Gdp()?sKg(i,e,n,s,a):oKg(e,o,n,a)}function oKg(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),xPt(r)&&e.captureException(n,{tags:{"error.code":r}})}function sKg(e,t,r,n,i){let o=_dp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Qt();function L8e(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function eIi({cliName:e,packageVersion:t,isLocal:r}){return L8e()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var tIi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(eIi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new O({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:O.Code.ConfigError});this.sentry=hPt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[kqe(),sAe(),aAe(),qge(),oAe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),gPt()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):vO(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Qt();var rIi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new O({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:O.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};jpe();Tt();vb();Qt();En();var FXt=class{result=Qf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:u}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=u}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new ru}failWithoutThrowing(t,r,n){this.result=Qf.Failure,!(r instanceof ru)&&(t!=null&&(this.lastFailureMessage=t),nLt({message:t,error:r,logger:this.logger}),$Ei(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=Av(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new iQs({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${fe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(i){n.failWithoutThrowing(void 0,i)}finally{n.finish()}return n.getResult()===Qf.Success}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
4942
4942
  `)}},iQs=class extends FXt{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(_n.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===Qf.Success?this.logAtLevelWithOverrides(_n.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(_n.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(fe.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),hj({prefix:this.getIcon({spinner:t}),content:r.join(`
4943
4943
  `)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?fe.dim("\u25B8 "):fe.dim("\u25E6 ");case"running":return r?fe.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case Qf.Success:return r?fe.green("\u25BE "):fe.green("\u2713 ");case Qf.Failure:return r?fe.red("\u25BE "):fe.red("x ")}}}getResult(){if(this.result===Qf.Failure)return Qf.Failure;for(let t of this.subtasks)if(t.getResult()===Qf.Failure)return Qf.Failure;return Qf.Success}};Qt();var Wdp=ye(mMe(),1);En();function Hdp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function aKg(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||Hdp(e.generatorUpgradeInfo)}async function Kdp({cliEnvironment:e,upgradeInfo:t}){if(!aKg(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${fe.underline("Upgrades available")}
4944
4944
 
@@ -4947,7 +4947,7 @@ ${r}`}function hEi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
4947
4947
  Run ${fe.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
4948
4948
  Run ${fe.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),iot(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function oQs({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!Hdp(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
4949
4949
  ${await cKg(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+fe.dim(a.currentVersion)+fe.reset(" \u2192 ")+fe.green(a.latestVersion);return i+=`
4950
- `,n?iot(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function cKg(e){let r=await new Wdp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new O({message:`Generator ${e} not found`,code:O.Code.ConfigError});return r.body.displayName}ho();Gpe();Qt();async function uKg({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=iMe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await y1({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=iMe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await y1({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await jL({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?jA(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function Ydp(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c;try{c=N1(a.latestVersion,a.previousVersion)}catch{throw new O({message:`Generator "${s}" has an invalid version "${a.previousVersion}" in generators.yml. Use an exact version like 1.2.3.`,code:O.Code.ConfigError})}r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function nIi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await uKg({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...Ydp(u,c,t.logger));else s.push(...Ydp(a.versions,void 0,t.logger))}return s}Qt();r0r();async function nge({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await GNe(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new O({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:O.Code.NetworkError})}}var Xdp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],iIi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=_n.Info;isLocal;stdoutRedirector=new rIi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await HUt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new bLt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new tIi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new ZEi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.110.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${fe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new ru}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof ru)&&(nLt({message:t,error:r,logger:this.logger}),$Ei(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
4950
+ `,n?iot(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function cKg(e){let r=await new Wdp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new O({message:`Generator ${e} not found`,code:O.Code.ConfigError});return r.body.displayName}ho();Gpe();Qt();async function uKg({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=iMe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await y1({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=iMe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await y1({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function Jdp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await jL({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?jA(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function Ydp(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c;try{c=N1(a.latestVersion,a.previousVersion)}catch{throw new O({message:`Generator "${s}" has an invalid version "${a.previousVersion}" in generators.yml. Use an exact version like 1.2.3.`,code:O.Code.ConfigError})}r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function nIi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await uKg({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...Ydp(u,c,t.logger));else s.push(...Ydp(a.versions,void 0,t.logger))}return s}Qt();r0r();async function nge({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await GNe(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new O({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:O.Code.NetworkError})}}var Xdp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],iIi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=_n.Info;isLocal;stdoutRedirector=new rIi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await HUt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new bLt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new tIi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new ZEi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.110.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${fe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new ru}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof ru)&&(nLt({message:t,error:r,logger:this.logger}),$Ei(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
4951
4951
  `),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();try{await this.posthogManager.flush()}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await Kdp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
4952
4952
  `)||(r+=`
4953
4953
  `),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=Fki(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t,this.automationTelemetryManager.setOrganization(t.config.organization)}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 FXt(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){throw n.failWithoutThrowing(void 0,o),new ru}finally{n.finish()}return i}instrumentPostHogEvent(t){this.isLocal||this.posthogManager.sendEvent(t)}instrumentPostHogAutomationEvent(t){this.isLocal||this.posthogManager.sendAutomationEvent(t)}captureException(t,r){return this.sentryClient.captureException(t,r)}emitAutomationTelemetryEvent(t,r){this.automationTelemetryManager.emit(t,r)}logger=Av((t,...r)=>this.log(t,...r));stderr=Av((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=Zdp(r),i=1+(this.longestWorkspaceName!=null?Zdp(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=Xdp[this.numTasks++%Xdp.length],a=fe.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:fe.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Qf.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:t=>{this.instrumentPostHogEvent(t)},shouldBufferLogs:!1,captureException:(t,r)=>this.sentryClient.captureException(t,r),emitAutomationTelemetryEvent:(t,r)=>this.emitAutomationTelemetryEvent(t,r)}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>lw.indexOf(i.level)>=lw.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===_n.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await nge({cliEnvironment:this.environment,includePreReleases:t}),n=N1(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await nIi({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await nQs({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:fe.yellow("?"),style:{answer:i=>fe.cyan(i),message:i=>fe.bold(i),highlight:i=>fe.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`