fern-api 3.54.0 → 3.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +5 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1304,7 +1304,7 @@ ${Kka(this).map(t=>` ${t.fn} - ${t.path}:${t.position}`).join(`
|
|
|
1304
1304
|
`),this.hasSameAccess(this.init)||t.write(`${this.init} `),t.writeTextStatement("init"),t.writeNoIndent(`#else
|
|
1305
1305
|
`),t.writeTextStatement("set"),t.writeNoIndent(`#endif
|
|
1306
1306
|
`)):(this.hasSameAccess(this.init)||t.write(`${this.init} `),this.accessors?.init?(t.write("init"),t.write(" => "),this.accessors.init(t),t.writeTextStatement("")):t.write("init; "))),this.set&&(this.hasSameAccess(this.set)||t.write(`${this.set} `),this.accessors?.set?(t.write("set"),t.write(" => "),this.accessors.set(t),t.writeTextStatement("")):t.write("set; ")),t.write("}")),this.initializer!=null?(n?t.write(" => "):t.write(" = "),this.initializer.write(t),t.writeLine(";")):!this.skipDefaultInitializer&&!r&&i?gl.Type(this.type)&&this.type.writeEmptyCollectionInitializer(t):!this.get&&!this.init&&t.writeLine(";")}hasSameAccess(t){return t===!0||t===this.access}};var x5t;(function(e){e[e.INSTANCE=0]="INSTANCE",e[e.STATIC=1]="STATIC"})(x5t||(x5t={}));var c2i=class e extends XZi{name;isAsync;access;return;noBody;body;bodyType;summary;doc;type;reference;override;parameters;typeParameters;annotations;interfaceReference;constructor({name:t,isAsync:r,override:i,access:n,return_:a,body:o,noBody:c,bodyType:d,summary:s,doc:u,type:f,classReference:p,parameters:_,typeParameters:h,annotations:y,codeExample:b,interfaceReference:v,origin:O,enclosingType:m},g){super({enclosingType:m},O,g),this.name=t,this.isAsync=r??!1,this.override=i??!1,this.access=n,this.return=a,this.noBody=c??!1,this.body=o,this.bodyType=d??e.BodyType.Statement,this.summary=s,this.doc=this.csharp.xmlDocBlockOf(u??{summary:s,codeExample:b}),this.type=f??x5t.INSTANCE,this.reference=p,this.parameters=_??[],this.typeParameters=h??[],this.annotations=(y??[]).map(A=>A instanceof Z5?this.csharp.annotation({reference:A}):A),this.interfaceReference=v}get isAsyncEnumerable(){return gl.AsyncEnumerable(this.return)}addParameter(t){return t instanceof W5t||(t=new W5t(t,this.generation)),this.parameters.push(t),t}write(t){if(t.writeNode(this.doc),this.annotations.forEach(r=>{r.write(t)}),t.writeNewLineIfLastLineNot(),this.access&&t.write(`${this.access} `),this.type===x5t.STATIC&&t.write("static "),this.isAsync&&t.write("async "),this.override&&t.write("override "),this.return==null?this.isAsync?(t.writeNode(this.System.Threading.Tasks.Task()),t.write(" ")):t.write("void "):(this.isAsync&&!this.isAsyncEnumerable?t.writeNode(this.System.Threading.Tasks.Task(this.return)):this.return.write(t),t.write(" ")),this.interfaceReference&&t.write(`${this.interfaceReference.name}.`),t.write(this.name),this.typeParameters.length>0&&(t.write("<"),this.typeParameters.forEach((r,i)=>{r.write(t),i<this.typeParameters.length-1&&t.write(", ")}),t.write(">")),t.write("("),this.parameters.forEach((r,i)=>{r.write(t),i<this.parameters.length-1&&t.write(", ")}),t.write(")"),this.noBody)t.writeLine(";");else switch(this.bodyType){case e.BodyType.Statement:t.write(" "),t.pushScope(),this.body?.write(t),t.popScope();break;case e.BodyType.Expression:t.write(" => "),this.body?.write(t),t.writeSemicolonIfLastCharacterIsNot();break;default:le(this.bodyType)}}getParameters(){return this.parameters}};(function(e){e.BodyType={Statement:"statement",Expression:"expression"}})(c2i||(c2i={}));var kda=class extends eme{access;partial;reference;interfaceReferences;fields=[];methods=[];constructor({name:t,namespace:r,access:i,partial:n,interfaceReferences:a,enclosingType:o,origin:c},d){super(c,d),t=t||(c?this.model.getClassNameFor(c):(0,omu.fail)("Class/Interface name or origin is required")),this.reference=o?this.csharp.classReference({name:t,enclosingType:o}):this.csharp.classReference({name:t,namespace:r||(0,omu.fail)("Class/Interface: Namespace or enclosingType is required ")}),this.access=i,this.partial=n??!1,this.interfaceReferences=a??[]}get name(){return this.reference.name}get namespace(){return this.reference.namespace}get enclosingType(){return this.reference.enclosingType}get isNested(){return this.enclosingType!=null}explicit(t){return this.origin?this.model.explicit(gl.Provenance(this.origin)?this.origin.node:this.origin,t):(0,omu.fail)(`Cannot create explicit named member '${t}' on '${this.name}' because the class is not bound to an origin.`)}getField(t){return this.fields.find(r=>this.model.provenance(r.origin)?.jsonPath===t.jsonPath)}addField(t){t.enclosingType=this.reference;let r=new Zda(t,this.generation);return this.fields.push(r),r}addMethod(t){t.enclosingType=this.reference;let r=new c2i(t,this.generation);return this.methods.push(r),r}get multipartMethodName(){return"AddJsonPart"}get multipartMethodNameForCollection(){return"AddJsonParts"}get isOptional(){return!1}get isCollection(){return!1}get isReferenceType(){}asOptional(){return new BDe(this,this.generation)}asNullable(){return new gPn(this,this.generation)}asNonOptional(){return this}get defaultValue(){return this.csharp.Literal.null()}get fullyQualifiedName(){return this.reference.fullyQualifiedName}};var yer=class e extends kda{static ClassType={Class:"class",Record:"record",Struct:"struct",RecordStruct:"record struct"};static Access=QT;static_;abstract_;sealed;readonly;parentClassReference;type;summary;doc;annotations=[];primaryConstructor;namespaceReferences=[];constructors=[];operators=[];nestedClasses=[];nestedInterfaces=[];constructor({name:t,namespace:r,access:i,static_:n,abstract_:a,sealed:o,partial:c,readonly:d,parentClassReference:s,interfaceReferences:u,enclosingType:f,type:p,summary:_,doc:h,annotations:y,primaryConstructor:b,origin:v},O){super({name:t,namespace:r,access:i,partial:c,interfaceReferences:u,enclosingType:f,origin:v},O),this.static_=n??!1,this.abstract_=a??!1,this.sealed=o??!1,this.readonly=d??!1,this.type=p??e.ClassType.Class,this.summary=_,this.doc=this.csharp.xmlDocBlockOf(h??{summary:_}),this.parentClassReference=s,this.annotations=(y??[]).map(m=>m instanceof Z5?this.csharp.annotation({reference:m}):m),this.primaryConstructor=b}addConstructor(t){let r=new e.Constructor(t,this.generation);return this.constructors.push(r),r}addNestedClass(t){if(t instanceof e||(t.enclosingType=this.reference,t=new e(t,this.generation)),!t.isNested)throw new Error(`Set the enclosingType of the class ${this.name} to add the nested class ${t.name}.`);return this.nestedClasses.push(t),t}addNestedClasses(t){t.forEach(r=>{r instanceof e?this.addNestedClass(r):this.addNestedClass(r)})}addAnnotation(t){return t instanceof v3i||(t=new v3i(t,this.generation)),this.annotations.push(t),t}addOperator(t){this.operators.push(t)}addOperators(t){t.forEach(r=>this.addOperator(r))}write(t){if(this.namespaceReferences.forEach(r=>{t.addNamespace(r)}),this.isNested||(t.writeLine(`namespace ${this.namespace};`),t.newLine()),t.writeNode(this.doc),this.annotations.forEach(r=>{r.write(t)}),t.writeNewLineIfLastLineNot(),t.write(`${this.access}`),this.static_&&t.write(" static"),this.abstract_&&t.write(" abstract"),this.sealed&&t.write(" sealed"),this.readonly&&t.write(" readonly"),this.partial&&t.write(" partial"),t.write(` ${this.type}`),t.write(` ${this.name}`),this.primaryConstructor!=null&&this.primaryConstructor.parameters.length>0){let r=this.primaryConstructor;t.write("("),r.parameters.forEach((i,n)=>{n>0&&t.write(","),i.write(t)}),t.write(")")}if(this.parentClassReference!=null||this.interfaceReferences.length>0){if(t.write(" : "),this.parentClassReference!=null&&(this.parentClassReference.write(t),this.interfaceReferences.length>0&&t.write(", ")),this.primaryConstructor!=null&&this.primaryConstructor.superClassArguments.length>0){let r=this.primaryConstructor;t.write("("),this.primaryConstructor.superClassArguments.forEach((i,n)=>{i.write(t),n<r.superClassArguments.length-1&&t.write(", ")}),t.write(")")}this.interfaceReferences.forEach((r,i)=>{r.write(t),i<this.interfaceReferences.length-1&&t.write(", ")})}if(!this.hasBody()){t.write(";");return}t.writeNewLineIfLastLineNot(),t.pushScope(),this.writeConsts(t),this.writeFieldFields(t),this.writeConstructors(t),this.writeProperties(t),this.writeMethods(t),this.writeOperators(t),this.writeNestedClasses(t),this.writeNestedInterfaces(t),t.popScope()}hasBody(){return this.fields.length>0||this.constructors.length>0||this.nestedClasses.length>0||this.nestedInterfaces.length>0||this.methods.length>0||this.operators.length>0}writeConstructors(t){this.constructors.forEach(r=>{t.writeNode(this.csharp.xmlDocBlockOf(r.doc)),t.write(`${r.access} ${this.name} (`),r.parameters.forEach((i,n)=>{i.write(t),n<r.parameters.length-1&&t.write(", ")}),t.write(")"),r.baseConstructorCall!=null&&(t.write(" : "),r.baseConstructorCall.write(t)),t.pushScope(),r.body.write(t),t.popScope(),t.newLine()})}writeFields({writer:t,fields:r}){r.forEach((i,n)=>{i.write(t),t.writeNewLineIfLastLineNot(),n<this.fields.length-1&&t.newLine()})}writeConsts(t){this.writeFields({writer:t,fields:this.getFields().sort(epa).sort(GYc).filter(this.fieldConstFilter())})}writeFieldFields(t){this.writeFields({writer:t,fields:this.getFields().sort(epa).sort(GYc).filter(this.fieldFieldFilter())})}writeProperties(t){this.writeFields({writer:t,fields:this.getFields().sort(epa).sort(GYc).filter(this.fieldPropertyFilter())})}writeMethods(t){this.methods.sort(epa).sort(ifB).sort(rfB).forEach(r=>{r.write(t),t.writeNewLineIfLastLineNot(),t.newLine()})}writeOperators(t){this.operators.forEach(r=>{this.writeOperator({writer:t,operator:r}),t.newLine()})}writeNestedClasses(t){this.nestedClasses.sort(epa).forEach((r,i)=>{r.write(t),t.writeNewLineIfLastLineNot(),i<this.fields.length-1&&t.newLine()})}writeNestedInterfaces(t){this.nestedInterfaces.sort(epa).forEach((r,i)=>{r.write(t),t.writeNewLineIfLastLineNot(),i<this.fields.length-1&&t.newLine()})}fieldConstFilter(){return t=>t.isConst}fieldFieldFilter(){return t=>t.isField}fieldPropertyFilter(){return t=>t.isProperty}getFields(){return this.fields}get isReferenceType(){return this.type===e.ClassType.Class||this.type===e.ClassType.Record}writeOperator({writer:t,operator:r}){if(t.write("public static "),r.type===e.CastOperator.Type.Explicit||r.type===e.CastOperator.Type.Implicit){t.write(`${r.type} `),t.write("operator ");let i=r.to??this.reference;t.writeNode(i),t.write("("),r.parameter.write(t)}else{let i=r;i.return.write(t),t.write(" operator "),t.write(`${r.type}(`),i.parameters.forEach((n,a)=>{n.write(t),a<i.parameters.length-1&&t.write(", ")})}r.useExpressionBody?(t.write(") => "),t.writeNodeStatement(r.body)):(t.write(") {"),t.writeNode(r.body),t.writeLine("}"))}addNamespaceReference(t){this.namespaceReferences.push(t)}};(function(e){class t{generation;doc;body;parameters;access;baseConstructorCall;constructor({doc:n,body:a,parameters:o,access:c,baseConstructorCall:d},s){this.generation=s,this.parameters=o??[],this.access=c??QT.Public,this.doc=n,this.body=new u2i({},this.generation),a!=null&&this.body.append(a),this.baseConstructorCall=d}addParameter(n){let a=new W5t(n,this.generation);return this.parameters.push(a),a}}e.Constructor=t;let r;(function(i){i.Type={Implicit:"implicit",Explicit:"explicit"}})(r=e.CastOperator||(e.CastOperator={}))})(yer||(yer={}));function aqh(e){switch(e){case void 0:return 0;case QT.Private:return 1;case QT.Protected:return 2;case QT.Internal:return 3;case QT.Public:return 4}}function epa(e,t){return aqh(e.access)-aqh(t.access)}function GYc(e,t){return e.isStatic===t.isStatic?0:e.isStatic?-1:1}function rfB(e,t){return e.type===x5t.STATIC&&t.type!==x5t.STATIC?-1:e.type!==x5t.STATIC&&t.type===x5t.STATIC?1:0}function ifB(e,t){return e.name==="FromProto"||e.name==="ToProto"?t.name==="Equals"||t.name==="ToString"?-1:1:t.name==="FromProto"||t.name==="ToProto"?e.name==="Equals"||e.name==="ToString"?1:-1:e.name==="ToString"?1:t.name==="ToString"?-1:e.name==="Equals"?t.name==="ToString"?-1:1:t.name==="Equals"?e.name==="ToString"?1:-1:0}var tpa=class extends eme{get name(){return this.reference.name}get namespace(){return this.reference.namespace}access;reference;annotations;fields=[];constructor({name:t,namespace:r,access:i,annotations:n,origin:a},o){super(a,o),this.reference=this.csharp.classReference({name:t,namespace:r,origin:a}),this.access=i,this.annotations=n??[]}getNamespace(){return this.namespace}addMember(t){this.fields.push({name:t.name,value:this.csharp.annotation({reference:this.System.Runtime.Serialization.EnumMember,argument:this.csharp.codeblock(r=>{r.write("Value = "),r.writeNode(this.csharp.string_({string:t.value}))})})})}write(t){t.writeLine(`namespace ${this.namespace};`),t.newLine();for(let r of this.annotations)r.write(t);t.writeNewLineIfLastLineNot(),t.write(`${this.access} `),t.write("enum "),t.writeLine(`${this.name}`),t.pushScope(),this.fields.forEach((r,i)=>{r.value.write(t),t.write(r.name),i<this.fields.length-1&&(t.writeLine(","),t.newLine())}),t.writeNewLineIfLastLineNot(),t.popScope()}};var rpa=class extends kda{constructor({name:t,namespace:r,access:i,partial:n,interfaceReferences:a,enclosingType:o,origin:c},d){super({name:t,namespace:r,access:i,partial:n,interfaceReferences:a,enclosingType:o,origin:c},d)}write(t){this.isNested||(t.writeLine(`namespace ${this.namespace};`),t.newLine()),t.write(`${this.access} `),this.partial&&t.write("partial "),t.write("interface "),t.writeLine(`${this.name}`),this.interfaceReferences.length>0&&(t.write(" : "),this.interfaceReferences.forEach((r,i)=>{r.write(t),i<this.interfaceReferences.length-1&&t.write(", ")})),t.pushScope();for(let r of this.fields)r.write(t),t.writeLine("");t.dedent(),t.indent();for(let r of this.methods)r.write(t),t.writeLine("");t.popScope()}};var ipa=class extends eme{get name(){return this.reference.name}get namespace(){return this.reference.namespace}reference;parentClassReference;testMethods=[];constructor({name:t,namespace:r,parentClassReference:i,origin:n},a){super(n,a),this.reference=this.csharp.classReference({name:t,namespace:r,origin:n}),this.parentClassReference=i}write(t){t.writeNode(this.getClass())}getClass(){let t=new yer({access:QT.Public,name:this.name,namespace:this.namespace,annotations:[this.NUnit.Framework.TestFixture],parentClassReference:this.parentClassReference,origin:this.origin},this.generation);for(let r of this.testMethods)t.addMethod({access:QT.Public,isAsync:r.isAsync,name:r.name,parameters:[],body:r.body,annotations:[this.NUnit.Framework.Test]});return t}addTestMethod(t){this.testMethods.push(t)}};var oeo=require("path");var oqh=require("assert");var OPn=require("assert");var HYc={System:["AccessViolationException","Action","Activator","AggregateException","AppContext","AppDomain","AppDomainSetup","AppDomainUnloadedException","ApplicationException","ApplicationId","ArgIterator","ArgumentException","ArgumentNullException","ArgumentOutOfRangeException","ArithmeticException","Array","ArrayTypeMismatchException","AssemblyLoadEventArgs","AssemblyLoadEventHandler","AsyncCallback","Attribute","AttributeTargets","AttributeUsageAttribute","BadImageFormatException","Base64FormattingOptions","BitConverter","Boolean","Buffer","Byte","CannotUnloadAppDomainException","Char","CharEnumerator","CLSCompliantAttribute","Console","ConsoleCancelEventArgs","ConsoleCancelEventHandler","ConsoleColor","ConsoleKey","ConsoleKeyInfo","ConsoleModifiers","ConsoleSpecialKey","ContextBoundObject","ContextMarshalException","ContextStaticAttribute","Convert","CultureAwareComparer","DataMisalignedException","DateOnly","DateTime","DateTimeKind","DateTimeOffset","DayOfWeek","DBNull","Decimal","Delegate","DivideByZeroException","DllNotFoundException","Double","DuplicateWaitObjectException","EntryPointNotFoundException","Enum","Environment","EnvironmentVariableTarget","EventArgs","EventHandler","Exception","ExecutionEngineException","FieldAccessException","FlagsAttribute","FormatException","FormattableString","GC","GCCollectionMode","GCGenerationInfo","GCKind","GCMemoryInfo","GCNotificationStatus","Guid","Half","HashCode","IAsyncDisposable","IAsyncResult","ICloneable","IComparable","IConvertible","ICustomFormatter","IDisposable","IFormatProvider","IFormattable","Index","IndexOutOfRangeException","InsufficientExecutionStackException","InsufficientMemoryException","Int128","Int16","Int32","Int64","IntPtr","InvalidCastException","InvalidOperationException","InvalidProgramException","InvalidTimeZoneException","ISpanFormattable","IUtf8SpanFormattable","LoaderOptimization","LoaderOptimizationAttribute","LocalDataStoreSlot","MarshalByRefObject","Math","MathF","MemberAccessException","MemoryExtensions","MethodAccessException","MidpointRounding","MissingFieldException","MissingMemberException","MissingMethodException","ModuleHandle","MTAThreadAttribute","MulticastDelegate","MulticastNotSupportedException","NonSerializedAttribute","NotFiniteNumberException","NotImplementedException","NotSupportedException","Nullable","NullReferenceException","Object","ObjectDisposedException","ObsoleteAttribute","OperatingSystem","OperationCanceledException","OrdinalComparer","OutOfMemoryException","OverflowException","ParamArrayAttribute","PlatformID","PlatformNotSupportedException","Random","Range","RankException","ResolveEventArgs","ResolveEventHandler","RuntimeArgumentHandle","RuntimeFieldHandle","RuntimeMethodHandle","RuntimeTypeHandle","SByte","SerializableAttribute","Single","StackOverflowException","STAThreadAttribute","String","StringComparer","StringComparison","StringNormalizationExtensions","StringSplitOptions","SystemException","ThreadStaticAttribute","TimeOnly","TimeoutException","TimeProvider","TimeSpan","TimeZone","TimeZoneInfo","TimeZoneNotFoundException","Tuple","TupleExtensions","Type","TypeAccessException","TypeCode","TypedReference","TypeInitializationException","TypeLoadException","TypeUnloadedException","UInt128","UInt16","UInt32","UInt64","UIntPtr","UnauthorizedAccessException","UnhandledExceptionEventArgs","UnhandledExceptionEventHandler","UnitySerializationHolder","ValueTuple","ValueType","Version","Void","WeakReference","Buffers","Collections","ComponentModel","Diagnostics","Globalization","IO","Linq","Net","Numerics","Reflection","Resources","Runtime","Security","Text","Threading"],"System.Collections.Generic":["ByteEqualityComparer","CollectionExtensions","IEnumerable","KeyNotFoundException","KeyValuePair","NonRandomizedStringEqualityComparer","ReferenceEqualityComparer"],"System.IO":["BinaryReader","BinaryWriter","BufferedStream","Directory","DirectoryInfo","DirectoryNotFoundException","EndOfStreamException","EnumerationOptions","File","FileAccess","FileAttributes","FileInfo","FileLoadException","FileMode","FileNotFoundException","FileOptions","FileShare","FileStream","FileStreamOptions","FileSystemInfo","HandleInheritability","InvalidDataException","IOException","MatchCasing","MatchType","MemoryStream","Path","PathTooLongException","RandomAccess","SearchOption","SeekOrigin","Stream","StreamReader","StreamWriter","StringReader","StringWriter","TextReader","TextWriter","UnixFileMode","UnmanagedMemoryAccessor","UnmanagedMemoryStream","System.IO.Enumeration"],"System.Linq":["Enumerable"],"System.Net.Http":["HttpClient","HttpMethod"],"System.Threading":["AbandonedMutexException","ApartmentState","AsyncFlowControl","AutoResetEvent","CancellationToken","CancellationTokenRegistration","CancellationTokenSource","CompressedStack","ContextCallback","EventResetMode","EventWaitHandle","ExecutionContext","Interlocked","IOCompletionCallback","IThreadPoolWorkItem","ITimer","LazyInitializer","LazyThreadSafetyMode","Lock","LockRecursionException","LockRecursionPolicy","ManualResetEvent","ManualResetEventSlim","Monitor","Mutex","NativeOverlapped","Overlapped","ParameterizedThreadStart","PeriodicTimer","PreAllocatedOverlapped","ReaderWriterLockSlim","RegisteredWaitHandle","Semaphore","SemaphoreFullException","SemaphoreSlim","SendOrPostCallback","SpinLock","SpinWait","SynchronizationContext","SynchronizationLockException","Thread","ThreadAbortException","ThreadExceptionEventArgs","ThreadExceptionEventHandler","ThreadInterruptedException","ThreadPool","ThreadPoolBoundHandle","ThreadPriority","ThreadStart","ThreadStartException","ThreadState","ThreadStateException","Timeout","Timer","TimerCallback","Volatile","WaitCallback","WaitHandle","WaitHandleCannotBeOpenedException","WaitHandleExtensions","WaitOrTimerCallback","Tasks"],"System.Threading.Tasks":["ConcurrentExclusiveSchedulerPair","ConfigureAwaitOptions","Task","TaskAsyncEnumerableExtensions","TaskCanceledException","TaskCompletionSource","TaskContinuationOptions","TaskCreationOptions","TaskExtensions","TaskFactory","TaskScheduler","TaskSchedulerException","TaskStatus","TaskToAsyncResult","UnobservedTaskExceptionEventArgs","ValueTask","Sources"]};var nfB=new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while"]);var afB=new Set(["from","where","select","orderby","groupby","into","let","join","on","equals"]),ofB=new Set(["async","await"]),ufB=new Set(["yield"]),sfB=new Set(["var","dynamic"]),cfB=new Set(["using","alias"]);var lfB=new Set(["required","scoped","unmanaged","managed"]),ffB=new Set(["when","and","or","not"]),dfB=new Set(["Equals","GetHashCode","ToString","GetType","MemberwiseClone","Finalize"]),pfB=new Set([...nfB,...afB,...ofB,...ufB,...sfB,...cfB,...lfB,...ffB]),umu=class{registry;name;jsonPath;constructor(t,r,i){this.registry=t,this.name=r,this.jsonPath=i}};var smu=class{scope;constructor(t){this.scope=t}byName=new Map;byPath=new Map;redirections=new Map;[Symbol.iterator](){return this.byName.values()}has(t){return this.byName.has(t)}getByJsonPath(t){return this.byPath.get(t)}getByName(t){return this.byName.get(t)}getRedirectedName(t){return this.redirections.get(t)}set(t){this.byName.has(t.name)&&(0,OPn.fail)(`set: ${t.name} in ${this.scope.fullyQualifiedName} already exists`),t.jsonPath&&this.byPath.has(t.jsonPath)&&(0,OPn.fail)(`set: ${t.name} in ${this.scope.fullyQualifiedName} already exists by jsonPath`),this.byName.set(t.name,t),t.jsonPath&&this.byPath.set(t.jsonPath,t)}redirect(t,r){this.redirections.has(t)&&(0,OPn.fail)(`redirect: ${t} in ${this.scope.fullyQualifiedName} already has a redirect`),this.redirections.set(t,r)}},KYc=class extends umu{namespace;fullyQualifiedName;fields;methods;constructor(t,r,i,n){super(t,r),this.namespace=i,this.fullyQualifiedName=n,this.fields=new smu(this),this.methods=new smu(this)}isKeyword(t){return pfB.has(t)}isBuiltinMemberName(t){return dfB.has(t)}isTypeName(t){return this.name===t}isField(t){return this.fields.has(t)}isMethod(t){return this.methods.has(t)}isMember(t){return this.isField(t)||this.isMethod(t)}nameBlocked(t){if(this.isKeyword(t))return"keyword";if(this.isBuiltinMemberName(t))return"builtin";if(this.isTypeName(t))return"typeName";if(this.isField(t))return"field";if(this.isMethod(t))return"method"}getAlternativeName(t){let r=`${t}_`,i=2;for(;this.nameBlocked(r);)r=`${t}_${i}`,i++;return r}getFieldByJsonPath(t){return t!==void 0?this.fields.getByJsonPath(t):void 0}getFieldByName(t){return this.fields.getByName(t)}getRedirectedFieldName(t){return this.fields.getRedirectedName(t)}registerField(t,r,i){let n=this.registry.model.jsonPath(r);if(n){let c=this.fields.getByJsonPath(n);if(c)return c.name}let a=this.fields.getByName(t);if(a&&n===a.jsonPath)return t;switch(this.nameBlocked(t)){case"field":r&&gl.Provenance(r)&&r.explicit||(0,OPn.fail)(`Field ${t} already exists - attempting to add a duplicate field with the same name that is not an explicitly named property`);break;case"keyword":case"builtin":case"typeName":case"method":break;default:return this.fields.set(new cmu(this.registry,t,this,n,i)),this.registry.setFieldNameShortcut(n,t),t}let o=this.getAlternativeName(t);return this.fields.set(new cmu(this.registry,o,this,n,i)),this.fields.redirect(t,o),this.registry.setFieldNameShortcut(n,o),o}getFieldName(t,r){let i=this.getFieldByJsonPath(this.registry.model.jsonPath(t))?.name;if(i)return i;if(gl.Provenance(t)){let o=this.getRedirectedFieldName(r);if(o)return o;let c=this.getFieldByName(r);return c?this.registry.model.provenance(c.jsonPath)?.explicit?r:`${r}_`:r}let n=this.getFieldByName(r);if(n)return this.registry.model.provenance(n.jsonPath)?.explicit?r:n.name;let a=this.getRedirectedFieldName(r);if(a)return a;this.isMethod(r)}},$Yc=class extends umu{scope;constructor(t,r,i,n){super(t,r,n),this.scope=i}},cmu=class extends $Yc{field;constructor(t,r,i,n,a){super(t,r,i,n),this.field=a}};var apa=class e{generation;classReferenceByJsonPath=new Map;typeRegistry=new Map;namespaceRegistry=new Map;typeNames=new Map;namespaceNames=new Map;implicitNamespaces=new Set;shortcuts=new Map;knownBuiltInIdentifiers=new Set(["Text","Json","Xml","Security","Collections","Data","Diagnostics","Globalization","Math","Reflection","Runtime","Security","Serialization","Threading","Xml"]);constructor(t){this.generation=t,this.initializeBuiltIns()}get csharp(){return this.generation.csharp}get model(){return this.generation.model}initializeBuiltIns(){for(let[t,r]of Object.entries(HYc))t.split(".").forEach(i=>this.knownBuiltInIdentifiers.add(i)),r.forEach(i=>this.knownBuiltInIdentifiers.add(i));for(let[t,r]of Object.entries(HYc)){for(let n of r)this.typeNames.set(n,new Set([t]));let i=t.split(".")[0];i&&this.typeNames.set(i,new Set([t]))}this.typeNames.set("System",new Set(["System"])),this.typeNames.set("NUnit",new Set(["NUnit"])),this.typeNames.set("OneOf",new Set(["OneOf"]))}setFieldNameShortcut(t,r){if(t){let i=this.shortcuts.get(t);i&&i!==r&&(0,OPn.fail)(`BAD_BAD_BAD setFieldNameShortcut: ${t} already has a name: ${i} - while setting to ${r} - if this is happening, then you could be getting back the wrong name later!`),this.shortcuts.set(t,r)}}getFieldNameByOrigin(t){return this.shortcuts.get(this.model.jsonPath(t)??">ignore<")}isKnownBuiltInIdentifier(t){return!t||typeof t!="string"?!1:this.knownBuiltInIdentifiers.has(t)}isKnownNamespace(t){return!t||typeof t!="string"?!1:this.namespaceRegistry.has(t)}isRegisteredTypeName(t){return this.typeRegistry.has(t)}isAmbiguousTypeName(t){return t?(this.typeNames.get(t)?.size??0)>1:!1}isAmbiguousNamespaceName(t){return t?(this.namespaceNames.get(t)?.size??0)>1:!1}static fullyQualifiedNameOf(t){return t.enclosingType?`${t.namespace}.${t.enclosingType.name}.${t.name}`:`${t.namespace}.${t.name}`}registerNamespace(t,r){this.namespaceRegistry.has(t)&&this.namespaceRegistry.get(t)!==r||this.namespaceRegistry.set(t,r)}trackType(t,r){let{name:i,namespace:n,enclosingType:a,fullyQualifiedName:o,origin:c}=t;if(c){let d=this.model.jsonPath(c)??(0,OPn.fail)(`JsonPath not found for origin: ${JSON.stringify(c).substring(0,100)}`);this.classReferenceByJsonPath.set(d,t)}if(r&&r!==o&&!this.typeRegistry.has(r)&&this.typeRegistry.set(r,t),!this.typeRegistry.has(o)){this.typeRegistry.set(o,t);for(let d of this.allNamespacesOf(n))this.registerNamespace(d,d);a||this.trackTypeName(i,n);for(let d of[this.generation.namespaces.root,...this.implicitNamespaces])if(n.startsWith(d)){let s=n.split(".")[d.split(".").length];s&&this.trackTypeName(s,n)}}return t}addImplicitNamespace(t){this.implicitNamespaces.add(t)}isNamespaceImplicit(t){return this.implicitNamespaces.has(t)}get implicitlyImportedNamespaces(){return[...this.implicitNamespaces]}trackTypeName(t,r){this.typeNames.has(t)?this.typeNames.get(t)?.add(r):this.typeNames.set(t,new Set([r]));let i=r.split("."),n="";for(let a of i)this.namespaceNames.has(a)?this.namespaceNames.get(a)?.add(n):this.namespaceNames.set(a,new Set([n])),n=n?`${n}.${a}`:a}allNamespacesOf(t){if(!t||typeof t!="string")return new Set;let r="",i=new Set;for(let n of t.split("."))n.trim()&&(r=r?`${r}.${n}`:`${n}`,i.add(r));return i}registerClassReference(t,r){let{name:i,namespace:n,enclosingType:a,origin:o}=t,c=this.model.jsonPath(o),d=(c?this.classReferenceByJsonPath.get(c):void 0)??this.typeRegistry.get(r),s=this.model.jsonPath(d?.origin),u=s&&c?s===c?"match":"mismatch":"no origin";if(d&&u!=="mismatch")return new Z5({name:d.name,namespace:d.namespace,enclosingType:d.enclosingType,fullyQualifiedName:d.fullyQualifiedName,namespaceAlias:t.namespaceAlias,fullyQualified:t.fullyQualified,generics:t.generics,global:t.global,origin:d.origin??o,isCollection:d.isCollection,isReferenceType:d.isReferenceType,multipartMethodName:d.multipartMethodName,multipartMethodNameForCollection:d.multipartMethodNameForCollection},d.scope,this.generation);let f=!1,p=this.resolveNamespace(n);p!==n&&(n=p,f=!0);let _;e:for(;;){_=e.fullyQualifiedNameOf({name:i,namespace:n,enclosingType:a});let h="",y=n.split(".");for(let b=0;b<y.length;b++)if(h=h?`${h}.${y[b]}`:`${y[b]}`,this.typeRegistry.has(h)){y[b]=`${y[b]}_`,n=y.join("."),f=!0;continue e}if(f&&this.registerNamespace(t.namespace,n),u==="mismatch"&&d?.name===i){i=`${i}_`,f=!0;continue e}if(this.namespaceRegistry.has(_)){i=`${i}_`,f=!0;continue e}break}return this.trackType(new Z5({name:i,namespace:n,enclosingType:a,namespaceAlias:t.namespaceAlias,fullyQualified:t.fullyQualified,generics:t.generics,global:t.global,fullyQualifiedName:_,origin:o,isCollection:t.isCollection,isReferenceType:t.isReferenceType,multipartMethodName:t.multipartMethodName,multipartMethodNameForCollection:t.multipartMethodNameForCollection},new KYc(this,i,n,_),this.generation),r)}resolveNamespace(t){let r=this.namespaceRegistry.get(t);if(r!==void 0)return r;let i=t.split(".");for(let n=i.length-1;n>=0;n--){let a=i.slice(0,n).join(".");if(this.namespaceRegistry.has(a)){let o=this.namespaceRegistry.get(a);if(o!==void 0){let c=i.slice(n).join("."),d=`${o}.${c}`;return this.registerNamespace(t,d),d}}}return t}canonicalizeNamespace(t){let r=this.namespaceRegistry.get(t);if(r!==void 0)return r;let i=!1,n=t;e:for(;;){let a="",o=n.split(".");for(let c=0;c<o.length;c++)if(a=a?`${a}.${o[c]}`:`${o[c]}`,this.typeRegistry.has(a)){o[c]=`${o[c]}_`,n=o.join("."),i=!0;continue e}break}return i&&this.registerNamespace(t,n),n}};var lmu=class{generation;constructor(t){this.generation=t}get model(){return this.generation.model}frozen=!1;extraClassReferences=new Map;classReference(t){return this.classReferenceInternal(t)}classReferenceInternal(t){if(!t.name&&"origin"in t&&t.origin&&(t.name=this.model.getClassNameFor(t.origin)),t.enclosingType){if(t.namespace)throw new Error("ClassReference: Both enclosingType and namespace cannot be provided");t.namespace=t.enclosingType.namespace}let r=apa.fullyQualifiedNameOf(t);if(this.frozen&&!this.generation.registry.isRegisteredTypeName(r)){let i=this.extraClassReferences.get(r);i||(i=new Set,this.extraClassReferences.set(r,i)),i.add(`${r} -
|
|
1307
|
-
${Hka()}`)}return this.generation.registry.registerClassReference(t,r)}freezeClassReferences(){this.frozen=!0}getPropertyName(t,r){let i=this.model.getPropertyNameFor(r),n=this.model.origin(r)??(0,oqh.fail)(`Origin not found for property: ${JSON.stringify(r).substring(0,100)}`),a=t.getFieldName(n,i);return a||i}class_(t){let r=t;return"reference"in t&&(r={...t.reference,...t}),new yer(r,this.generation)}testClass(t){return new ipa(t,this.generation)}annotation(t){return new v3i(t,this.generation)}annotationGroup(t){return new Kda(t,this.generation)}instantiateClass(t){return new Nda(t,this.generation)}invokeMethod(t){return new Lda(t,this.generation)}codeblock(t){return new o2i(t,this.generation)}code(){return new u2i({},this.generation)}anonymousFunction(t){return new $da(t)}parameter(t){return new W5t(t,this.generation)}interface_(t){return new rpa(t,this.generation)}enum_(t){return new tpa(t,this.generation)}dictionary(t){return new Fda(t,this.generation)}list(t){return new Uda(t,this.generation)}readOnlyMemory(t){return new Vda(t,this.generation)}set(t){return new Wda(t,this.generation)}switch_(t){return new Yda(t,this.generation)}ternary(t){return new Xda(t,this.generation)}and(t){return new Hda(t,this.generation)}or(t){return new Jda(t,this.generation)}enumInstantiation(t){return new Qda(t,this.generation)}string_(t){return new xda(t,this.generation)}xmlDocBlock(t){return new s2i(t,this.generation)}InstantiatedPrimitive={string:t=>new e3({type:"string",value:t},this.generation),boolean:t=>new e3({type:"boolean",value:t},this.generation),integer:t=>new e3({type:"integer",value:t},this.generation),long:t=>new e3({type:"long",value:t},this.generation),uint:t=>new e3({type:"uint",value:t},this.generation),ulong:t=>new e3({type:"ulong",value:t},this.generation),float:t=>new e3({type:"float",value:t},this.generation),double:t=>new e3({type:"double",value:t},this.generation),date:t=>new e3({type:"date",value:t},this.generation),dateTime:(t,r=!0)=>new e3({type:"dateTime",value:t,parse:r},this.generation),uuid:t=>new e3({type:"uuid",value:t},this.generation),null:()=>new e3({type:"null"},this.generation)};Literal={class_:({reference:t,fields:r})=>new ap.Class_(t,r,this.generation),dictionary:({keyType:t,valueType:r,entries:i})=>new ap.Dictionary(t,r,i,this.generation),list:({valueType:t,values:r})=>new ap.List(t,r,this.generation),set:({valueType:t,values:r})=>new ap.Set(t,r,this.generation),boolean:t=>new ap.Boolean(t,this.generation),float:t=>new ap.Float(t,this.generation),date:t=>new ap.Date(t,this.generation),datetime:t=>new ap.DateTime(t,this.generation),decimal:t=>new ap.Decimal(t,this.generation),double:t=>new ap.Double(t,this.generation),integer:t=>new ap.Integer(t,this.generation),long:t=>new ap.Long(t,this.generation),uint:t=>new ap.Uint(t,this.generation),ulong:t=>new ap.Ulong(t,this.generation),reference:t=>new ap.Reference(t,this.generation),string:t=>new ap.String(t,this.generation),null:()=>new ap.Null(this.generation),nop:()=>new ap.Nop(this.generation),unknown:t=>new ap.Unknown(t,this.generation)};xmlDocBlockOf(t){return t instanceof s2i?t:new s2i(t,this.generation)}VALID_READ_ONLY_MEMORY_TYPES=new Set(["int","long","uint","ulong","string","bool","float","double"]);validateReadOnlyMemoryTypes(){for(let t of this.generation.settings.readOnlyMemoryTypes)if(!this.VALID_READ_ONLY_MEMORY_TYPES.has(t))throw new Error(`Type "${t}" is not a valid 'read-only-memory-types' custom config option; expected one of ${JSON.stringify(this.VALID_READ_ONLY_MEMORY_TYPES)}.`)}};function bd(e){let t={},r={};for(let[i,n]of Object.entries(e))n.length===0?Object.defineProperty(r,i,{get(){return i in t||(t[i]=n()),t[i]},enumerable:!0,configurable:!0}):r[i]=n;return r}var fmu=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}System=bd({Action:t=>this.csharp.classReference({name:"Action",namespace:"System",generics:t||void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),Func:(t,r)=>this.csharp.classReference({name:"Func",namespace:"System",generics:t?r?[...t,r]:t:r?[r]:void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),DateOnly:()=>this.csharp.classReference({name:"DateOnly",namespace:"System"}),DateTime:()=>this.csharp.classReference({name:"DateTime",namespace:"System"}),Enum:()=>this.csharp.classReference({name:"Enum",namespace:"System"}),Exception:()=>this.csharp.classReference({name:"Exception",namespace:"System"}),ReadOnlyMemory:t=>this.csharp.classReference({name:"ReadOnlyMemory",namespace:"System",generics:[t]}),Serializable:()=>this.csharp.classReference({name:"SerializableAttribute",namespace:"System"}),String:()=>this.csharp.classReference({name:"String",namespace:"System"}),Type:()=>this.csharp.classReference({name:"Type",namespace:"System",isReferenceType:!0,multipartMethodName:null,multipartMethodNameForCollection:null,fullyQualified:!0}),TimeSpan:()=>this.csharp.classReference({name:"TimeSpan",namespace:"System"}),Uri:()=>this.csharp.classReference({name:"Uri",namespace:"System"}),UriBuilder:()=>this.csharp.classReference({name:"UriBuilder",namespace:"System"}),Runtime:()=>bd({Serialization:()=>bd({EnumMember:()=>this.csharp.classReference({name:"EnumMemberAttribute",namespace:"System.Runtime.Serialization"})})}),Collections:()=>bd({Generic:()=>bd({IAsyncEnumerable:t=>this.csharp.classReference({name:"IAsyncEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),IEnumerable:t=>this.csharp.classReference({name:"IEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),KeyValuePair:(t,r)=>this.csharp.classReference({name:"KeyValuePair",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0}),List:t=>this.csharp.classReference({name:"List",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),HashSet:t=>this.csharp.classReference({name:"HashSet",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),Dictionary:(t,r)=>this.csharp.classReference({name:"Dictionary",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0,isCollection:!0}),IDictionary:(t,r)=>this.csharp.classReference({name:"IDictionary",namespace:"System.Collections.Generic",generics:[t,r]})}),Linq:()=>bd({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})})}),Globalization:()=>bd({DateTimeStyles:()=>this.csharp.classReference({name:"DateTimeStyles",namespace:"System.Globalization"})}),Linq:()=>bd({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})}),Net:()=>bd({Http:()=>bd({HttpClient:()=>this.csharp.classReference({name:"HttpClient",namespace:"System.Net.Http"}),HttpMethod:()=>this.csharp.classReference({name:"HttpMethod",namespace:"System.Net.Http"}),HttpResponseHeaders:()=>this.csharp.classReference({name:"HttpResponseHeaders",namespace:"System.Net.Http.Headers"})}),ServerSentEvents:()=>bd({SseEvent:()=>this.csharp.classReference({name:"SseEvent",namespace:"System.Net.ServerSentEvents"}),SseParser:()=>this.csharp.classReference({name:"SseParser",namespace:"System.Net.ServerSentEvents"})}),WebSockets:()=>bd({ClientWebSocketOptions:()=>this.csharp.classReference({name:"ClientWebSocketOptions",namespace:"System.Net.WebSockets"})})}),IO:()=>bd({MemoryStream:()=>this.csharp.classReference({name:"MemoryStream",namespace:"System.IO"}),Stream:()=>this.csharp.classReference({name:"Stream",namespace:"System.IO"}),StreamReader:()=>this.csharp.classReference({name:"StreamReader",namespace:"System.IO"})}),Text:()=>bd({Encoding:()=>this.csharp.classReference({name:"Encoding",namespace:"System.Text"}),Encoding_UTF8:()=>this.csharp.classReference({name:"UTF8",enclosingType:this.csharp.classReference({name:"Encoding",namespace:"System.Text"})}),Json:()=>bd({JsonElement:()=>this.csharp.classReference({name:"JsonElement",namespace:"System.Text.Json"}),JsonDocument:()=>this.csharp.classReference({name:"JsonDocument",namespace:"System.Text.Json"}),JsonException:()=>this.csharp.classReference({name:"JsonException",namespace:"System.Text.Json"}),Utf8JsonReader:()=>this.csharp.classReference({name:"Utf8JsonReader",namespace:"System.Text.Json"}),JsonSerializerOptions:()=>this.csharp.classReference({name:"JsonSerializerOptions",namespace:"System.Text.Json"}),JsonSerializer:()=>this.csharp.classReference({name:"JsonSerializer",namespace:"System.Text.Json"}),Utf8JsonWriter:()=>this.csharp.classReference({name:"Utf8JsonWriter",namespace:"System.Text.Json"}),Nodes:()=>bd({JsonNode:()=>this.csharp.classReference({name:"JsonNode",namespace:"System.Text.Json.Nodes"}),JsonObject:()=>this.csharp.classReference({name:"JsonObject",namespace:"System.Text.Json.Nodes"})}),Serialization:()=>bd({IJsonOnDeserialized:()=>this.csharp.classReference({name:"IJsonOnDeserialized",namespace:"System.Text.Json.Serialization"}),IJsonOnSerializing:()=>this.csharp.classReference({name:"IJsonOnSerializing",namespace:"System.Text.Json.Serialization"}),JsonOnDeserializedAttribute:()=>this.csharp.classReference({name:"JsonOnDeserializedAttribute",namespace:"System.Text.Json.Serialization"}),JsonExtensionData:()=>this.csharp.classReference({name:"JsonExtensionDataAttribute",namespace:"System.Text.Json.Serialization"}),JsonConverter:t=>this.csharp.classReference({name:"JsonConverter",namespace:"System.Text.Json.Serialization",generics:t?[t]:void 0}),JsonIgnore:()=>this.csharp.classReference({name:"JsonIgnoreAttribute",namespace:"System.Text.Json.Serialization"}),JsonPropertyName:()=>this.csharp.classReference({name:"JsonPropertyNameAttribute",namespace:"System.Text.Json.Serialization"})})})}),Threading:()=>bd({CancellationToken:()=>this.csharp.classReference({name:"CancellationToken",namespace:"System.Threading"}),Tasks:()=>bd({Task:t=>this.csharp.classReference({name:"Task",namespace:"System.Threading.Tasks",generics:t?[t]:void 0}),ValueTask:t=>this.csharp.classReference({name:"ValueTask",namespace:"System.Threading.Tasks",generics:t?[t]:void 0})})}),ComponentModel:()=>bd({INotifyPropertyChanged:()=>this.csharp.classReference({name:"INotifyPropertyChanged",namespace:"System.ComponentModel"}),PropertyChangedEventHandler:()=>this.csharp.classReference({name:"PropertyChangedEventHandler",namespace:"System.ComponentModel"})}),IAsyncDisposable:()=>this.csharp.classReference({name:"IAsyncDisposable",namespace:"System"}),IDisposable:()=>this.csharp.classReference({name:"IDisposable",namespace:"System"})});NUnit=bd({Framework:()=>bd({TestFixture:()=>this.csharp.classReference({name:"TestFixture",namespace:"NUnit.Framework"}),Test:()=>this.csharp.classReference({name:"Test",namespace:"NUnit.Framework"}),OneTimeTearDown:()=>this.csharp.classReference({name:"OneTimeTearDown",namespace:"NUnit.Framework"}),OneTimeSetUp:()=>this.csharp.classReference({name:"OneTimeSetUp",namespace:"NUnit.Framework"}),SetUpFixture:()=>this.csharp.classReference({name:"SetUpFixture",namespace:"NUnit.Framework"})})});OneOf=bd({OneOf:t=>this.csharp.classReference({name:"OneOf",namespace:"OneOf",generics:t}),OneOfBase:t=>this.csharp.classReference({name:"OneOfBase",namespace:"OneOf",generics:t})});Google=bd({Protobuf:()=>bd({WellKnownTypes:()=>bd({Struct:()=>this.csharp.classReference({name:"Struct",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Value:()=>this.csharp.classReference({name:"Value",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),ListValue:()=>this.csharp.classReference({name:"ListValue",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Timestamp:()=>this.csharp.classReference({name:"Timestamp",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"})})})});WireMock=bd({Server:()=>this.csharp.classReference({name:"WireMockServer",namespace:"WireMock.Server"}),WireMockServerSettings:()=>this.csharp.classReference({name:"WireMockServerSettings",namespace:"WireMock.Settings"}),WireMockConsoleLogger:()=>this.csharp.classReference({name:"WireMockConsoleLogger",namespace:"WireMock.Logging"})});Grpc=bd({Core:()=>bd({RpcException:()=>this.csharp.classReference({name:"RpcException",namespace:"Grpc.Core"})})})};var aeo=require("assert");function uqh(e){return e.split(".").filter(t=>!["name","camelCase","snakeCase","screamingSnakeCase","pascalCase"].includes(t)).join(".")}var dmu=class{generation;indexByObject=new Map;indexByPath=new Map;explicitByObject=new Map;explicitByPath=new Map;root;ir;get csharp(){return this.generation.csharp}get registry(){return this.generation.registry}constructor(t,r){this.generation=r,this.root=this.createIndex(t),this.ir=t}createIndex(t,r="",i){let n=uqh(i?.jsonPath?`${i.jsonPath}.${r}`:r);if(this.indexByPath.has(n)){i||(0,aeo.fail)(`Parent provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),this.indexByObject.set(t,i);for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null&&this.createIndex(c,o,i);return i}let a={jsonPath:n,name:r,node:t,parent:i};this.indexByObject.set(t,a),this.indexByPath.set(n,a);for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null&&this.createIndex(c,o,a);return a}staticExplicit(t){return this.explicit(this.ir,t)}explicit(t,r){let i=this.provenance(t)??(0,aeo.fail)(`Provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),n={...i,jsonPath:uqh(`${i.jsonPath}+${r}`),name:r,node:i.node,parent:i,explicit:!0},a=this.explicitByObject.get(i.node);return a?a.add(n):this.explicitByObject.set(i.node,new Set([n])),this.explicitByPath.set(n.jsonPath,n),n}provenance(t){if(t!==void 0)return gl.string(t)?this.explicitByPath.get(t)??this.indexByPath.get(t):gl.Provenance(t)?this.explicitByPath.get(t.jsonPath)??this.indexByPath.get(t.jsonPath):this.indexByObject.get(t)}origin(t){let r=this.provenance(t);return r?.explicit?r:r?.node}irNode(t){return this.provenance(t)?.node}jsonPath(t){return this.provenance(t)?.jsonPath}getEnumValueName(t,r){let i=gl.IR.ExampleEnumType(r)?r.value.name:r.name,n=t.values.find(a=>this.nameEquals(a.name.name,i));return n?this.getPropertyNameFor(n):(0,aeo.fail)(`Unexpected - can't find enum value ${i} in enum`)}getPropertyNameFor(t){let r=this.registry.getFieldNameByOrigin(t);if(r)return r;if(gl.Provenance(t))return t.name;if("name"in t){if(gl.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if(gl.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${this.jsonPath(t)}`)}getClassNameFor(t){if(gl.Provenance(t))return t.name;if("name"in t){if(gl.IR.TypeDeclaration(t)||gl.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if(gl.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${JSON.stringify(t)}`)}nameEquals(t,r){return t.camelCase.safeName===r.camelCase.safeName}dereferenceType(t){let r=gl.string(t)?t:gl.IR.NamedType(t)||gl.IR.DeclaredTypeName(t)?t.typeId:gl.IR.ExampleNamedType(t)?t.typeName.typeId:t.name.typeId,i=this.irNode(this.ir.types[r]);if(gl.IR.TypeDeclaration(i))return{typeId:r,typeDeclaration:i};(0,aeo.fail)(`dereferenceType: typeId ${r} not resolved.`)}};var ueo=class{intermediateRepresentation;apiName;customConfig;generatorConfig;support;constructor(t,r,i,n,a={makeRelativeFilePath:o=>o,makeAbsoluteFilePath:o=>o,getNamespaceForTypeId:o=>"",getDirectoryForTypeId:o=>"",getCoreAsIsFiles:()=>[],getCoreTestAsIsFiles:()=>[],getPublicCoreAsIsFiles:()=>[],getAsyncCoreAsIsFiles:()=>[],getChildNamespaceSegments:o=>[]}){this.intermediateRepresentation=t,this.apiName=r,this.customConfig=i,this.generatorConfig=n,this.support=a,this.model=new dmu(t,this),this.ir=gl.IR.IntermediateRepresentation(t)?t:{},this.dir=gl.DynamicIR.DynamicIntermediateRepresentation(t)?t:{}}ir;dir;csharp=new lmu(this);registry=new apa(this);model;extern=new fmu(this);settings=bd({namespace:()=>this.customConfig.namespace??imu(nmu(`${this.generatorConfig.organization}_${this.apiName}`)),readOnlyMemoryTypes:()=>this.customConfig["read-only-memory-types"]??[],simplifyObjectDictionaries:()=>this.customConfig["simplify-object-dictionaries"]??!1,useFullyQualifiedNamespaces:()=>this.customConfig["experimental-fully-qualified-namespaces"]??!1,useDotnetFormat:()=>this.customConfig["experimental-dotnet-format"]??!1,enableWebsockets:()=>this.customConfig["experimental-enable-websockets"]??!1,enableReadonlyConstants:()=>this.customConfig["experimental-readonly-constants"]??!1,enableExplicitNullableOptional:()=>this.customConfig["experimental-explicit-nullable-optional"]??!1,useDefaultRequestParameterValues:()=>this.customConfig["use-default-request-parameter-values"]??!1,temporaryWebsocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},baseApiExceptionClassName:()=>this.customConfig["base-api-exception-class-name"]??"",baseExceptionClassName:()=>this.customConfig["base-exception-class-name"]??"",shouldGeneratedDiscriminatedUnions:()=>this.customConfig["use-discriminated-unions"]??!0,shouldGenerateUndiscriminatedUnions:()=>this.customConfig["use-undiscriminated-unions"]??!1,exportedClientClassName:()=>this.customConfig["exported-client-class-name"]??"",clientClassName:()=>this.customConfig["client-class-name"]??"",rootNamespaceForCoreClasses:()=>this.customConfig["root-namespace-for-core-classes"]??!0,packageId:()=>this.customConfig["package-id"]??"",isForwardCompatibleEnumsEnabled:()=>this.customConfig["enable-forward-compatible-enums"]??this.customConfig["experimental-enable-forward-compatible-enums"]??!0,websocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},customPagerName:()=>this.customConfig["custom-pager-name"]??"",environmentClassName:()=>this.customConfig["environment-class-name"]??"",generateErrorTypes:()=>this.customConfig["generate-error-types"]??!0,shouldInlinePathParameters:()=>this.customConfig["inline-path-parameters"]??!0,includeExceptionHandler:()=>this.customConfig["include-exception-handler"]??!1,exceptionInterceptorClassName:()=>this.customConfig["exception-interceptor-class-name"]??"",shouldGenerateMockServerTests:()=>this.customConfig["generate-mock-server-tests"]??this.customConfig["enable-wire-tests"]??!0,rootClientAccess:()=>this.customConfig["root-client-class-access"]=="internal"?QT.Internal:QT.Public,extraDependencies:()=>this.customConfig["extra-dependencies"]??{},pascalCaseEnvironments:()=>this.customConfig["pascal-case-environments"]??!0,explicitNamespaces:()=>this.customConfig["explicit-namespaces"]===!0,outputPath:()=>{let t=this.customConfig["output-path"];return t==null?{library:"src",test:"src",solution:".",other:"."}:typeof t=="string"?{library:t,test:t,solution:".",other:"."}:{library:t.library??"src",test:t.test??"src",solution:t.solution??".",other:t.other??"."}}});constants={folders:bd({mockServerTests:()=>this.support.makeRelativeFilePath("Unit/MockServer"),types:()=>"Types",exceptions:()=>"Exceptions",src:()=>"src",protobuf:()=>"proto",serializationTests:()=>this.support.makeRelativeFilePath("Unit/Serialization"),project:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.project))),sourceFiles:()=>this.support.makeRelativeFilePath(this.constants.folders.src),coreFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core))),publicCoreFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core),this.support.makeRelativeFilePath(this.constants.defaults.publicCore))),testFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.testProject)))}),formatting:bd({indent:()=>" "}),defaults:bd({core:()=>"Core",publicCore:()=>"Public",version:()=>"0.0.0"})};namespaces=bd({root:()=>this.settings.namespace,core:()=>`${this.namespaces.root}.Core`,test:()=>this.registry.canonicalizeNamespace(`${this.namespaces.root}.Test`),testUtils:()=>`${this.namespaces.test}.Utils`,mockServerTest:()=>`${this.namespaces.test}.Unit.MockServer`,publicCore:()=>this.namespaces.root,webSocketsCore:()=>`${this.namespaces.core}.WebSockets`,publicCoreTest:()=>`${this.namespaces.root}.Test.PublicCore`,asIsTestUtils:()=>`${this.namespaces.root}.Test.Utils`,publicCoreClasses:()=>this.settings.rootNamespaceForCoreClasses?this.namespaces.root:this.namespaces.core,implicit:()=>new Set(["System","System.Collections.Generic","System.IO","System.Linq","System.Threading","System.Threading.Tasks","System.Net.Http"])});names={classes:bd({baseApiException:()=>this.settings.baseApiExceptionClassName||`${this.names.project.clientPrefix}ApiException`,baseException:()=>this.settings.baseExceptionClassName||`${this.names.project.clientPrefix}Exception`,rootClient:()=>this.settings.clientClassName||`${this.names.project.clientPrefix}Client`,rootClientForSnippets:()=>this.settings.exportedClientClassName||this.names.classes.rootClient,customPager:()=>this.settings.customPagerName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}Pager`,environment:()=>this.settings.environmentClassName||`${this.names.project.clientPrefix}Environment`,exceptionInterceptor:()=>this.settings.exceptionInterceptorClassName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}ExceptionInterceptor`}),project:bd({client:()=>imu(nmu(`${this.generatorConfig.organization}_${this.generatorConfig.workspaceName}`)),clientPrefix:()=>this.settings.exportedClientClassName||this.settings.clientClassName||this.names.project.client,packageId:()=>this.settings.packageId||this.namespaces.root}),files:bd({project:()=>this.namespaces.root,testProject:()=>`${this.namespaces.root}.Test`}),methods:bd({mockOauth:()=>"MockOAuthEndpoint",mockInferredAuth:()=>"MockInferredAuthEndpoint",getAccessTokenAsync:()=>"GetAccessTokenAsync",getAuthHeadersAsync:()=>"GetAuthHeadersAsync"}),variables:bd({client:()=>"client",response:()=>"response",httpRequest:()=>"httpRequest",sendRequest:()=>"sendRequest",responseBody:()=>"responseBody",query:()=>"_query",headers:()=>"_headers"}),parameters:bd({cancellationToken:()=>"cancellationToken",requestOptions:()=>"options",idempotentOptions:()=>"options"})};Types=bd({Arbitrary:t=>new gm.AribitraryType(t,this),HttpMethodExtensions:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HttpMethodExtensions")}),FormRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("FormRequest")}),Optional:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Optional")}),ClientOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("ClientOptions"),namespace:this.namespaces.publicCoreClasses}),RawClient:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("RawClient")}),RequestOptions:()=>this.csharp.classReference({namespace:this.namespaces.publicCoreClasses,origin:this.model.staticExplicit("RequestOptions")}),RequestOptionsInterface:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("IRequestOptions")}),JsonRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("JsonRequest")}),Version:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("Version")}),ValueConvert:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("ValueConvert")}),FileParameter:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("FileParameter"),multipartMethodName:"AddFileParameterPart",multipartMethodNameForCollection:"AddFileParameterParts",isReferenceType:!0}),Headers:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Headers")}),HeaderValue:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HeaderValue")}),RootClient:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClient),namespace:this.namespaces.root}),RootClientForSnippets:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClientForSnippets),namespace:this.namespaces.root}),BaseApiException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseApiException),namespace:this.namespaces.publicCoreClasses}),BaseException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseException),namespace:this.namespaces.publicCoreClasses}),ExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit("IExceptionInterceptor"),namespace:this.namespaces.core}),ExceptionHandler:()=>this.csharp.classReference({origin:this.model.staticExplicit("ExceptionHandler"),namespace:this.namespaces.core}),CustomExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.exceptionInterceptor),namespace:this.namespaces.core}),ProtoAnyMapper:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoAnyMapper"),namespace:this.namespaces.core}),Constants:()=>this.csharp.classReference({origin:this.model.staticExplicit("Constants"),namespace:this.namespaces.core}),EnumSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("EnumSerializer"),namespace:this.namespaces.core}),DateTimeSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("DateTimeSerializer"),namespace:this.namespaces.core}),JsonUtils:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonUtils"),namespace:this.namespaces.core}),CustomPagerFactory:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Factory`),namespace:this.namespaces.core}),CustomPagerContext:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Context`),namespace:this.namespaces.core}),Environments:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.environment),namespace:this.namespaces.publicCoreClasses}),TestClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("TestClient"),namespace:this.namespaces.test}),BaseMockServerTest:()=>this.csharp.classReference({origin:this.model.staticExplicit("BaseMockServerTest"),namespace:this.namespaces.mockServerTest}),IdempotentRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("IdempotentRequestOptions"),namespace:this.namespaces.publicCoreClasses}),IdempotentRequestOptionsInterface:()=>this.csharp.classReference({origin:this.model.staticExplicit("IIdempotentRequestOptions"),namespace:this.namespaces.core}),IStringEnum:()=>this.csharp.classReference({origin:this.model.staticExplicit("IStringEnum"),namespace:this.namespaces.core}),WebSocketClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("WebSocketClient"),namespace:this.namespaces.webSocketsCore}),QueryBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("Query"),namespace:this.namespaces.webSocketsCore}),QueryStringBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder"),namespace:this.namespaces.core}),QueryStringBuilderBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder.Builder"),namespace:this.namespaces.core}),OAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("OAuthTokenProvider"),namespace:this.namespaces.core}),InferredAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("InferredAuthTokenProvider"),namespace:this.namespaces.core}),ProtoConverter:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoConverter"),namespace:this.namespaces.core}),RawGrpcClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("RawGrpcClient"),namespace:this.namespaces.core}),Extensions:()=>this.csharp.classReference({origin:this.model.staticExplicit("Extensions"),namespace:this.namespaces.core}),GrpcRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcRequestOptions"),namespace:this.namespaces.root}),GrpcChannelOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcChannelOptions"),namespace:"Grpc.Net.Client"}),StringEnum:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnum"),namespace:this.namespaces.core,generics:t?[t]:void 0}),WebSocketEvent:t=>this.csharp.classReference({origin:this.model.staticExplicit("Event"),namespace:this.namespaces.webSocketsCore,generics:[t]}),ConnectionStatus:()=>this.csharp.classReference({origin:this.model.staticExplicit("ConnectionStatus"),namespace:this.namespaces.webSocketsCore}),WebSocketConnected:()=>this.csharp.classReference({origin:this.model.staticExplicit("Connected"),namespace:this.namespaces.webSocketsCore}),WebSocketClosed:()=>this.csharp.classReference({origin:this.model.staticExplicit("Closed"),namespace:this.namespaces.webSocketsCore}),StringEnumSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnumSerializer"),namespace:this.namespaces.core,generics:[t]}),CustomPagerClass:t=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.customPager),namespace:this.namespaces.core,generics:[t]}),Pager:t=>this.csharp.classReference({origin:this.model.staticExplicit("Pager"),namespace:this.namespaces.core,generics:[t]}),OffsetPager:({requestType:t,requestOptionsType:r,responseType:i,offsetType:n,stepType:a,itemType:o})=>this.csharp.classReference({origin:this.model.staticExplicit("OffsetPager"),namespace:this.namespaces.core,generics:[t,r,i,n,a,o]}),CursorPager:({requestType:t,requestOptionsType:r,responseType:i,cursorType:n,itemType:a})=>this.csharp.classReference({origin:this.model.staticExplicit("CursorPager"),namespace:this.namespaces.core,generics:[t,r,i,n,a]}),CollectionItemSerializer:(t,r)=>this.csharp.classReference({origin:this.model.staticExplicit("CollectionItemSerializer"),namespace:this.namespaces.core,generics:[t,r]}),OneOfSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("OneOfSerializer"),namespace:this.namespaces.core,generics:[t]}),AdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("AdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0}),ReadOnlyAdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("ReadOnlyAdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0})});Primitive=bd({string:()=>new gm.String(this),boolean:()=>new gm.Boolean(this),integer:()=>new gm.Integer(this),long:()=>new gm.Long(this),uint:()=>new gm.Uint(this),ulong:()=>new gm.ULong(this),float:()=>new gm.Float(this),double:()=>new gm.Double(this),object:()=>new gm.Object(this)});Value=bd({binary:()=>new ome.Binary(this),dateOnly:()=>new ome.DateOnly(this),dateTime:()=>new ome.DateTime(this),uuid:()=>new ome.Uuid(this),stringEnum:t=>new ome.StringEnum(t,this)});Collection=bd({array:t=>new FQ.Array(t,this),listType:t=>new FQ.ListType(t,this),list:t=>new FQ.List(t,this),set:t=>new FQ.Set(t,this),map:(t,r,i)=>new FQ.Map(t,r,this,i),idictionary:(t,r,i)=>new FQ.IDictionary(t,r,this,i),keyValuePair:(t,r)=>new FQ.KeyValuePair(t,r,this)});format=bd({private:t=>`_${amu.camelCase(t)}`});initialize(){return this.initializers.implicitNamespaces}initializers=bd({implicitNamespaces:()=>{for(let t of this.namespaces.implicit)this.registry.addImplicitNamespace(t);return!0}});get System(){return this.extern.System}get NUnit(){return this.extern.NUnit}get OneOf(){return this.extern.OneOf}get Google(){return this.extern.Google}get Grpc(){return this.extern.Grpc}get WireMock(){return this.extern.WireMock}};var G5t=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get namespaces(){return this.generation.namespaces}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get registry(){return this.generation.registry}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get Grpc(){return this.generation.extern.Grpc}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}};var pmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.csharp.Literal.null():(this.context.errors.add({severity:Ur.Critical,message:"Expected non-null value, but got null"}),this.csharp.Literal.nop());if(t.value===void 0&&!t.fallbackToDefault)return this.csharp.Literal.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,fallbackToDefault:t.fallbackToDefault});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.csharp.Literal.nop():this.convertNamed({named:r,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault})}case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"unknown":return this.convertUnknown({value:t.value,fallbackToDefault:t.fallbackToDefault});default:le(t.typeReference)}}convertList({list:t,value:r,fallbackToDefault:i}){return Array.isArray(r)?this.csharp.Literal.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertLiteral({literal:t,value:r,fallbackToDefault:i}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?this.csharp.Literal.nop():this.csharp.Literal.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(n)}default:le(t)}}convertSet({set:t,value:r,fallbackToDefault:i}){return Array.isArray(r)?this.csharp.Literal.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertMap({map:t,value:r,fallbackToDefault:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ur.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),this.csharp.Literal.nop()):this.csharp.Literal.dictionary({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:t.value.type==="unknown"?this.context.dynamicTypeMapper.convert({typeReference:t.value}).asOptional():this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([n,a])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:a})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:i,fallbackToDefault:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:i,fallbackToDefault:n});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:n}):this.convertUnknown({value:r,fallbackToDefault:n});case"enum":return this.getEnumValue(t,r);case"object":return this.convertObject({object_:t,value:r,fallbackToDefault:n});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:n});default:le(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:i}){let n=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),a=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(a==null)return this.csharp.Literal.nop();let o=a.singleDiscriminatedUnionType,c=this.getBaseProperties({discriminatedUnionTypeInstance:a,singleDiscriminatedUnionType:o});switch(o.type){case"samePropertiesAsObject":{let d=this.context.resolveNamedType({typeId:o.typeId});return d==null?this.csharp.Literal.nop():this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.convertNamed({named:d,value:a.value})]})}case"singleProperty":{if(this.context.getRecord(a.value)==null)return this.csharp.Literal.nop();try{let s=["Value","Type"].includes(o.discriminantValue.name.pascalCase.safeName)?`${o.discriminantValue.name.pascalCase.safeName}Inner`:o.discriminantValue.name.pascalCase.safeName;return this.context.errors.scope(o.discriminantValue.wireValue),this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({name:s,enclosingType:n}),arguments_:[this.convert({typeReference:o.typeReference,value:o.discriminantValue.wireValue})]})]})}finally{this.context.errors.unscope()}}case"noProperties":return this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({origin:a.discriminantValue,enclosingType:n}),arguments_:[]})]});default:le(o)}}getBaseProperties({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(n=>{this.context.errors.scope(n.name.wireValue);try{return{name:this.context.getPropertyName(n.name.name),assignment:this.convert(n)}}finally{this.context.errors.unscope()}})}instantiateUnionWithBaseProperties({classReference:t,arguments_:r,baseProperties:i}){let n=this.csharp.instantiateClass({classReference:t,arguments_:r,multiline:!0});return i.length===0?this.csharp.Literal.reference(n):this.csharp.Literal.reference(this.csharp.codeblock(a=>{a.write(n," "),a.pushScope();for(let o of i)a.write(o.name," = ",o.assignment,",");a.popScope(!1)}))}getEnumValue(t,r){if(typeof r!="string")return this.context.errors.add({severity:Ur.Critical,message:`Expected enum value string, got: ${typeof r}`}),this.csharp.Literal.nop();let i=t.values.find(o=>o.wireValue===r);if(i==null)return this.context.errors.add({severity:Ur.Critical,message:`An enum value named "${r}" does not exist in this context`}),this.csharp.Literal.nop();let n=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),a=n.registerField(this.model.getPropertyNameFor(i),i);return this.csharp.Literal.reference(this.csharp.enumInstantiation({reference:n,value:a}))}convertObject({object_:t,value:r,fallbackToDefault:i}){let n=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:n.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getClassName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}})})}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:i}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n==null?this.csharp.Literal.nop():n.typeLiteral}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let i of t.types)try{let n=this.convert({typeReference:i,value:r});return{valueTypeReference:i,typeLiteral:n}}catch{continue}this.context.errors.add({severity:Ur.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,fallbackToDefault:r}){return this.csharp.Literal.unknown(t)}convertPrimitive({primitive:t,value:r,as:i,fallbackToDefault:n}){switch(t){case"INTEGER":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.integer.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.integer(a)}case"LONG":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.long.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.long(a)}case"UINT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.uint.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.uint(a)}case"UINT_64":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.ulong.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.ulong(a)}case"FLOAT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.float.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.float(a)}case"DOUBLE":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.double.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.double(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:r,as:i});return a==null?n?this.Primitive.boolean.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.boolean(a)}case"STRING":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"DATE":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Value.dateOnly.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.date(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Value.dateTime.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.datetime(a)}case"UUID":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"BASE_64":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"BIG_INTEGER":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}default:le(t)}}getValueAsNumber({value:t,as:r}){let i=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:r}){let i=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:i})}};var _mu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){switch(t.typeReference.type){case"list":return this.Collection.list(this.convert({typeReference:t.typeReference,unboxOptionals:!0}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return this.Collection.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":{let r=this.convert({typeReference:t.typeReference.value});return t.unboxOptionals?r.asNonOptional():r.asOptional()}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return this.Collection.set(this.convert({typeReference:t.typeReference,unboxOptionals:!0}));case"unknown":return this.convertUnknown();default:le(t.typeReference)}}convertToClassReference(t){return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)})}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"object":return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.Primitive.object;case"undiscriminatedUnion":return this.OneOf.OneOf(t.types.map(r=>this.convert({typeReference:r})));default:le(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return this.Primitive.boolean;case"string":return this.Primitive.string}}convertUnknown(){return this.Primitive.object}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return this.Primitive.integer;case"UINT":return this.Primitive.uint;case"LONG":return this.Primitive.long;case"UINT_64":return this.Primitive.ulong;case"FLOAT":return this.Primitive.float;case"DOUBLE":return this.Primitive.double;case"BOOLEAN":return this.Primitive.boolean;case"STRING":return this.Primitive.string;case"DATE":return this.Value.dateOnly;case"DATE_TIME":return this.Value.dateTime;case"UUID":return this.Primitive.string;case"BASE_64":return this.Primitive.string;case"BIG_INTEGER":return this.Primitive.string;default:le(t)}}};var hmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}getFilePropertyInfo({body:t,value:r}){let i={fileFields:[],bodyPropertyFields:[]},n=this.context.getRecord(r)??{};for(let a of t.properties)switch(a.type){case"file":gl.Record.missingKey(n,a.wireValue)&&(n[a.wireValue]="[bytes]"),i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getSingleFileProperty({property:a,record:n})});break;case"fileArray":gl.Record.missingKey(n,a.wireValue)&&(n[a.wireValue]=["[bytes]"]),i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getArrayFileProperty({property:a,record:n})});break;case"bodyProperty":if(gl.Record.missingKey(n,a.name.wireValue))switch(a.typeReference.type){case"optional":break;case"primitive":{switch(a.typeReference.value.toLowerCase()){case"integer":{n[a.name.wireValue]=123;break}case"string":{n[a.name.wireValue]="[string]";break}case"boolean":{n[a.name.wireValue]=!0;break}case"double":{n[a.name.wireValue]=123.456;break}case"float":{n[a.name.wireValue]=123.456;break}case"long":{n[a.name.wireValue]=123456789;break}case"uint":{n[a.name.wireValue]=123;break}case"uint64":{n[a.name.wireValue]=12345;break}case"date":{n[a.name.wireValue]=new Date(2021,1,1);break}case"datetime":{n[a.name.wireValue]=new Date(2021,1,1,12,0,0);break}case"uuid":{n[a.name.wireValue]="123e4567-e89b-12d3-a456-426614174000";break}case"base64":{n[a.name.wireValue]="SGVsbG8gd29ybGQh";break}case"biginteger":{n[a.name.wireValue]="12345678901234567890";break}}break}default:break}i.bodyPropertyFields.push({name:this.context.getPropertyName(a.name.name),value:this.getBodyProperty({property:a,record:n})});break;default:le(a)}return i}getSingleFileProperty({property:t,record:r}){let i=this.context.getSingleFileValue({property:t,record:r});return i==null?this.csharp.Literal.nop():this.context.getFileParameterForString(i)}getArrayFileProperty({property:t,record:r}){let i=this.context.getFileArrayValues({property:t,record:r});return i==null?this.csharp.Literal.nop():this.csharp.Literal.list({valueType:this.Types.FileParameter,values:i.map(n=>this.context.getFileParameterForString(n))})}getBodyProperty({property:t,record:r}){let i=r[t.name.wireValue];return i==null?this.csharp.Literal.nop():this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var ymu=class e extends Oq{ir;dynamicTypeMapper;dynamicLiteralMapper;filePropertyMapper;generation;get namespaces(){return this.generation.namespaces}get registry(){return this.generation.registry}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get csharp(){return this.generation.csharp}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}constructor({ir:t,config:r,options:i,generation:n}){super({ir:t,config:r,options:i}),this.ir=t,this.generation=n??new ueo(t,r.workspaceName,r.customConfig!=null?r.customConfig:{},r),this.dynamicTypeMapper=new _mu({context:this}),this.dynamicLiteralMapper=new pmu({context:this}),this.filePropertyMapper=new hmu({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options,generation:this.generation})}getFileParameterForString(t){return this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.FileParameter,arguments_:[],properties:[{name:"Stream",value:this.getMemoryStreamForString(t)}],multiline:!0}))}getMemoryStreamForString(t){return this.System.IO.MemoryStream.new({arguments_:[this.csharp.invokeMethod({on:this.System.Text.Encoding_UTF8,method:"GetBytes",arguments_:[this.csharp.Literal.string(t)]})]})}getClassName(t){return t.pascalCase.safeName}getParameterName(t){return t.camelCase.safeName}getPropertyName(t){return t.pascalCase.safeName}getMethodName(t){return`${t.pascalCase.safeName}Async`}getNamespace(t,r){let i=this.getNamespaceSegments(t);return i=r!=null?[...i,r]:i,[this.namespaces.root,...i].join(".")}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentClassReferenceForEnumName(r)}getEnvironmentClassReferenceForEnumName(t){return this.csharp.classReference({name:`${this.generation.Types.Environments.name}.${this.getClassName(t)}`,namespace:this.namespaces.root})}getNamespaceSegments(t){return(this.settings.explicitNamespaces?t.allParts:t.packagePath).map(i=>i.pascalCase.safeName)}precalculate(t){this.generation.initialize(),this.System.Collections.Generic.KeyValuePair(),this.System.Collections.Generic.IEnumerable(),this.System.Collections.Generic.IAsyncEnumerable(),this.System.Collections.Generic.HashSet(),this.System.Collections.Generic.List(),this.System.Collections.Generic.Dictionary(),this.System.Threading.Tasks.Task(),Object.entries(this.ir.types).sort((r,i)=>r[0].length-i[0].length).forEach(([r,i])=>{this.dynamicTypeMapper.convertToClassReference(i)});for(let[r,i]of t.entries())if(this.csharp.classReference({origin:this.model.staticExplicit(`Example${r}`),namespace:"Usage"}),i.endpoint){let n=this.resolveEndpointLocation(i.endpoint);for(let a of n)switch(a.request.type){case"inlined":this.csharp.classReference({origin:a.request.declaration.name,namespace:this.getNamespace(a.request.declaration.fernFilepath)});break;case"body":break}}this.generation.Types.ClientOptions,this.generation.Types.RootClient,this.csharp.freezeClassReferences()}};var bmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}async generateSnippet({endpoint:t,request:r,options:i}){return this.buildCodeBlock({endpoint:t,snippet:r,options:i}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map})}generateSnippetSync({endpoint:t,request:r,options:i}){return this.buildCodeBlock({endpoint:t,snippet:r,options:i}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map})}async generateSnippetAst({endpoint:t,request:r,options:i}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:i}){if(t.examples&&!t.examples?.find(o=>gl.DynamicIR.EndpointExample(r)&&o.id===r.id))throw new Error("Endpoint does not have an example that matches the snippet");let n=this.csharp.codeblock(o=>{o.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),o.newLine(),o.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),a=this.getStyle(i);switch(a){case Vz.Concise:return n;case Vz.Full:return this.buildFullCodeBlock({body:n,options:i});default:le(a)}}buildFullCodeBlock({body:t,options:r}){let i=this.getConfig(r),n=this.csharp.class_({name:i.fullStyleClassName??"Example",namespace:"Usage",access:npa.Access.Public});return n.addNamespaceReference(this.Types.RootClient.namespace),n.addMethod({name:"Do",access:npa.Access.Public,isAsync:!0,parameters:[],body:t}),n}constructClient({endpoint:t,snippet:r}){return this.csharp.codeblock(i=>{i.write("var client = "),i.writeNode(this.getRootClientConstructorInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){let i=t.response?.type==="streaming"||t.response?.type==="streamParameter",n=this.csharp.invokeMethod({on:this.csharp.codeblock("client"),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),async:!0,configureAwait:!0,multiline:!0,isAsyncEnumerable:i});return i?this.csharp.codeblock(a=>{a.write("await foreach (var item in "),a.writeNode(n),a.writeLine(")"),a.pushScope(),a.writeLine("/* consume each item */"),a.popScope()}):n}getConstructorArgs({endpoint:t,snippet:r}){let i=[];t.auth!=null&&(r.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ur.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let n=[],a=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});a.length>0&&n.push(...a),this.context.errors.scope(Po.Headers);let o=[];return this.context.ir.headers!=null&&r.headers!=null&&o.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n.length===0?[...i,...o]:[...i,...o,{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:n.map(c=>({name:c.name,assignment:c.assignment})),multiline:!0})}]}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let i=this.getBaseUrlArg({baseUrl:t,environment:r});return gl.Literal.nop(i)?[]:[{name:this.getBaseUrlOptionName(),assignment:i}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ur.Critical,message:"Cannot specify both baseUrl and environment options"}),this.csharp.Literal.nop();if(t!=null)return this.context.ir.environments?.environments.type==="multipleBaseUrls"?(this.context.errors.add({severity:Ur.Critical,message:"The C# SDK doesn't support a baseUrl when multiple URL environments are configured"}),this.csharp.Literal.nop()):this.csharp.Literal.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let i=this.context.getEnvironmentTypeReferenceFromID(r);return i==null?(this.context.errors.add({severity:Ur.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),this.csharp.Literal.nop()):this.csharp.Literal.reference(i)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.Environments,arguments_:Object.entries(r).map(([i,n])=>({name:Ff(yn(i)),assignment:this.context.dynamicLiteralMapper.convert({typeReference:{type:"primitive",value:"STRING"},value:n})})),multiline:!0})):this.csharp.Literal.nop()}return this.csharp.Literal.nop()}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArg({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:le(t)}}addError(t){this.context.errors.add({severity:Ur.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ur.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getParameterName(t.username),assignment:this.csharp.Literal.string(r.username)},{name:this.context.getParameterName(t.password),assignment:this.csharp.Literal.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.token),assignment:this.csharp.Literal.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.header.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value,fallbackToDefault:t.header.name.wireValue})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.clientId),assignment:this.csharp.Literal.string(r.clientId)},{name:this.context.getParameterName(t.clientSecret),assignment:this.csharp.Literal.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let i=[];if(t.parameters!=null)for(let n of t.parameters){let a=n.name.wireValue,o=r.values?.[a];i.push({name:this.context.getParameterName(n.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:n.typeReference,value:o,fallbackToDefault:a})})}else this.context.errors.add({severity:Ur.Critical,message:"Inferred auth parameters are not defined in the IR. Please ensure you're using IR version 62.3.0 or later."});return i}getConstructorHeaderArgs({headers:t,values:r}){let i=[];for(let n of t){let a=this.getConstructorHeaderArg({header:n,value:r.value});a!=null&&i.push({name:this.context.getParameterName(n.name.name),assignment:a})}return i}getConstructorHeaderArg({header:t,value:r}){let i=this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:r,fallbackToDefault:t.name.wireValue});if(!gl.Literal.nop(i))return i}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:le(t.request)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(Po.PathParameters);let n=[],a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let o=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})||i.push(...n.map(c=>c.value)),i.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})?n:[],filePropertyInfo:o})),i}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:i,filePropertyInfo:n}){this.context.errors.scope(Po.QueryParameters);let o=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicLiteralMapper.convert(u)}));this.context.errors.unscope(),this.context.errors.scope(Po.Headers);let d=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicLiteralMapper.convert({...u,fallbackToDefault:u.name.wireValue})}));this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let s=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];return this.context.errors.unscope(),this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:[...i,...o,...d,...s]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:i});default:le(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let i=[],n=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicLiteralMapper.convert({...a,fallbackToDefault:a.name.wireValue})});return i}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:le(t)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(Po.PathParameters);let n=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return n.length>0&&i.push(...this.getPathParameters({namedParameters:n,snippet:r}).map(a=>a.value)),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody),t.body!=null&&i.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),i}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return t.value.type==="optional"&&r==null?this.csharp.Literal.null():this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:le(t)}}getBytesBodyRequestArg({value:t}){let r=this.context.getValueAsString({value:t});return r==null&&(this.context.errors.add({severity:Ur.Critical,message:"The bytes request body must be provided in string format"}),r="[bytes]"),this.csharp.Literal.reference(this.context.getMemoryStreamForString(r))}getRootClientConstructorInvocation(t){return this.csharp.instantiateClass({classReference:this.Types.RootClient,arguments_:t,forceUseConstructor:!0,multiline:!0})}getPathParameters({namedParameters:t,snippet:r}){let i=[],n=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicLiteralMapper.convert({...a,fallbackToDefault:a.name.wireValue})});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getClassName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getBaseUrlOptionName(){return this.context.ir.environments?.environments.type==="multipleBaseUrls"?"Environment":"BaseUrl"}getStyle(t){return t.style??this.context.options.style??Vz.Full}getConfig(t){return t.config??this.context.options.config??{}}};var seo=class extends gq{constructor({ir:t,config:r,options:i={}}){super(new ymu({ir:t,config:r,options:i}))}precalculate(t){this.context.precalculate(t)}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new bmu({context:t})}};var opa=require("fs/promises"),cqh=ue(require("path"),1);function QQ(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:_fB(e.auth)}}function _fB(e){if(e!=null)return e}function sqh(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,hfB(r)]).filter(([t,r])=>r!=null))}function hfB(e){let t=e.location.method;if(t!=="HEAD")return{...e,location:{...e.location,method:t},examples:e.examples!=null?yfB(e.examples):void 0,auth:gfB(e.auth)}}function yfB(e){return e.map(t=>bfB(t)).filter(t=>t!=null)}function bfB(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:vfB(e.auth)}}function vfB(e){if(e!=null)return e}function gfB(e){if(e!=null)return e}function UQ(e){return{...e,endpoints:sqh(e.endpoints)}}var OfB=`
|
|
1307
|
+
${Hka()}`)}return this.generation.registry.registerClassReference(t,r)}freezeClassReferences(){this.frozen=!0}getPropertyName(t,r){let i=this.model.getPropertyNameFor(r),n=this.model.origin(r)??(0,oqh.fail)(`Origin not found for property: ${JSON.stringify(r).substring(0,100)}`),a=t.getFieldName(n,i);return a||i}class_(t){let r=t;return"reference"in t&&(r={...t.reference,...t}),new yer(r,this.generation)}testClass(t){return new ipa(t,this.generation)}annotation(t){return new v3i(t,this.generation)}annotationGroup(t){return new Kda(t,this.generation)}instantiateClass(t){return new Nda(t,this.generation)}invokeMethod(t){return new Lda(t,this.generation)}codeblock(t){return new o2i(t,this.generation)}code(){return new u2i({},this.generation)}anonymousFunction(t){return new $da(t)}parameter(t){return new W5t(t,this.generation)}interface_(t){return new rpa(t,this.generation)}enum_(t){return new tpa(t,this.generation)}dictionary(t){return new Fda(t,this.generation)}list(t){return new Uda(t,this.generation)}readOnlyMemory(t){return new Vda(t,this.generation)}set(t){return new Wda(t,this.generation)}switch_(t){return new Yda(t,this.generation)}ternary(t){return new Xda(t,this.generation)}and(t){return new Hda(t,this.generation)}or(t){return new Jda(t,this.generation)}enumInstantiation(t){return new Qda(t,this.generation)}string_(t){return new xda(t,this.generation)}xmlDocBlock(t){return new s2i(t,this.generation)}InstantiatedPrimitive={string:t=>new e3({type:"string",value:t},this.generation),boolean:t=>new e3({type:"boolean",value:t},this.generation),integer:t=>new e3({type:"integer",value:t},this.generation),long:t=>new e3({type:"long",value:t},this.generation),uint:t=>new e3({type:"uint",value:t},this.generation),ulong:t=>new e3({type:"ulong",value:t},this.generation),float:t=>new e3({type:"float",value:t},this.generation),double:t=>new e3({type:"double",value:t},this.generation),date:t=>new e3({type:"date",value:t},this.generation),dateTime:(t,r=!0)=>new e3({type:"dateTime",value:t,parse:r},this.generation),uuid:t=>new e3({type:"uuid",value:t},this.generation),null:()=>new e3({type:"null"},this.generation)};Literal={class_:({reference:t,fields:r})=>new ap.Class_(t,r,this.generation),dictionary:({keyType:t,valueType:r,entries:i})=>new ap.Dictionary(t,r,i,this.generation),list:({valueType:t,values:r})=>new ap.List(t,r,this.generation),set:({valueType:t,values:r})=>new ap.Set(t,r,this.generation),boolean:t=>new ap.Boolean(t,this.generation),float:t=>new ap.Float(t,this.generation),date:t=>new ap.Date(t,this.generation),datetime:t=>new ap.DateTime(t,this.generation),decimal:t=>new ap.Decimal(t,this.generation),double:t=>new ap.Double(t,this.generation),integer:t=>new ap.Integer(t,this.generation),long:t=>new ap.Long(t,this.generation),uint:t=>new ap.Uint(t,this.generation),ulong:t=>new ap.Ulong(t,this.generation),reference:t=>new ap.Reference(t,this.generation),string:t=>new ap.String(t,this.generation),null:()=>new ap.Null(this.generation),nop:()=>new ap.Nop(this.generation),unknown:t=>new ap.Unknown(t,this.generation)};xmlDocBlockOf(t){return t instanceof s2i?t:new s2i(t,this.generation)}VALID_READ_ONLY_MEMORY_TYPES=new Set(["int","long","uint","ulong","string","bool","float","double"]);validateReadOnlyMemoryTypes(){for(let t of this.generation.settings.readOnlyMemoryTypes)if(!this.VALID_READ_ONLY_MEMORY_TYPES.has(t))throw new Error(`Type "${t}" is not a valid 'read-only-memory-types' custom config option; expected one of ${JSON.stringify(this.VALID_READ_ONLY_MEMORY_TYPES)}.`)}};function bd(e){let t={},r={};for(let[i,n]of Object.entries(e))n.length===0?Object.defineProperty(r,i,{get(){return i in t||(t[i]=n()),t[i]},enumerable:!0,configurable:!0}):r[i]=n;return r}var fmu=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}System=bd({Action:t=>this.csharp.classReference({name:"Action",namespace:"System",generics:t||void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),Func:(t,r)=>this.csharp.classReference({name:"Func",namespace:"System",generics:t?r?[...t,r]:t:r?[r]:void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),DateOnly:()=>this.csharp.classReference({name:"DateOnly",namespace:"System"}),DateTime:()=>this.csharp.classReference({name:"DateTime",namespace:"System"}),Enum:()=>this.csharp.classReference({name:"Enum",namespace:"System"}),Exception:()=>this.csharp.classReference({name:"Exception",namespace:"System"}),ReadOnlyMemory:t=>this.csharp.classReference({name:"ReadOnlyMemory",namespace:"System",generics:[t]}),Serializable:()=>this.csharp.classReference({name:"SerializableAttribute",namespace:"System"}),String:()=>this.csharp.classReference({name:"String",namespace:"System"}),Type:()=>this.csharp.classReference({name:"Type",namespace:"System",isReferenceType:!0,multipartMethodName:null,multipartMethodNameForCollection:null,fullyQualified:!0}),TimeSpan:()=>this.csharp.classReference({name:"TimeSpan",namespace:"System"}),Uri:()=>this.csharp.classReference({name:"Uri",namespace:"System"}),UriBuilder:()=>this.csharp.classReference({name:"UriBuilder",namespace:"System"}),Runtime:()=>bd({Serialization:()=>bd({EnumMember:()=>this.csharp.classReference({name:"EnumMemberAttribute",namespace:"System.Runtime.Serialization"})})}),Collections:()=>bd({Generic:()=>bd({IAsyncEnumerable:t=>this.csharp.classReference({name:"IAsyncEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),IEnumerable:t=>this.csharp.classReference({name:"IEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),KeyValuePair:(t,r)=>this.csharp.classReference({name:"KeyValuePair",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0}),List:t=>this.csharp.classReference({name:"List",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),HashSet:t=>this.csharp.classReference({name:"HashSet",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),Dictionary:(t,r)=>this.csharp.classReference({name:"Dictionary",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0,isCollection:!0}),IDictionary:(t,r)=>this.csharp.classReference({name:"IDictionary",namespace:"System.Collections.Generic",generics:[t,r]})}),Linq:()=>bd({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})})}),Globalization:()=>bd({DateTimeStyles:()=>this.csharp.classReference({name:"DateTimeStyles",namespace:"System.Globalization"})}),Linq:()=>bd({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})}),Net:()=>bd({Http:()=>bd({HttpClient:()=>this.csharp.classReference({name:"HttpClient",namespace:"System.Net.Http"}),HttpMethod:()=>this.csharp.classReference({name:"HttpMethod",namespace:"System.Net.Http"}),HttpResponseHeaders:()=>this.csharp.classReference({name:"HttpResponseHeaders",namespace:"System.Net.Http.Headers"})}),ServerSentEvents:()=>bd({SseEvent:()=>this.csharp.classReference({name:"SseEvent",namespace:"System.Net.ServerSentEvents"}),SseParser:()=>this.csharp.classReference({name:"SseParser",namespace:"System.Net.ServerSentEvents"})}),WebSockets:()=>bd({ClientWebSocketOptions:()=>this.csharp.classReference({name:"ClientWebSocketOptions",namespace:"System.Net.WebSockets"})})}),IO:()=>bd({MemoryStream:()=>this.csharp.classReference({name:"MemoryStream",namespace:"System.IO"}),Stream:()=>this.csharp.classReference({name:"Stream",namespace:"System.IO"}),StreamReader:()=>this.csharp.classReference({name:"StreamReader",namespace:"System.IO"})}),Text:()=>bd({Encoding:()=>this.csharp.classReference({name:"Encoding",namespace:"System.Text"}),Encoding_UTF8:()=>this.csharp.classReference({name:"UTF8",enclosingType:this.csharp.classReference({name:"Encoding",namespace:"System.Text"})}),Json:()=>bd({JsonElement:()=>this.csharp.classReference({name:"JsonElement",namespace:"System.Text.Json"}),JsonDocument:()=>this.csharp.classReference({name:"JsonDocument",namespace:"System.Text.Json"}),JsonException:()=>this.csharp.classReference({name:"JsonException",namespace:"System.Text.Json"}),Utf8JsonReader:()=>this.csharp.classReference({name:"Utf8JsonReader",namespace:"System.Text.Json"}),JsonSerializerOptions:()=>this.csharp.classReference({name:"JsonSerializerOptions",namespace:"System.Text.Json"}),JsonSerializer:()=>this.csharp.classReference({name:"JsonSerializer",namespace:"System.Text.Json"}),Utf8JsonWriter:()=>this.csharp.classReference({name:"Utf8JsonWriter",namespace:"System.Text.Json"}),Nodes:()=>bd({JsonNode:()=>this.csharp.classReference({name:"JsonNode",namespace:"System.Text.Json.Nodes"}),JsonObject:()=>this.csharp.classReference({name:"JsonObject",namespace:"System.Text.Json.Nodes"})}),Serialization:()=>bd({IJsonOnDeserialized:()=>this.csharp.classReference({name:"IJsonOnDeserialized",namespace:"System.Text.Json.Serialization"}),IJsonOnSerializing:()=>this.csharp.classReference({name:"IJsonOnSerializing",namespace:"System.Text.Json.Serialization"}),JsonOnDeserializedAttribute:()=>this.csharp.classReference({name:"JsonOnDeserializedAttribute",namespace:"System.Text.Json.Serialization"}),JsonExtensionData:()=>this.csharp.classReference({name:"JsonExtensionDataAttribute",namespace:"System.Text.Json.Serialization"}),JsonConverter:t=>this.csharp.classReference({name:"JsonConverter",namespace:"System.Text.Json.Serialization",generics:t?[t]:void 0}),JsonIgnore:()=>this.csharp.classReference({name:"JsonIgnoreAttribute",namespace:"System.Text.Json.Serialization"}),JsonPropertyName:()=>this.csharp.classReference({name:"JsonPropertyNameAttribute",namespace:"System.Text.Json.Serialization"})})})}),Threading:()=>bd({CancellationToken:()=>this.csharp.classReference({name:"CancellationToken",namespace:"System.Threading"}),Tasks:()=>bd({Task:t=>this.csharp.classReference({name:"Task",namespace:"System.Threading.Tasks",generics:t?[t]:void 0}),ValueTask:t=>this.csharp.classReference({name:"ValueTask",namespace:"System.Threading.Tasks",generics:t?[t]:void 0})})}),ComponentModel:()=>bd({INotifyPropertyChanged:()=>this.csharp.classReference({name:"INotifyPropertyChanged",namespace:"System.ComponentModel"}),PropertyChangedEventHandler:()=>this.csharp.classReference({name:"PropertyChangedEventHandler",namespace:"System.ComponentModel"})}),IAsyncDisposable:()=>this.csharp.classReference({name:"IAsyncDisposable",namespace:"System"}),IDisposable:()=>this.csharp.classReference({name:"IDisposable",namespace:"System"})});NUnit=bd({Framework:()=>bd({TestFixture:()=>this.csharp.classReference({name:"TestFixture",namespace:"NUnit.Framework"}),Test:()=>this.csharp.classReference({name:"Test",namespace:"NUnit.Framework"}),OneTimeTearDown:()=>this.csharp.classReference({name:"OneTimeTearDown",namespace:"NUnit.Framework"}),OneTimeSetUp:()=>this.csharp.classReference({name:"OneTimeSetUp",namespace:"NUnit.Framework"}),SetUpFixture:()=>this.csharp.classReference({name:"SetUpFixture",namespace:"NUnit.Framework"})})});OneOf=bd({OneOf:t=>this.csharp.classReference({name:"OneOf",namespace:"OneOf",generics:t}),OneOfBase:t=>this.csharp.classReference({name:"OneOfBase",namespace:"OneOf",generics:t})});Google=bd({Protobuf:()=>bd({WellKnownTypes:()=>bd({Struct:()=>this.csharp.classReference({name:"Struct",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Value:()=>this.csharp.classReference({name:"Value",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),ListValue:()=>this.csharp.classReference({name:"ListValue",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Timestamp:()=>this.csharp.classReference({name:"Timestamp",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"})})})});WireMock=bd({Server:()=>this.csharp.classReference({name:"WireMockServer",namespace:"WireMock.Server"}),WireMockServerSettings:()=>this.csharp.classReference({name:"WireMockServerSettings",namespace:"WireMock.Settings"}),WireMockConsoleLogger:()=>this.csharp.classReference({name:"WireMockConsoleLogger",namespace:"WireMock.Logging"})});Grpc=bd({Core:()=>bd({RpcException:()=>this.csharp.classReference({name:"RpcException",namespace:"Grpc.Core"})})})};var aeo=require("assert");function uqh(e){return e.split(".").filter(t=>!["name","camelCase","snakeCase","screamingSnakeCase","pascalCase"].includes(t)).join(".")}var dmu=class{generation;indexByObject=new Map;indexByPath=new Map;explicitByObject=new Map;explicitByPath=new Map;root;ir;get csharp(){return this.generation.csharp}get registry(){return this.generation.registry}constructor(t,r){this.generation=r,this.root=this.createIndex(t),this.ir=t}createIndex(t,r="",i){let n=uqh(i?.jsonPath?`${i.jsonPath}.${r}`:r);if(this.indexByPath.has(n)){i||(0,aeo.fail)(`Parent provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),this.indexByObject.set(t,i);for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null&&this.createIndex(c,o,i);return i}let a={jsonPath:n,name:r,node:t,parent:i};this.indexByObject.set(t,a),this.indexByPath.set(n,a);for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null&&this.createIndex(c,o,a);return a}staticExplicit(t){return this.explicit(this.ir,t)}explicit(t,r){let i=this.provenance(t)??(0,aeo.fail)(`Provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),n={...i,jsonPath:uqh(`${i.jsonPath}+${r}`),name:r,node:i.node,parent:i,explicit:!0},a=this.explicitByObject.get(i.node);return a?a.add(n):this.explicitByObject.set(i.node,new Set([n])),this.explicitByPath.set(n.jsonPath,n),n}provenance(t){if(t!==void 0)return gl.string(t)?this.explicitByPath.get(t)??this.indexByPath.get(t):gl.Provenance(t)?this.explicitByPath.get(t.jsonPath)??this.indexByPath.get(t.jsonPath):this.indexByObject.get(t)}origin(t){let r=this.provenance(t);return r?.explicit?r:r?.node}irNode(t){return this.provenance(t)?.node}jsonPath(t){return this.provenance(t)?.jsonPath}getEnumValueName(t,r){let i=gl.IR.ExampleEnumType(r)?r.value.name:r.name,n=t.values.find(a=>this.nameEquals(a.name.name,i));return n?this.getPropertyNameFor(n):(0,aeo.fail)(`Unexpected - can't find enum value ${i} in enum`)}getPropertyNameFor(t){let r=this.registry.getFieldNameByOrigin(t);if(r)return r;if(gl.Provenance(t))return t.name;if("name"in t){if(gl.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if(gl.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${this.jsonPath(t)}`)}getClassNameFor(t){if(gl.Provenance(t))return t.name;if("name"in t){if(gl.IR.TypeDeclaration(t)||gl.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if(gl.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${JSON.stringify(t)}`)}nameEquals(t,r){return t.camelCase.safeName===r.camelCase.safeName}dereferenceType(t){let r=gl.string(t)?t:gl.IR.NamedType(t)||gl.IR.DeclaredTypeName(t)?t.typeId:gl.IR.ExampleNamedType(t)?t.typeName.typeId:t.name.typeId,i=this.irNode(this.ir.types[r]);if(gl.IR.TypeDeclaration(i))return{typeId:r,typeDeclaration:i};(0,aeo.fail)(`dereferenceType: typeId ${r} not resolved.`)}};var ueo=class{intermediateRepresentation;apiName;customConfig;generatorConfig;support;constructor(t,r,i,n,a={makeRelativeFilePath:o=>o,makeAbsoluteFilePath:o=>o,getNamespaceForTypeId:o=>"",getDirectoryForTypeId:o=>"",getCoreAsIsFiles:()=>[],getCoreTestAsIsFiles:()=>[],getPublicCoreAsIsFiles:()=>[],getAsyncCoreAsIsFiles:()=>[],getChildNamespaceSegments:o=>[]}){this.intermediateRepresentation=t,this.apiName=r,this.customConfig=i,this.generatorConfig=n,this.support=a,this.model=new dmu(t,this),this.ir=gl.IR.IntermediateRepresentation(t)?t:{},this.dir=gl.DynamicIR.DynamicIntermediateRepresentation(t)?t:{}}ir;dir;csharp=new lmu(this);registry=new apa(this);model;extern=new fmu(this);settings=bd({namespace:()=>this.customConfig.namespace??imu(nmu(`${this.generatorConfig.organization}_${this.apiName}`)),readOnlyMemoryTypes:()=>this.customConfig["read-only-memory-types"]??[],simplifyObjectDictionaries:()=>this.customConfig["simplify-object-dictionaries"]??!1,useFullyQualifiedNamespaces:()=>this.customConfig["experimental-fully-qualified-namespaces"]??!1,useDotnetFormat:()=>this.customConfig["experimental-dotnet-format"]??!1,enableWebsockets:()=>this.customConfig["experimental-enable-websockets"]??!1,enableReadonlyConstants:()=>this.customConfig["experimental-readonly-constants"]??!1,enableExplicitNullableOptional:()=>this.customConfig["experimental-explicit-nullable-optional"]??!1,useDefaultRequestParameterValues:()=>this.customConfig["use-default-request-parameter-values"]??!1,temporaryWebsocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},baseApiExceptionClassName:()=>this.customConfig["base-api-exception-class-name"]??"",baseExceptionClassName:()=>this.customConfig["base-exception-class-name"]??"",shouldGeneratedDiscriminatedUnions:()=>this.customConfig["use-discriminated-unions"]??!0,shouldGenerateUndiscriminatedUnions:()=>this.customConfig["use-undiscriminated-unions"]??!1,exportedClientClassName:()=>this.customConfig["exported-client-class-name"]??"",clientClassName:()=>this.customConfig["client-class-name"]??"",rootNamespaceForCoreClasses:()=>this.customConfig["root-namespace-for-core-classes"]??!0,packageId:()=>this.customConfig["package-id"]??"",isForwardCompatibleEnumsEnabled:()=>this.customConfig["enable-forward-compatible-enums"]??this.customConfig["experimental-enable-forward-compatible-enums"]??!0,websocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},customPagerName:()=>this.customConfig["custom-pager-name"]??"",environmentClassName:()=>this.customConfig["environment-class-name"]??"",generateErrorTypes:()=>this.customConfig["generate-error-types"]??!0,shouldInlinePathParameters:()=>this.customConfig["inline-path-parameters"]??!0,includeExceptionHandler:()=>this.customConfig["include-exception-handler"]??!1,exceptionInterceptorClassName:()=>this.customConfig["exception-interceptor-class-name"]??"",shouldGenerateMockServerTests:()=>this.customConfig["generate-mock-server-tests"]??this.customConfig["enable-wire-tests"]??!0,rootClientAccess:()=>this.customConfig["root-client-class-access"]=="internal"?QT.Internal:QT.Public,extraDependencies:()=>this.customConfig["extra-dependencies"]??{},pascalCaseEnvironments:()=>this.customConfig["pascal-case-environments"]??!0,explicitNamespaces:()=>this.customConfig["explicit-namespaces"]===!0,outputPath:()=>{let t=this.customConfig["output-path"];return t==null?{library:"src",test:"src",solution:".",other:"."}:typeof t=="string"?{library:t,test:t,solution:".",other:"."}:{library:t.library??"src",test:t.test??"src",solution:t.solution??".",other:t.other??"."}}});constants={folders:bd({mockServerTests:()=>this.support.makeRelativeFilePath("Unit/MockServer"),types:()=>"Types",exceptions:()=>"Exceptions",src:()=>"src",protobuf:()=>"proto",serializationTests:()=>this.support.makeRelativeFilePath("Unit/Serialization"),project:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.project))),sourceFiles:()=>this.support.makeRelativeFilePath(this.constants.folders.src),coreFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core))),publicCoreFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core),this.support.makeRelativeFilePath(this.constants.defaults.publicCore))),testFiles:()=>this.support.makeRelativeFilePath((0,oeo.join)(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.testProject)))}),formatting:bd({indent:()=>" "}),defaults:bd({core:()=>"Core",publicCore:()=>"Public",version:()=>"0.0.0"})};namespaces=bd({root:()=>this.settings.namespace,core:()=>`${this.namespaces.root}.Core`,test:()=>this.registry.canonicalizeNamespace(`${this.namespaces.root}.Test`),testUtils:()=>`${this.namespaces.test}.Utils`,mockServerTest:()=>`${this.namespaces.test}.Unit.MockServer`,publicCore:()=>this.namespaces.root,webSocketsCore:()=>`${this.namespaces.core}.WebSockets`,publicCoreTest:()=>`${this.namespaces.root}.Test.PublicCore`,asIsTestUtils:()=>`${this.namespaces.root}.Test.Utils`,publicCoreClasses:()=>this.settings.rootNamespaceForCoreClasses?this.namespaces.root:this.namespaces.core,implicit:()=>new Set(["System","System.Collections.Generic","System.IO","System.Linq","System.Threading","System.Threading.Tasks","System.Net.Http"])});names={classes:bd({baseApiException:()=>this.settings.baseApiExceptionClassName||`${this.names.project.clientPrefix}ApiException`,baseException:()=>this.settings.baseExceptionClassName||`${this.names.project.clientPrefix}Exception`,rootClient:()=>this.settings.clientClassName||`${this.names.project.clientPrefix}Client`,rootClientForSnippets:()=>this.settings.exportedClientClassName||this.names.classes.rootClient,customPager:()=>this.settings.customPagerName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}Pager`,environment:()=>this.settings.environmentClassName||`${this.names.project.clientPrefix}Environment`,exceptionInterceptor:()=>this.settings.exceptionInterceptorClassName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}ExceptionInterceptor`}),project:bd({client:()=>imu(nmu(`${this.generatorConfig.organization}_${this.generatorConfig.workspaceName}`)),clientPrefix:()=>this.settings.exportedClientClassName||this.settings.clientClassName||this.names.project.client,packageId:()=>this.settings.packageId||this.namespaces.root}),files:bd({project:()=>this.namespaces.root,testProject:()=>`${this.namespaces.root}.Test`}),methods:bd({mockOauth:()=>"MockOAuthEndpoint",mockInferredAuth:()=>"MockInferredAuthEndpoint",getAccessTokenAsync:()=>"GetAccessTokenAsync",getAuthHeadersAsync:()=>"GetAuthHeadersAsync"}),variables:bd({client:()=>"client",response:()=>"response",httpRequest:()=>"httpRequest",sendRequest:()=>"sendRequest",responseBody:()=>"responseBody",query:()=>"_query",headers:()=>"_headers"}),parameters:bd({cancellationToken:()=>"cancellationToken",requestOptions:()=>"options",idempotentOptions:()=>"options"})};Types=bd({Arbitrary:t=>new gm.AribitraryType(t,this),HttpMethodExtensions:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HttpMethodExtensions")}),FormRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("FormRequest")}),Optional:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Optional")}),ClientOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("ClientOptions"),namespace:this.namespaces.publicCoreClasses}),RawClient:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("RawClient")}),RequestOptions:()=>this.csharp.classReference({namespace:this.namespaces.publicCoreClasses,origin:this.model.staticExplicit("RequestOptions")}),RequestOptionsInterface:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("IRequestOptions")}),JsonRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("JsonRequest")}),Version:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("Version")}),ValueConvert:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("ValueConvert")}),FileParameter:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("FileParameter"),multipartMethodName:"AddFileParameterPart",multipartMethodNameForCollection:"AddFileParameterParts",isReferenceType:!0}),Headers:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Headers")}),HeaderValue:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HeaderValue")}),RootClient:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClient),namespace:this.namespaces.root}),RootClientForSnippets:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClientForSnippets),namespace:this.namespaces.root}),BaseApiException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseApiException),namespace:this.namespaces.publicCoreClasses}),BaseException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseException),namespace:this.namespaces.publicCoreClasses}),ExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit("IExceptionInterceptor"),namespace:this.namespaces.core}),ExceptionHandler:()=>this.csharp.classReference({origin:this.model.staticExplicit("ExceptionHandler"),namespace:this.namespaces.core}),CustomExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.exceptionInterceptor),namespace:this.namespaces.core}),ProtoAnyMapper:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoAnyMapper"),namespace:this.namespaces.core}),Constants:()=>this.csharp.classReference({origin:this.model.staticExplicit("Constants"),namespace:this.namespaces.core}),EnumSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("EnumSerializer"),namespace:this.namespaces.core}),DateTimeSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("DateTimeSerializer"),namespace:this.namespaces.core}),JsonUtils:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonUtils"),namespace:this.namespaces.core}),JsonAssert:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonAssert"),namespace:this.namespaces.testUtils}),CustomPagerFactory:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Factory`),namespace:this.namespaces.core}),CustomPagerContext:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Context`),namespace:this.namespaces.core}),Environments:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.environment),namespace:this.namespaces.publicCoreClasses}),TestClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("TestClient"),namespace:this.namespaces.test}),BaseMockServerTest:()=>this.csharp.classReference({origin:this.model.staticExplicit("BaseMockServerTest"),namespace:this.namespaces.mockServerTest}),IdempotentRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("IdempotentRequestOptions"),namespace:this.namespaces.publicCoreClasses}),IdempotentRequestOptionsInterface:()=>this.csharp.classReference({origin:this.model.staticExplicit("IIdempotentRequestOptions"),namespace:this.namespaces.core}),IStringEnum:()=>this.csharp.classReference({origin:this.model.staticExplicit("IStringEnum"),namespace:this.namespaces.core}),WebSocketClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("WebSocketClient"),namespace:this.namespaces.webSocketsCore}),QueryBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("Query"),namespace:this.namespaces.webSocketsCore}),QueryStringBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder"),namespace:this.namespaces.core}),QueryStringBuilderBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder.Builder"),namespace:this.namespaces.core}),OAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("OAuthTokenProvider"),namespace:this.namespaces.core}),InferredAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("InferredAuthTokenProvider"),namespace:this.namespaces.core}),ProtoConverter:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoConverter"),namespace:this.namespaces.core}),RawGrpcClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("RawGrpcClient"),namespace:this.namespaces.core}),Extensions:()=>this.csharp.classReference({origin:this.model.staticExplicit("Extensions"),namespace:this.namespaces.core}),GrpcRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcRequestOptions"),namespace:this.namespaces.root}),GrpcChannelOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcChannelOptions"),namespace:"Grpc.Net.Client"}),StringEnum:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnum"),namespace:this.namespaces.core,generics:t?[t]:void 0}),WebSocketEvent:t=>this.csharp.classReference({origin:this.model.staticExplicit("Event"),namespace:this.namespaces.webSocketsCore,generics:[t]}),ConnectionStatus:()=>this.csharp.classReference({origin:this.model.staticExplicit("ConnectionStatus"),namespace:this.namespaces.webSocketsCore}),WebSocketConnected:()=>this.csharp.classReference({origin:this.model.staticExplicit("Connected"),namespace:this.namespaces.webSocketsCore}),WebSocketClosed:()=>this.csharp.classReference({origin:this.model.staticExplicit("Closed"),namespace:this.namespaces.webSocketsCore}),StringEnumSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnumSerializer"),namespace:this.namespaces.core,generics:[t]}),CustomPagerClass:t=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.customPager),namespace:this.namespaces.core,generics:[t]}),Pager:t=>this.csharp.classReference({origin:this.model.staticExplicit("Pager"),namespace:this.namespaces.core,generics:[t]}),OffsetPager:({requestType:t,requestOptionsType:r,responseType:i,offsetType:n,stepType:a,itemType:o})=>this.csharp.classReference({origin:this.model.staticExplicit("OffsetPager"),namespace:this.namespaces.core,generics:[t,r,i,n,a,o]}),CursorPager:({requestType:t,requestOptionsType:r,responseType:i,cursorType:n,itemType:a})=>this.csharp.classReference({origin:this.model.staticExplicit("CursorPager"),namespace:this.namespaces.core,generics:[t,r,i,n,a]}),CollectionItemSerializer:(t,r)=>this.csharp.classReference({origin:this.model.staticExplicit("CollectionItemSerializer"),namespace:this.namespaces.core,generics:[t,r]}),OneOfSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("OneOfSerializer"),namespace:this.namespaces.core,generics:[t]}),AdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("AdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0}),ReadOnlyAdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("ReadOnlyAdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0})});Primitive=bd({string:()=>new gm.String(this),boolean:()=>new gm.Boolean(this),integer:()=>new gm.Integer(this),long:()=>new gm.Long(this),uint:()=>new gm.Uint(this),ulong:()=>new gm.ULong(this),float:()=>new gm.Float(this),double:()=>new gm.Double(this),object:()=>new gm.Object(this)});Value=bd({binary:()=>new ome.Binary(this),dateOnly:()=>new ome.DateOnly(this),dateTime:()=>new ome.DateTime(this),uuid:()=>new ome.Uuid(this),stringEnum:t=>new ome.StringEnum(t,this)});Collection=bd({array:t=>new FQ.Array(t,this),listType:t=>new FQ.ListType(t,this),list:t=>new FQ.List(t,this),set:t=>new FQ.Set(t,this),map:(t,r,i)=>new FQ.Map(t,r,this,i),idictionary:(t,r,i)=>new FQ.IDictionary(t,r,this,i),keyValuePair:(t,r)=>new FQ.KeyValuePair(t,r,this)});format=bd({private:t=>`_${amu.camelCase(t)}`});initialize(){return this.initializers.implicitNamespaces}initializers=bd({implicitNamespaces:()=>{for(let t of this.namespaces.implicit)this.registry.addImplicitNamespace(t);return!0}});get System(){return this.extern.System}get NUnit(){return this.extern.NUnit}get OneOf(){return this.extern.OneOf}get Google(){return this.extern.Google}get Grpc(){return this.extern.Grpc}get WireMock(){return this.extern.WireMock}};var G5t=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get namespaces(){return this.generation.namespaces}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get registry(){return this.generation.registry}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get Grpc(){return this.generation.extern.Grpc}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}};var pmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.csharp.Literal.null():(this.context.errors.add({severity:Ur.Critical,message:"Expected non-null value, but got null"}),this.csharp.Literal.nop());if(t.value===void 0&&!t.fallbackToDefault)return this.csharp.Literal.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,fallbackToDefault:t.fallbackToDefault});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.csharp.Literal.nop():this.convertNamed({named:r,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault})}case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"unknown":return this.convertUnknown({value:t.value,fallbackToDefault:t.fallbackToDefault});default:le(t.typeReference)}}convertList({list:t,value:r,fallbackToDefault:i}){return Array.isArray(r)?this.csharp.Literal.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertLiteral({literal:t,value:r,fallbackToDefault:i}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?this.csharp.Literal.nop():this.csharp.Literal.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(n)}default:le(t)}}convertSet({set:t,value:r,fallbackToDefault:i}){return Array.isArray(r)?this.csharp.Literal.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertMap({map:t,value:r,fallbackToDefault:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ur.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),this.csharp.Literal.nop()):this.csharp.Literal.dictionary({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:t.value.type==="unknown"?this.context.dynamicTypeMapper.convert({typeReference:t.value}).asOptional():this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([n,a])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:a})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:i,fallbackToDefault:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:i,fallbackToDefault:n});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:n}):this.convertUnknown({value:r,fallbackToDefault:n});case"enum":return this.getEnumValue(t,r);case"object":return this.convertObject({object_:t,value:r,fallbackToDefault:n});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:n});default:le(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:i}){let n=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),a=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(a==null)return this.csharp.Literal.nop();let o=a.singleDiscriminatedUnionType,c=this.getBaseProperties({discriminatedUnionTypeInstance:a,singleDiscriminatedUnionType:o});switch(o.type){case"samePropertiesAsObject":{let d=this.context.resolveNamedType({typeId:o.typeId});return d==null?this.csharp.Literal.nop():this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.convertNamed({named:d,value:a.value})]})}case"singleProperty":{if(this.context.getRecord(a.value)==null)return this.csharp.Literal.nop();try{let s=["Value","Type"].includes(o.discriminantValue.name.pascalCase.safeName)?`${o.discriminantValue.name.pascalCase.safeName}Inner`:o.discriminantValue.name.pascalCase.safeName;return this.context.errors.scope(o.discriminantValue.wireValue),this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({name:s,enclosingType:n}),arguments_:[this.convert({typeReference:o.typeReference,value:o.discriminantValue.wireValue})]})]})}finally{this.context.errors.unscope()}}case"noProperties":return this.instantiateUnionWithBaseProperties({classReference:n,baseProperties:c,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({origin:a.discriminantValue,enclosingType:n}),arguments_:[]})]});default:le(o)}}getBaseProperties({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(n=>{this.context.errors.scope(n.name.wireValue);try{return{name:this.context.getPropertyName(n.name.name),assignment:this.convert(n)}}finally{this.context.errors.unscope()}})}instantiateUnionWithBaseProperties({classReference:t,arguments_:r,baseProperties:i}){let n=this.csharp.instantiateClass({classReference:t,arguments_:r,multiline:!0});return i.length===0?this.csharp.Literal.reference(n):this.csharp.Literal.reference(this.csharp.codeblock(a=>{a.write(n," "),a.pushScope();for(let o of i)a.write(o.name," = ",o.assignment,",");a.popScope(!1)}))}getEnumValue(t,r){if(typeof r!="string")return this.context.errors.add({severity:Ur.Critical,message:`Expected enum value string, got: ${typeof r}`}),this.csharp.Literal.nop();let i=t.values.find(o=>o.wireValue===r);if(i==null)return this.context.errors.add({severity:Ur.Critical,message:`An enum value named "${r}" does not exist in this context`}),this.csharp.Literal.nop();let n=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),a=n.registerField(this.model.getPropertyNameFor(i),i);return this.csharp.Literal.reference(this.csharp.enumInstantiation({reference:n,value:a}))}convertObject({object_:t,value:r,fallbackToDefault:i}){let n=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:n.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getClassName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}})})}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:i}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n==null?this.csharp.Literal.nop():n.typeLiteral}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let i of t.types)try{let n=this.convert({typeReference:i,value:r});return{valueTypeReference:i,typeLiteral:n}}catch{continue}this.context.errors.add({severity:Ur.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,fallbackToDefault:r}){return this.csharp.Literal.unknown(t)}convertPrimitive({primitive:t,value:r,as:i,fallbackToDefault:n}){switch(t){case"INTEGER":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.integer.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.integer(a)}case"LONG":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.long.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.long(a)}case"UINT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.uint.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.uint(a)}case"UINT_64":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.ulong.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.ulong(a)}case"FLOAT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.float.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.float(a)}case"DOUBLE":{let a=this.getValueAsNumber({value:r,as:i});return a==null?n?this.Primitive.double.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.double(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:r,as:i});return a==null?n?this.Primitive.boolean.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.boolean(a)}case"STRING":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"DATE":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Value.dateOnly.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.date(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Value.dateTime.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.datetime(a)}case"UUID":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"BASE_64":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}case"BIG_INTEGER":{let a=this.context.getValueAsString({value:r});return a==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(a)}default:le(t)}}getValueAsNumber({value:t,as:r}){let i=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:r}){let i=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:i})}};var _mu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){switch(t.typeReference.type){case"list":return this.Collection.list(this.convert({typeReference:t.typeReference,unboxOptionals:!0}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return this.Collection.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":{let r=this.convert({typeReference:t.typeReference.value});return t.unboxOptionals?r.asNonOptional():r.asOptional()}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return this.Collection.set(this.convert({typeReference:t.typeReference,unboxOptionals:!0}));case"unknown":return this.convertUnknown();default:le(t.typeReference)}}convertToClassReference(t){return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)})}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"object":return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.Primitive.object;case"undiscriminatedUnion":return this.OneOf.OneOf(t.types.map(r=>this.convert({typeReference:r})));default:le(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return this.Primitive.boolean;case"string":return this.Primitive.string}}convertUnknown(){return this.Primitive.object}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return this.Primitive.integer;case"UINT":return this.Primitive.uint;case"LONG":return this.Primitive.long;case"UINT_64":return this.Primitive.ulong;case"FLOAT":return this.Primitive.float;case"DOUBLE":return this.Primitive.double;case"BOOLEAN":return this.Primitive.boolean;case"STRING":return this.Primitive.string;case"DATE":return this.Value.dateOnly;case"DATE_TIME":return this.Value.dateTime;case"UUID":return this.Primitive.string;case"BASE_64":return this.Primitive.string;case"BIG_INTEGER":return this.Primitive.string;default:le(t)}}};var hmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}getFilePropertyInfo({body:t,value:r}){let i={fileFields:[],bodyPropertyFields:[]},n=this.context.getRecord(r)??{};for(let a of t.properties)switch(a.type){case"file":gl.Record.missingKey(n,a.wireValue)&&(n[a.wireValue]="[bytes]"),i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getSingleFileProperty({property:a,record:n})});break;case"fileArray":gl.Record.missingKey(n,a.wireValue)&&(n[a.wireValue]=["[bytes]"]),i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getArrayFileProperty({property:a,record:n})});break;case"bodyProperty":if(gl.Record.missingKey(n,a.name.wireValue))switch(a.typeReference.type){case"optional":break;case"primitive":{switch(a.typeReference.value.toLowerCase()){case"integer":{n[a.name.wireValue]=123;break}case"string":{n[a.name.wireValue]="[string]";break}case"boolean":{n[a.name.wireValue]=!0;break}case"double":{n[a.name.wireValue]=123.456;break}case"float":{n[a.name.wireValue]=123.456;break}case"long":{n[a.name.wireValue]=123456789;break}case"uint":{n[a.name.wireValue]=123;break}case"uint64":{n[a.name.wireValue]=12345;break}case"date":{n[a.name.wireValue]=new Date(2021,1,1);break}case"datetime":{n[a.name.wireValue]=new Date(2021,1,1,12,0,0);break}case"uuid":{n[a.name.wireValue]="123e4567-e89b-12d3-a456-426614174000";break}case"base64":{n[a.name.wireValue]="SGVsbG8gd29ybGQh";break}case"biginteger":{n[a.name.wireValue]="12345678901234567890";break}}break}default:break}i.bodyPropertyFields.push({name:this.context.getPropertyName(a.name.name),value:this.getBodyProperty({property:a,record:n})});break;default:le(a)}return i}getSingleFileProperty({property:t,record:r}){let i=this.context.getSingleFileValue({property:t,record:r});return i==null?this.csharp.Literal.nop():this.context.getFileParameterForString(i)}getArrayFileProperty({property:t,record:r}){let i=this.context.getFileArrayValues({property:t,record:r});return i==null?this.csharp.Literal.nop():this.csharp.Literal.list({valueType:this.Types.FileParameter,values:i.map(n=>this.context.getFileParameterForString(n))})}getBodyProperty({property:t,record:r}){let i=r[t.name.wireValue];return i==null?this.csharp.Literal.nop():this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var ymu=class e extends Oq{ir;dynamicTypeMapper;dynamicLiteralMapper;filePropertyMapper;generation;get namespaces(){return this.generation.namespaces}get registry(){return this.generation.registry}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get csharp(){return this.generation.csharp}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}constructor({ir:t,config:r,options:i,generation:n}){super({ir:t,config:r,options:i}),this.ir=t,this.generation=n??new ueo(t,r.workspaceName,r.customConfig!=null?r.customConfig:{},r),this.dynamicTypeMapper=new _mu({context:this}),this.dynamicLiteralMapper=new pmu({context:this}),this.filePropertyMapper=new hmu({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options,generation:this.generation})}getFileParameterForString(t){return this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.FileParameter,arguments_:[],properties:[{name:"Stream",value:this.getMemoryStreamForString(t)}],multiline:!0}))}getMemoryStreamForString(t){return this.System.IO.MemoryStream.new({arguments_:[this.csharp.invokeMethod({on:this.System.Text.Encoding_UTF8,method:"GetBytes",arguments_:[this.csharp.Literal.string(t)]})]})}getClassName(t){return t.pascalCase.safeName}getParameterName(t){return t.camelCase.safeName}getPropertyName(t){return t.pascalCase.safeName}getMethodName(t){return`${t.pascalCase.safeName}Async`}getNamespace(t,r){let i=this.getNamespaceSegments(t);return i=r!=null?[...i,r]:i,[this.namespaces.root,...i].join(".")}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentClassReferenceForEnumName(r)}getEnvironmentClassReferenceForEnumName(t){return this.csharp.classReference({name:`${this.generation.Types.Environments.name}.${this.getClassName(t)}`,namespace:this.namespaces.root})}getNamespaceSegments(t){return(this.settings.explicitNamespaces?t.allParts:t.packagePath).map(i=>i.pascalCase.safeName)}precalculate(t){this.generation.initialize(),this.System.Collections.Generic.KeyValuePair(),this.System.Collections.Generic.IEnumerable(),this.System.Collections.Generic.IAsyncEnumerable(),this.System.Collections.Generic.HashSet(),this.System.Collections.Generic.List(),this.System.Collections.Generic.Dictionary(),this.System.Threading.Tasks.Task(),Object.entries(this.ir.types).sort((r,i)=>r[0].length-i[0].length).forEach(([r,i])=>{this.dynamicTypeMapper.convertToClassReference(i)});for(let[r,i]of t.entries())if(this.csharp.classReference({origin:this.model.staticExplicit(`Example${r}`),namespace:"Usage"}),i.endpoint){let n=this.resolveEndpointLocation(i.endpoint);for(let a of n)switch(a.request.type){case"inlined":this.csharp.classReference({origin:a.request.declaration.name,namespace:this.getNamespace(a.request.declaration.fernFilepath)});break;case"body":break}}this.generation.Types.ClientOptions,this.generation.Types.RootClient,this.csharp.freezeClassReferences()}};var bmu=class extends G5t{context;constructor({context:t}){super(t.generation),this.context=t}async generateSnippet({endpoint:t,request:r,options:i}){return this.buildCodeBlock({endpoint:t,snippet:r,options:i}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map})}generateSnippetSync({endpoint:t,request:r,options:i}){return this.buildCodeBlock({endpoint:t,snippet:r,options:i}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map})}async generateSnippetAst({endpoint:t,request:r,options:i}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:i}){if(t.examples&&!t.examples?.find(o=>gl.DynamicIR.EndpointExample(r)&&o.id===r.id))throw new Error("Endpoint does not have an example that matches the snippet");let n=this.csharp.codeblock(o=>{o.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),o.newLine(),o.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),a=this.getStyle(i);switch(a){case Vz.Concise:return n;case Vz.Full:return this.buildFullCodeBlock({body:n,options:i});default:le(a)}}buildFullCodeBlock({body:t,options:r}){let i=this.getConfig(r),n=this.csharp.class_({name:i.fullStyleClassName??"Example",namespace:"Usage",access:npa.Access.Public});return n.addNamespaceReference(this.Types.RootClient.namespace),n.addMethod({name:"Do",access:npa.Access.Public,isAsync:!0,parameters:[],body:t}),n}constructClient({endpoint:t,snippet:r}){return this.csharp.codeblock(i=>{i.write("var client = "),i.writeNode(this.getRootClientConstructorInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){let i=t.response?.type==="streaming"||t.response?.type==="streamParameter",n=this.csharp.invokeMethod({on:this.csharp.codeblock("client"),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),async:!0,configureAwait:!0,multiline:!0,isAsyncEnumerable:i});return i?this.csharp.codeblock(a=>{a.write("await foreach (var item in "),a.writeNode(n),a.writeLine(")"),a.pushScope(),a.writeLine("/* consume each item */"),a.popScope()}):n}getConstructorArgs({endpoint:t,snippet:r}){let i=[];t.auth!=null&&(r.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ur.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let n=[],a=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});a.length>0&&n.push(...a),this.context.errors.scope(Po.Headers);let o=[];return this.context.ir.headers!=null&&r.headers!=null&&o.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n.length===0?[...i,...o]:[...i,...o,{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:n.map(c=>({name:c.name,assignment:c.assignment})),multiline:!0})}]}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let i=this.getBaseUrlArg({baseUrl:t,environment:r});return gl.Literal.nop(i)?[]:[{name:this.getBaseUrlOptionName(),assignment:i}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ur.Critical,message:"Cannot specify both baseUrl and environment options"}),this.csharp.Literal.nop();if(t!=null)return this.context.ir.environments?.environments.type==="multipleBaseUrls"?(this.context.errors.add({severity:Ur.Critical,message:"The C# SDK doesn't support a baseUrl when multiple URL environments are configured"}),this.csharp.Literal.nop()):this.csharp.Literal.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let i=this.context.getEnvironmentTypeReferenceFromID(r);return i==null?(this.context.errors.add({severity:Ur.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),this.csharp.Literal.nop()):this.csharp.Literal.reference(i)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.Environments,arguments_:Object.entries(r).map(([i,n])=>({name:Ff(yn(i)),assignment:this.context.dynamicLiteralMapper.convert({typeReference:{type:"primitive",value:"STRING"},value:n})})),multiline:!0})):this.csharp.Literal.nop()}return this.csharp.Literal.nop()}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArg({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:le(t)}}addError(t){this.context.errors.add({severity:Ur.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ur.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getParameterName(t.username),assignment:this.csharp.Literal.string(r.username)},{name:this.context.getParameterName(t.password),assignment:this.csharp.Literal.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.token),assignment:this.csharp.Literal.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.header.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value,fallbackToDefault:t.header.name.wireValue})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.clientId),assignment:this.csharp.Literal.string(r.clientId)},{name:this.context.getParameterName(t.clientSecret),assignment:this.csharp.Literal.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let i=[];if(t.parameters!=null)for(let n of t.parameters){let a=n.name.wireValue,o=r.values?.[a];i.push({name:this.context.getParameterName(n.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:n.typeReference,value:o,fallbackToDefault:a})})}else this.context.errors.add({severity:Ur.Critical,message:"Inferred auth parameters are not defined in the IR. Please ensure you're using IR version 62.3.0 or later."});return i}getConstructorHeaderArgs({headers:t,values:r}){let i=[];for(let n of t){let a=this.getConstructorHeaderArg({header:n,value:r.value});a!=null&&i.push({name:this.context.getParameterName(n.name.name),assignment:a})}return i}getConstructorHeaderArg({header:t,value:r}){let i=this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:r,fallbackToDefault:t.name.wireValue});if(!gl.Literal.nop(i))return i}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:le(t.request)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(Po.PathParameters);let n=[],a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let o=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})||i.push(...n.map(c=>c.value)),i.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})?n:[],filePropertyInfo:o})),i}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:i,filePropertyInfo:n}){this.context.errors.scope(Po.QueryParameters);let o=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicLiteralMapper.convert(u)}));this.context.errors.unscope(),this.context.errors.scope(Po.Headers);let d=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicLiteralMapper.convert({...u,fallbackToDefault:u.name.wireValue})}));this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let s=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];return this.context.errors.unscope(),this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:[...i,...o,...d,...s]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:i});default:le(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let i=[],n=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicLiteralMapper.convert({...a,fallbackToDefault:a.name.wireValue})});return i}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:le(t)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(Po.PathParameters);let n=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return n.length>0&&i.push(...this.getPathParameters({namedParameters:n,snippet:r}).map(a=>a.value)),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody),t.body!=null&&i.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),i}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return t.value.type==="optional"&&r==null?this.csharp.Literal.null():this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:le(t)}}getBytesBodyRequestArg({value:t}){let r=this.context.getValueAsString({value:t});return r==null&&(this.context.errors.add({severity:Ur.Critical,message:"The bytes request body must be provided in string format"}),r="[bytes]"),this.csharp.Literal.reference(this.context.getMemoryStreamForString(r))}getRootClientConstructorInvocation(t){return this.csharp.instantiateClass({classReference:this.Types.RootClient,arguments_:t,forceUseConstructor:!0,multiline:!0})}getPathParameters({namedParameters:t,snippet:r}){let i=[],n=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicLiteralMapper.convert({...a,fallbackToDefault:a.name.wireValue})});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getClassName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getBaseUrlOptionName(){return this.context.ir.environments?.environments.type==="multipleBaseUrls"?"Environment":"BaseUrl"}getStyle(t){return t.style??this.context.options.style??Vz.Full}getConfig(t){return t.config??this.context.options.config??{}}};var seo=class extends gq{constructor({ir:t,config:r,options:i={}}){super(new ymu({ir:t,config:r,options:i}))}precalculate(t){this.context.precalculate(t)}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new bmu({context:t})}};var opa=require("fs/promises"),cqh=ue(require("path"),1);function QQ(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:_fB(e.auth)}}function _fB(e){if(e!=null)return e}function sqh(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,hfB(r)]).filter(([t,r])=>r!=null))}function hfB(e){let t=e.location.method;if(t!=="HEAD")return{...e,location:{...e.location,method:t},examples:e.examples!=null?yfB(e.examples):void 0,auth:gfB(e.auth)}}function yfB(e){return e.map(t=>bfB(t)).filter(t=>t!=null)}function bfB(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:vfB(e.auth)}}function vfB(e){if(e!=null)return e}function gfB(e){if(e!=null)return e}function UQ(e){return{...e,endpoints:sqh(e.endpoints)}}var OfB=`
|
|
1308
1308
|
<Project Sdk="Microsoft.NET.Sdk">
|
|
1309
1309
|
<PropertyGroup>
|
|
1310
1310
|
<TargetFramework>net8.0</TargetFramework>
|
|
@@ -1938,7 +1938,7 @@ A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
|
1938
1938
|
Learn more about project structure:
|
|
1939
1939
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
1940
1940
|
Learn more about project structure:
|
|
1941
|
-
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Qt.V1.SlugGenerator.init(Qt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Qt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return sT(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Qt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??sM(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);let a=5,o=[];for(let c=0;c<t.versions.length;c+=a){let d=t.versions.slice(c,c+a),s=await Promise.all(d.map((u,f)=>this.toVersionNode(u,r,c+f===0)));o.push(...s)}return{id:i,type:"versioned",children:o}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??sM(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:le(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Qt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Qt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:dH.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??sM(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Qt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?SC5(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),o=(await Promise.all(r.map(d=>this.toNavigationChild({prefix:n,item:d,parentSlug:i})))).filter(d=>d!=null),c=[];return o.forEach(d=>{if(d.type==="apiReference"){c.push(d);return}if(d.type==="section"&&!d.collapsed){c.push(d);return}let s=c.length>0?c[c.length-1]:void 0,u;s?.type==="sidebarGroup"?u=s:(u={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},c.push(u)),u.children.push(d)}),{type:"sidebarRoot",id:n,children:c}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??sM(t.title)}`),a=i.apply({urlSlug:t.slug??sM(t.title),skipUrlSlug:t.skipUrlSlug}),c=(await Promise.all(t.layout.map(d=>this.toVariantChild(d,n,a)))).filter(d=>d!=null);return{type:"variant",id:n,variantId:Qt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:c,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return sT(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i),pythonDocsSection:async n=>this.handlePythonDocsSection(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return sT(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n),pythonDocsSection:async o=>this.handlePythonDocsSection(o,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=GAE(t.snippetsConfiguration),o,c,d,s,u=this.parsedDocsConfig.experimental?.openapiParserV3,f=u==null||u;if(f)try{d=this.getOpenApiWorkspaceForApiSection(t),o=await d.getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch(O){s=O}let p;if(t.tagDescriptionPages&&f)try{let m=await(d??this.getOpenApiWorkspaceForApiSection(t)).getOpenAPIIr({context:this.taskContext,loadAiExamples:!0});m.tags.tagsById&&(p=Object.fromEntries(Object.entries(m.tags.tagsById).filter(([g,A])=>A.description&&A.description.trim().length>0).map(([g,A])=>[yn(g),{id:String(A.id),description:A.description}])))}catch(O){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(O))}if(o==null){if(this.apiWorkspaces.length===0&&s!=null)throw s;c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),o=iE({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new eE(this.taskContext,c)})}this.docsWorkspace.config.settings?.substituteEnvVars&&(o=yz(o,{onError:O=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${O}`)},{substituteAsEmpty:!1}));let _=t.apiName??c?.workspaceName??d?.workspaceName,h=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:_,workspace:c}),y=fFo({ir:o,apiDefinitionId:h,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),b=new eXs(t,y,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,p),v=b.getTagDescriptionContent();for(let[O,m]of v.entries()){let g=O.split("/").pop()||O,A=je.of(g),j=m;this.docsWorkspace.config.settings?.substituteEnvVars&&(j=yz(m,{onError:S=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${S}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[A]=j,this.parsedDocsConfig.pages[A]=j}return b.get()}async toChangelogNode(t,r,i){return new a2n(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Qt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}handlePythonDocsSection(t,r){return this.pythonDocsSectionHandler==null?null:this.pythonDocsSectionHandler(t,r,{addPage:(i,n)=>{this.parsedDocsConfig.pages[je.of(i)]=n},generateId:i=>this.#e.get(i)})}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Qt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??sM(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Qt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??sM(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden,_=(await Promise.all(r.contents.map(h=>this.toNavigationChild({prefix:d,item:h,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a})))).filter(h=>h!=null);if(c==null){let h=_.find(y=>y.type==="apiReference"&&y.hideTitle===!0&&y.overviewPageId!=null);h!=null&&(c=h.overviewPageId)}return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:_,authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return sT(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new a2n(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Qt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??sM(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??sM(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):dH.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ws),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:dH.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return sT(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:dH.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function EC5(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${LJ(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function SC5(e){switch(e){case"beta":return Qt.V1.NavigationV1Availability.Beta;case"deprecated":return Qt.V1.NavigationV1Availability.Deprecated;case"ga":return Qt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Qt.V1.NavigationV1Availability.Stable;default:le(e)}}function I_p(e,t,r){let i=e.title??"Python Reference",n=e.slug??"python-docs",a=t.apply({urlSlug:n}),o=`__python-docs-placeholder-${n}__.mdx`,c=Qt.PageId(o),d=`---
|
|
1941
|
+
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Qt.V1.SlugGenerator.init(Qt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Qt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return sT(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Qt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??sM(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);let a=5,o=[];for(let c=0;c<t.versions.length;c+=a){let d=t.versions.slice(c,c+a),s=await Promise.all(d.map((u,f)=>this.toVersionNode(u,r,c+f===0)));o.push(...s)}return{id:i,type:"versioned",children:o}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??sM(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:le(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Qt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Qt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:dH.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??sM(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Qt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?SC5(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),o=(await Promise.all(r.map(d=>this.toNavigationChild({prefix:n,item:d,parentSlug:i})))).filter(d=>d!=null),c=[];return o.forEach(d=>{if(d.type==="apiReference"){c.push(d);return}if(d.type==="section"&&!d.collapsed){c.push(d);return}let s=c.length>0?c[c.length-1]:void 0,u;s?.type==="sidebarGroup"?u=s:(u={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},c.push(u)),u.children.push(d)}),{type:"sidebarRoot",id:n,children:c}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??sM(t.title)}`),a=i.apply({urlSlug:t.slug??sM(t.title),skipUrlSlug:t.skipUrlSlug}),c=(await Promise.all(t.layout.map(d=>this.toVariantChild(d,n,a)))).filter(d=>d!=null);return{type:"variant",id:n,variantId:Qt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:c,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return sT(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i),pythonDocsSection:async n=>this.handlePythonDocsSection(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return sT(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n),pythonDocsSection:async o=>this.handlePythonDocsSection(o,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=GAE(t.snippetsConfiguration),o,c,d,s,u=this.parsedDocsConfig.experimental?.openapiParserV3,f=u==null||u;if(f)try{d=this.getOpenApiWorkspaceForApiSection(t),o=await d.getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch(O){s=O}let p;if(t.tagDescriptionPages&&f)try{let m=await(d??this.getOpenApiWorkspaceForApiSection(t)).getOpenAPIIr({context:this.taskContext,loadAiExamples:!0});m.tags.tagsById&&(p=Object.fromEntries(Object.entries(m.tags.tagsById).filter(([g,A])=>A.description&&A.description.trim().length>0).map(([g,A])=>[yn(g),{id:String(A.id),description:A.description}])))}catch(O){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(O))}if(o==null){if(this.apiWorkspaces.length===0&&s!=null)throw s;c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),o=iE({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new eE(this.taskContext,c)})}else if(Object.keys(a).length>0)try{c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0})}catch(O){this.taskContext.logger.debug(`Could not load workspace for dynamic snippets: ${O}. Dynamic snippets may not be available.`)}this.docsWorkspace.config.settings?.substituteEnvVars&&(o=yz(o,{onError:O=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${O}`)},{substituteAsEmpty:!1}));let _=t.apiName??c?.workspaceName??d?.workspaceName,h=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:_,workspace:c}),y=fFo({ir:o,apiDefinitionId:h,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),b=new eXs(t,y,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,p),v=b.getTagDescriptionContent();for(let[O,m]of v.entries()){let g=O.split("/").pop()||O,A=je.of(g),j=m;this.docsWorkspace.config.settings?.substituteEnvVars&&(j=yz(m,{onError:S=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${S}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[A]=j,this.parsedDocsConfig.pages[A]=j}return b.get()}async toChangelogNode(t,r,i){return new a2n(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Qt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}handlePythonDocsSection(t,r){return this.pythonDocsSectionHandler==null?null:this.pythonDocsSectionHandler(t,r,{addPage:(i,n)=>{this.parsedDocsConfig.pages[je.of(i)]=n},generateId:i=>this.#e.get(i)})}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Qt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??sM(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Qt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??sM(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden,_=(await Promise.all(r.contents.map(h=>this.toNavigationChild({prefix:d,item:h,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a})))).filter(h=>h!=null);if(c==null){let h=_.find(y=>y.type==="apiReference"&&y.hideTitle===!0&&y.overviewPageId!=null);h!=null&&(c=h.overviewPageId)}return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:_,authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return sT(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new a2n(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Qt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??sM(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??sM(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):dH.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ws),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:dH.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return sT(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:dH.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function EC5(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${LJ(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function SC5(e){switch(e){case"beta":return Qt.V1.NavigationV1Availability.Beta;case"deprecated":return Qt.V1.NavigationV1Availability.Deprecated;case"ga":return Qt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Qt.V1.NavigationV1Availability.Stable;default:le(e)}}function I_p(e,t,r){let i=e.title??"Python Reference",n=e.slug??"python-docs",a=t.apply({urlSlug:n}),o=`__python-docs-placeholder-${n}__.mdx`,c=Qt.PageId(o),d=`---
|
|
1942
1942
|
title: ${i}
|
|
1943
1943
|
---
|
|
1944
1944
|
|
|
@@ -2048,7 +2048,7 @@ ${l1E.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&cvp(th
|
|
|
2048
2048
|
`+w2n.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?w2n.default.cyan(g1E(t,this.opt.mask)):w2n.default.italic(w2n.default.dim("[hidden]")):this.opt.mask?g1E(t,this.opt.mask):w2n.default.italic(w2n.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 ktc=ue(PF(),1);var gTE=ue(xvp(),1),Xtc=require("child_process"),k3a=require("fs"),Ytc=ue(require("path"),1),OTE=ue(require("os"),1),mTE=require("crypto"),Mgp=ue(bTE(),1);var Ktc=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var gQo=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var $tc=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var Jtc=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function Ztc(e="",t,r){let i=new Dgp(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function vTE(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function X$5(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var Dgp=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=X$5(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??OTE.default.tmpdir(),r=(0,mTE.randomUUID)(),i=vTE(this.fileOptions.prefix),n=vTE(this.fileOptions.postfix),a=`${i}${r}${n}`,o=Ytc.default.resolve(t,a),c=Ytc.default.resolve(t)+Ytc.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,k3a.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new Ktc(t)}}readTemporaryFile(){try{let t=(0,k3a.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,gTE.detect)(t)??"utf8";Mgp.default.encodingExists(r)||(r="utf8"),this.text=Mgp.default.decode(t,r)}}catch(t){throw new $tc(t)}}removeTemporaryFile(){try{(0,k3a.unlinkSync)(this.tempFile)}catch(t){throw new Jtc(t)}}launchEditor(){try{let t=(0,Xtc.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new gQo(t)}}launchEditorAsync(t){try{(0,Xtc.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new gQo(r)}}};var ATE=ue(E0e(),1);var OQo=class extends jF{_run(t){this.done=t,this.editorResult=new ATE.Subject;let r=Q8(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?ktc.default.dim("Received"):ktc.default.dim("Press <enter> to launch your preferred editor."),t&&(r=ktc.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),Ztc(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 STE=require("stream");var wTE=ue(require("readline"),1),ETE=ue(jTE(),1),D2n=class{constructor(t){this.rl||=wTE.default.createInterface(k$5(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 k$5(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new ETE.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var mQo=class extends D2n{constructor(t={}){super(t),this.log=new STE.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return nQo(this.rl,this.bottomBar.split(`
|
|
2049
2049
|
`).length),this}updateBottomBar(t){return nQo(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+`
|
|
2050
2050
|
`}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&&mtc(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lA=ue(E0e(),1),BTE=ue(RFo(),1);var erc=ue(E0e(),1),MTE=ue(RFo(),1),trc=function(e,t,r){return typeof e[t]!="function"?(0,erc.of)(e):(0,erc.from)((0,MTE.default)(e[t])(r).then(i=>(e[t]=i,e)))};var DTE={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},eWa=class extends D2n{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,lA.from)(t):(0,lA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,lA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,lA.from)([t]),this.process=i.pipe((0,lA.concatMap)(this.processQuestion.bind(this)),(0,lA.publish)()),this.process.connect(),this.process.pipe((0,lA.reduce)((n,a)=>(DTE.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,lA.defer)(()=>(0,lA.of)(t).pipe((0,lA.concatMap)(this.setDefaultType.bind(this)),(0,lA.concatMap)(this.filterIfRunnable.bind(this)),(0,lA.concatMap)(()=>trc(t,"message",this.answers)),(0,lA.concatMap)(()=>trc(t,"default",this.answers)),(0,lA.concatMap)(()=>trc(t,"choices",this.answers)),(0,lA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,lA.defer)(()=>(0,lA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,lA.defer)(()=>(0,lA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&DTE.get(this.answers,t.name)!==void 0)return lA.EMPTY;if(t.when===!1)return lA.EMPTY;if(typeof t.when!="function")return(0,lA.of)(t);let{answers:r}=this;return(0,lA.defer)(()=>(0,lA.from)((0,BTE.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,lA.filter)(i=>i!=null)))}};function ITE(e){let t=function(r,i){let n;try{n=new eWa(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",oQo),this.registerPrompt("input",j2n),this.registerPrompt("number",uQo),this.registerPrompt("confirm",sQo),this.registerPrompt("rawlist",cQo),this.registerPrompt("expand",lQo),this.registerPrompt("checkbox",fQo),this.registerPrompt("password",dQo),this.registerPrompt("editor",OQo)},t.restoreDefaultPrompts(),t}var Igp=ITE();function tJ5(e,t){Igp.registerPrompt(e,t)}function rJ5(){Igp.restoreDefaultPrompts()}var iJ5={prompt:Igp,ui:{BottomBar:mQo,Prompt:eWa},createPromptModule:ITE,registerPrompt:tJ5,restoreDefaultPrompts:rJ5,Separator:Oge},rrc=iJ5;var tWa=require("path");function qTE(){let e=nJ5();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function nJ5(e=process.argv[1]?(0,tWa.dirname)(process.argv[1]):process.cwd(),t=tWa.sep==="\\"){let r=t?CTE(e):e;return i=>{if(!i)return;let n=t?CTE(i):i,{dir:a,base:o,ext:c}=tWa.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function CTE(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Cgp=e=>{if("flags"in e){let t=TTE(e.flags),r=RTE(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,zTE(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,aJ5(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function aJ5(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 TTE=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,B2n(r)]).filter(([,t])=>t!==void 0)),RTE=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?zTE(i):void 0]}))};var B2n=e=>e===void 0?void 0:e.variant??e.enabled,zTE=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var irc="0123456789abcdef",nrc=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=irc.charAt(this.bytes[r]>>>4),t+=irc.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+=irc.charAt(this.bytes[r]>>>4),t+=irc.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},qgp=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??oJ5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return nrc.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,nrc.ofInner(t)}},oJ5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),NTE,VQi=()=>uJ5().toString(),uJ5=()=>(NTE||(NTE=new qgp)).generate();var sJ5=["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"],FTE=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return sJ5.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var Age=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var lJ5=Array.isArray,QTE=Object.prototype,hL2=QTE.hasOwnProperty,Tgp=QTE.toString,UTE=lJ5||function(e){return Tgp.call(e)==="[object Array]"};var rWa=e=>e===void 0,AQo=e=>Tgp.call(e)=="[object String]",LTE=e=>AQo(e)&&e.trim().length===0;var VTE=e=>Tgp.call(e)=="[object Number]";var Rgp=e=>e instanceof Error;function fJ5(e,t){try{return e instanceof t}catch{return!1}}function PQo(e){return e===null||typeof e!="object"}function I2n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function WTE(e){return I2n(e,"ErrorEvent")}function arc(e){return!rWa(Event)&&fJ5(e,Event)}function xTE(e){return I2n(e,"Object")}function jQo(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),VTE(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),jQo(n||r,t,r,i))}var dJ5=864e5,orc=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=jQo(t.bucketSize,0,100,t._logger),this._refillRate=jQo(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=jQo(t.refillInterval,0,dJ5,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var urc=class{add(t){let r=VQi();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 pJ5(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var GTE=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>GTE(`${e} ${a}`,t,r)}},_J5=e=>e();function HTE(e,t=_J5){return GTE(e,t,pJ5())}var nWa="Mobile",crc="iOS",iWa="Android",KTE="Tablet",SL2=iWa+" "+KTE;var hJ5="Apple",ML2=hJ5+" Watch",$TE="Safari",lrc="BlackBerry",JTE="Samsung",yJ5=JTE+"Browser",bJ5=JTE+" Internet",frc="Chrome",vJ5=frc+" OS",gJ5=frc+" "+crc,YTE="Internet Explorer",OJ5=YTE+" "+nWa,Ngp="Opera",DL2=Ngp+" Mini",XTE="Edge",mJ5="Microsoft "+XTE,Fgp="Firefox",AJ5=Fgp+" "+crc,Qgp="Nintendo",Ugp="PlayStation",src="Xbox",PJ5=iWa+" "+nWa,jJ5=nWa+" "+$TE,wQo="Windows",wJ5=wQo+" Phone";var ZTE="Generic",BL2=ZTE+" "+nWa.toLowerCase(),IL2=ZTE+" "+KTE.toLowerCase(),EJ5="Konqueror",$J="(\\d+(\\.\\d+)?)",zgp=new RegExp("Version/"+$J),CL2=new RegExp(src,"i"),qL2=new RegExp(Ugp+" \\w+","i"),TL2=new RegExp(Qgp+" \\w+","i"),SJ5=new RegExp(lrc+"|PlayBook|BB10","i"),MJ5={"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 RL2={[OJ5]:[new RegExp("rv:"+$J)],[mJ5]:[new RegExp(XTE+"?\\/"+$J)],[frc]:[new RegExp("("+frc+"|CrMo)\\/"+$J)],[gJ5]:[new RegExp("CriOS\\/"+$J)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$J)],[$TE]:[zgp],[jJ5]:[zgp],[Ngp]:[new RegExp("("+Ngp+"|OPR)\\/"+$J)],[Fgp]:[new RegExp(Fgp+"\\/"+$J)],[AJ5]:[new RegExp("FxiOS\\/"+$J)],[EJ5]:[new RegExp("Konqueror[:/]?"+$J,"i")],[lrc]:[new RegExp(lrc+" "+$J),zgp],[PJ5]:[new RegExp("android\\s"+$J,"i")],[bJ5]:[new RegExp(yJ5+"\\/"+$J)],[YTE]:[new RegExp("(rv:|MSIE )"+$J)],Mozilla:[new RegExp("rv:"+$J)]};var zL2=[[new RegExp(src+"; "+src+" (.*?)[);]","i"),e=>[src,e&&e[1]||""]],[new RegExp(Qgp,"i"),[Qgp,""]],[new RegExp(Ugp,"i"),[Ugp,""]],[SJ5,[lrc,""]],[new RegExp(wQo,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[wJ5,""];if(new RegExp(nWa).test(t)&&!/IEMobile\b/.test(t))return[wQo+" "+nWa,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=MJ5[i]||"";return/arm/i.test(t)&&(n="RT"),[wQo,n]}return[wQo,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[crc,t.join(".")]}return[crc,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=rWa(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+iWa+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+iWa+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[iWa,t.join(".")]}return[iWa,""]}],[/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/,[vJ5,""]],[/Linux|debian/i,["Linux",""]]];var kTE="utf8";function eRE(e,t){if(!e||typeof e!="string"||DJ5(e))throw new Error(t)}function DJ5(e){return e.trim().length===0}function tRE(e){return e?.replace(/\/+$/,"")}async function rRE(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function drc(){return new Date().toISOString()}function C2n(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var iRE=e=>e instanceof Error;function Lgp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var prc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};function nRE(){return"CompressionStream"in globalThis}async function Vgp(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var aWa=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()}},EQo=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function aRE(e){if(e instanceof aWa){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 Wgp(e){return typeof e=="object"&&(e instanceof aWa||e instanceof EQo)}function oRE(e){return typeof e=="object"&&e instanceof aWa&&e.status===413}var SQo=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new urc,this._events=new prc,this._isInitialized=!1,eRE(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=tRE(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:Wgp},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=HTE("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!nRE()||(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(Age.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Age.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Age.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>Cgp(f)).catch(f=>{this._events.emit("error",f)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=B2n(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId,evaluatedAt:c.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let d=await this.getFlags(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(Age.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(Age.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(Age.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(Age.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(Age.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=C2n(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:drc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await Vgp(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:drc(),uuid:i?.uuid?i.uuid:VQi()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await aRE(t)})}async flush(){let t=Lgp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Lgp([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(Age.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(_=>_.message),o=()=>{let h=(this.getPersistedProperty(Age.Queue)||[]).slice(n.length);this.setPersistedProperty(Age.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:drc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await Vgp(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>oRE(_)?!1:Wgp(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(oRE(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof EQo||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,kTE)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await rRE(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new EQo(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new aWa(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(Age.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Wgp(n))throw n;await aRE(n)}};return Promise.race([new Promise((n,a)=>{C2n(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var Pge={};$t(Pge,{DOMExceptionCoercer:()=>Ggp,ErrorCoercer:()=>Hgp,ErrorEventCoercer:()=>Kgp,ErrorPropertiesBuilder:()=>xgp,EventCoercer:()=>Ygp,ObjectCoercer:()=>Jgp,PrimitiveCoercer:()=>Xgp,PromiseRejectionEventCoercer:()=>Zgp,ReduceableCache:()=>kgp,StringCoercer:()=>$gp,chromeStackLineParser:()=>cRE,createStackParser:()=>WJ5,geckoStackLineParser:()=>fRE,nodeStackLineParser:()=>hRE,opera10StackLineParser:()=>dRE,opera11StackLineParser:()=>pRE,reverseAndStripFrames:()=>vRE,winjsStackLineParser:()=>lRE});var _rc,uRE,hrc;function sRE(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return hrc&&r.length===uRE||(uRE=r.length,hrc=r.reduce((i,n)=>{_rc||(_rc={});let a=_rc[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,_rc[n]=[s,u];break}}}return i},{})),hrc}var BJ5=4,xgp=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&UTE(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:sRE(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=BJ5){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var L8="?";function WQi(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?L8:r,in_app:!0};return rWa(i)||(a.lineno=i),rWa(n)||(a.colno=n),a}var yrc=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:L8,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var IJ5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,CJ5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,qJ5=/\((\S*)(?::(\d+))(?::(\d+))\)/,cRE=(e,t)=>{let r=IJ5.exec(e);if(r){let[,n,a,o]=r;return WQi(t,n,L8,+a,+o)}let i=CJ5.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=qJ5.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=yrc(i[1]||L8,i[2]);return WQi(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var TJ5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,lRE=(e,t)=>{let r=TJ5.exec(e);return r?WQi(t,r[2],r[1]||L8,+r[3],r[4]?+r[4]:void 0):void 0};var RJ5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zJ5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,fRE=(e,t)=>{let r=RJ5.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=zJ5.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||L8;return[a,n]=yrc(a,n),WQi(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var NJ5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,dRE=(e,t)=>{let r=NJ5.exec(e);return r?WQi(t,r[2],r[3]||L8,+r[1]):void 0},FJ5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,pRE=(e,t)=>{let r=FJ5.exec(e);return r?WQi(t,r[5],r[3]||r[4]||L8,+r[1],+r[2]):void 0};var QJ5=/^\s*[-]{4,}$/,UJ5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,hRE=(e,t)=>{let r=e.match(UJ5);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||L8,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:_RE(r[3]),colno:_RE(r[4]),in_app:LJ5(d||"",s),platform:t}}if(e.match(QJ5))return{filename:e,platform:t}};function LJ5(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 _RE(e){return parseInt(e||"",10)||void 0}var yRE=/\(error: (.*)\)/,bRE=50;function vRE(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,bRE).map(r=>({...r,filename:r.filename||VJ5(t).filename,function:r.function||L8}))}function VJ5(e){return e[e.length-1]||{}}function WJ5(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
2051
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=yRE.test(c)?c.replace(yRE,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=bRE)break}}return vRE(n)}}var Ggp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=AQo(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return I2n(t,"DOMException")}isDOMError(t){return I2n(t,"DOMError")}};var Hgp=class{match(t){return Rgp(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var Kgp=class{constructor(){}match(t){return WTE(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var xJ5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$gp=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(xJ5);return n&&(r=n[1],i=n[2]),[r,i]}};var gRE=["fatal","error","warning","log","info","debug"];function brc(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Jgp=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return arc(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=brc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return AQo(t)&&!LTE(t)&&gRE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(iRE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Ygp=class{match(t){return arc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${brc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Xgp=class{match(t){return PQo(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Zgp=class{match(t){return I2n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return PQo(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(PQo(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var kgp=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 ARE=require("fs"),PRE=require("readline"),vrc=new Pge.ReduceableCache(25),jRE=new Pge.ReduceableCache(20),eOp=7,GJ5=1e3,HJ5=1e4;async function wRE(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||YJ5(o)||XJ5(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(jRE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=kJ5(a);if(o.every(d=>ZJ5(n,d)))continue;let c=eY5(vrc,n,{});i.push(KJ5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&$J5(e,vrc),vrc.reduce(),e}function KJ5(e,t,r){return new Promise(i=>{let n=(0,ARE.createReadStream)(e),a=(0,PRE.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){jRE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=tY5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function $J5(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;JJ5(r.lineno,r,i)}}function JJ5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=ERE(e);n<e;n++){let a=r[n];if(a===void 0)return void ORE(t);t.pre_context.push(a)}if(r[e]===void 0)return void ORE(t);t.context_line=r[e];let i=SRE(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function ORE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function YJ5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function XJ5(e){return e.lineno!==void 0&&e.lineno>HJ5||e.colno!==void 0&&e.colno>GJ5}function ZJ5(e,t){let r=vrc.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function kJ5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=mRE(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+eOp:(n.push(i),i=mRE(a)),t++}return n}function mRE(e){return[ERE(e),SRE(e)]}function ERE(e){return Math.max(1,e-eOp)}function SRE(e){return e+eOp}function eY5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function tY5(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function rY5(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function MRE(e,t){globalThis.process?.on("uncaughtException",rY5(e,t))}function DRE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var iY5=2e3,F7i=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new orc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||VQi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(MRE(this.onException.bind(this),this.onFatalError.bind(this)),DRE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(iY5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var BRE="5.17.4";async function IRE(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var nY5=6e4,aY5=1152921504606847e3,oY5=["is_not"],oWa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},F0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xQi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},grc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof xQi||d instanceof F0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof xQi||p instanceof F0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new F0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new F0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new F0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new F0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new F0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new F0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new F0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new F0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new F0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof xQi)throw u;if(u instanceof F0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new F0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?zRE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):RRE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await CRE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await CRE(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(nY5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof oWa&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=C2n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function CRE(e,t,r=""){let i=await IRE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/aY5}function RRE(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new F0("Operator is_not_set is not supported")}else throw new F0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!oY5.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return qRE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return qRE(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new F0("Date operations cannot be performed on boolean values");let s=sY5(String(n));if(s==null&&(s=TRE(n)),s==null)throw new F0(`Invalid date: ${n}`);let u=TRE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new F0(`Unknown operator: ${a}`)}}function uY5(e,t){if(!(e in t))throw new xQi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function zRE(e,t,r,i=!1){let n=String(e.value);uY5(n,r);let a=r[n];return NRE(a,t,r,i)}function NRE(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=NRE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof xQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=zRE(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=RRE(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof xQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("can't match cohort without a given cohort property value");return n==="AND"}function qRE(e){try{return new RegExp(e),!0}catch{return!1}}function TRE(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 F0(`${e} is in an invalid date format`)}throw new F0(`The date provided ${e} must be a string, number, or date object`)}function sY5(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Orc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var cY5=100,FRE=3e4,lY5=5e4,mrc=class extends SQo{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Orc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,cY5):FRE,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new grc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new F7i(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||lY5}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 BRE}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=FRE){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=B2n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof xQi||y instanceof F0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=C2n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(xTE(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(F7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(F7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=VQi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&FTE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var QRE=require("async_hooks"),Arc=class{constructor(){this.storage=new QRE.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var URE="posthog-node";function fY5(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[tOp.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var tOp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=URE,this.name=URE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(fY5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};F7i.errorPropertiesBuilder=new Pge.ErrorPropertiesBuilder([new Pge.EventCoercer,new Pge.ErrorCoercer,new Pge.ObjectCoercer,new Pge.StringCoercer,new Pge.PrimitiveCoercer],Pge.createStackParser("node:javascript",Pge.nodeStackLineParser),[qTE(),wRE]);var uWa=class extends mrc{getLibraryId(){return"posthog-node"}initializeContext(){return new Arc}};var Prc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new uWa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.54.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var MQo=class{async sendEvent(){}async identify(){}async flush(){}};var sWa=require("fs/promises"),LRE=require("os"),VRE=require("path");var dY5="id",pY5=".fern",DQo=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new uWa(r),this.userId=t==null?void 0:h1c(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.54.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await OV({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=ut(gr.of((0,LRE.homedir)()),je.of(pY5),je.of(dY5));await ri(t)||(await(0,sWa.mkdir)((0,VRE.dirname)(t),{recursive:!0}),await(0,sWa.writeFile)(t,JOe())),this.persistedDistinctId=(await(0,sWa.readFile)(t)).toString()}return this.persistedDistinctId}};var rOp;async function cWa(){return rOp==null&&(rOp=await _Y5()),rOp}async function _Y5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new MQo;let r=await M$o();return r!=null?new DQo({token:r,posthogApiKey:e}):await Saa()!=null?new Prc({posthogApiKey:e}):new DQo({token:void 0,posthogApiKey:e})}catch{return new MQo}}var BQo=ue(require("process"),1);var GRE=ue(Azc(),1),HRE=ue(xRE(),1);function M4(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=EWt(e),e.length===0))return 0;e=e.replace((0,HRE.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(GRE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function jrc(e){let t=0;for(let r of e.split(`
|
|
2051
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=yRE.test(c)?c.replace(yRE,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=bRE)break}}return vRE(n)}}var Ggp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=AQo(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return I2n(t,"DOMException")}isDOMError(t){return I2n(t,"DOMError")}};var Hgp=class{match(t){return Rgp(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var Kgp=class{constructor(){}match(t){return WTE(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var xJ5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$gp=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(xJ5);return n&&(r=n[1],i=n[2]),[r,i]}};var gRE=["fatal","error","warning","log","info","debug"];function brc(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Jgp=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return arc(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=brc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return AQo(t)&&!LTE(t)&&gRE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(iRE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Ygp=class{match(t){return arc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${brc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Xgp=class{match(t){return PQo(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Zgp=class{match(t){return I2n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return PQo(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(PQo(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var kgp=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 ARE=require("fs"),PRE=require("readline"),vrc=new Pge.ReduceableCache(25),jRE=new Pge.ReduceableCache(20),eOp=7,GJ5=1e3,HJ5=1e4;async function wRE(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||YJ5(o)||XJ5(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(jRE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=kJ5(a);if(o.every(d=>ZJ5(n,d)))continue;let c=eY5(vrc,n,{});i.push(KJ5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&$J5(e,vrc),vrc.reduce(),e}function KJ5(e,t,r){return new Promise(i=>{let n=(0,ARE.createReadStream)(e),a=(0,PRE.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){jRE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=tY5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function $J5(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;JJ5(r.lineno,r,i)}}function JJ5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=ERE(e);n<e;n++){let a=r[n];if(a===void 0)return void ORE(t);t.pre_context.push(a)}if(r[e]===void 0)return void ORE(t);t.context_line=r[e];let i=SRE(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function ORE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function YJ5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function XJ5(e){return e.lineno!==void 0&&e.lineno>HJ5||e.colno!==void 0&&e.colno>GJ5}function ZJ5(e,t){let r=vrc.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function kJ5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=mRE(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+eOp:(n.push(i),i=mRE(a)),t++}return n}function mRE(e){return[ERE(e),SRE(e)]}function ERE(e){return Math.max(1,e-eOp)}function SRE(e){return e+eOp}function eY5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function tY5(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function rY5(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function MRE(e,t){globalThis.process?.on("uncaughtException",rY5(e,t))}function DRE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var iY5=2e3,F7i=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new orc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||VQi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(MRE(this.onException.bind(this),this.onFatalError.bind(this)),DRE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(iY5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var BRE="5.17.4";async function IRE(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var nY5=6e4,aY5=1152921504606847e3,oY5=["is_not"],oWa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},F0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xQi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},grc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof xQi||d instanceof F0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof xQi||p instanceof F0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new F0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new F0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new F0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new F0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new F0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new F0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new F0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new F0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new F0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof xQi)throw u;if(u instanceof F0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new F0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?zRE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):RRE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await CRE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await CRE(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(nY5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new oWa(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof oWa&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=C2n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function CRE(e,t,r=""){let i=await IRE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/aY5}function RRE(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new F0("Operator is_not_set is not supported")}else throw new F0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!oY5.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return qRE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return qRE(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new F0("Date operations cannot be performed on boolean values");let s=sY5(String(n));if(s==null&&(s=TRE(n)),s==null)throw new F0(`Invalid date: ${n}`);let u=TRE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new F0(`Unknown operator: ${a}`)}}function uY5(e,t){if(!(e in t))throw new xQi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function zRE(e,t,r,i=!1){let n=String(e.value);uY5(n,r);let a=r[n];return NRE(a,t,r,i)}function NRE(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=NRE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof xQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=zRE(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=RRE(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof xQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("can't match cohort without a given cohort property value");return n==="AND"}function qRE(e){try{return new RegExp(e),!0}catch{return!1}}function TRE(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 F0(`${e} is in an invalid date format`)}throw new F0(`The date provided ${e} must be a string, number, or date object`)}function sY5(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Orc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var cY5=100,FRE=3e4,lY5=5e4,mrc=class extends SQo{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Orc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,cY5):FRE,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new grc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new F7i(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||lY5}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 BRE}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=FRE){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=B2n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof xQi||y instanceof F0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=C2n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(xTE(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(F7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(F7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=VQi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&FTE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var QRE=require("async_hooks"),Arc=class{constructor(){this.storage=new QRE.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var URE="posthog-node";function fY5(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[tOp.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var tOp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=URE,this.name=URE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(fY5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};F7i.errorPropertiesBuilder=new Pge.ErrorPropertiesBuilder([new Pge.EventCoercer,new Pge.ErrorCoercer,new Pge.ObjectCoercer,new Pge.StringCoercer,new Pge.PrimitiveCoercer],Pge.createStackParser("node:javascript",Pge.nodeStackLineParser),[qTE(),wRE]);var uWa=class extends mrc{getLibraryId(){return"posthog-node"}initializeContext(){return new Arc}};var Prc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new uWa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.54.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var MQo=class{async sendEvent(){}async identify(){}async flush(){}};var sWa=require("fs/promises"),LRE=require("os"),VRE=require("path");var dY5="id",pY5=".fern",DQo=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new uWa(r),this.userId=t==null?void 0:h1c(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.54.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await OV({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=ut(gr.of((0,LRE.homedir)()),je.of(pY5),je.of(dY5));await ri(t)||(await(0,sWa.mkdir)((0,VRE.dirname)(t),{recursive:!0}),await(0,sWa.writeFile)(t,JOe())),this.persistedDistinctId=(await(0,sWa.readFile)(t)).toString()}return this.persistedDistinctId}};var rOp;async function cWa(){return rOp==null&&(rOp=await _Y5()),rOp}async function _Y5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new MQo;let r=await M$o();return r!=null?new DQo({token:r,posthogApiKey:e}):await Saa()!=null?new Prc({posthogApiKey:e}):new DQo({token:void 0,posthogApiKey:e})}catch{return new MQo}}var BQo=ue(require("process"),1);var GRE=ue(Azc(),1),HRE=ue(xRE(),1);function M4(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=EWt(e),e.length===0))return 0;e=e.replace((0,HRE.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(GRE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function jrc(e){let t=0;for(let r of e.split(`
|
|
2052
2052
|
`))t=Math.max(t,M4(r));return t}var dzE=ue(nOp(),1);var yY5=/[\p{Lu}]/u,bY5=/[\p{Ll}]/u,JRE=/^[\p{Lu}](?![\p{Lu}])/gu,ZRE=/([\p{Alpha}\p{N}_]|$)/u,aOp=/[_.\- ]+/,vY5=new RegExp("^"+aOp.source),YRE=new RegExp(aOp.source+ZRE.source,"gu"),XRE=new RegExp("\\d+"+ZRE.source,"gu"),gY5=(e,t,r,i)=>{let n=!1,a=!1,o=!1,c=!1;for(let d=0;d<e.length;d++){let s=e[d];c=d>2?e[d-3]==="-":!0,n&&yY5.test(s)?(e=e.slice(0,d)+"-"+e.slice(d),n=!1,o=a,a=!0,d++):a&&o&&bY5.test(s)&&(!c||i)?(e=e.slice(0,d-1)+"-"+e.slice(d-1),o=a,a=!1,n=!0):(n=t(s)===s&&r(s)!==s,o=a,a=r(s)===s&&t(s)!==s)}return e},OY5=(e,t)=>(JRE.lastIndex=0,e.replace(JRE,r=>t(r))),mY5=(e,t)=>(YRE.lastIndex=0,XRE.lastIndex=0,e.replace(YRE,(r,i)=>t(i)).replace(XRE,r=>t(r)));function oOp(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(a=>a.trim()).filter(a=>a.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(t.locale),i=t.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(t.locale);return e.length===1?aOp.test(e)?"":t.pascalCase?i(e):r(e):(e!==r(e)&&(e=gY5(e,r,i,t.preserveConsecutiveUppercase)),e=e.replace(vY5,""),e=t.preserveConsecutiveUppercase?OY5(e,r):r(e),t.pascalCase&&(e=i(e.charAt(0))+e.slice(1)),mY5(e,i))}var lOp=ue(ezE(),1);var tzE=(e=0)=>t=>`\x1B[${t+e}m`,rzE=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,izE=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,cB={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]}},C32=Object.keys(cB.modifier),wY5=Object.keys(cB.color),EY5=Object.keys(cB.bgColor),q32=[...wY5,...EY5];function SY5(){let e=new Map;for(let[t,r]of Object.entries(cB)){for(let[i,n]of Object.entries(r))cB[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=cB[i],e.set(n[0],n[1]);Object.defineProperty(cB,t,{value:r,enumerable:!1})}return Object.defineProperty(cB,"codes",{value:e,enumerable:!1}),cB.color.close="\x1B[39m",cB.bgColor.close="\x1B[49m",cB.color.ansi=tzE(),cB.color.ansi256=rzE(),cB.color.ansi16m=izE(),cB.bgColor.ansi=tzE(10),cB.bgColor.ansi256=rzE(10),cB.bgColor.ansi16m=izE(10),Object.defineProperties(cB,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?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(i/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[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>cB.rgbToAnsi256(...cB.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>cB.ansi256ToAnsi(cB.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>cB.ansi256ToAnsi(cB.hexToAnsi256(t)),enumerable:!1}}),cB}var MY5=SY5(),nzE=MY5;var wrc=new Set(["\x1B","\x9B"]),DY5=39,sOp="\x07",uzE="[",BY5="]",szE="m",cOp=`${BY5}8;;`,azE=e=>`${wrc.values().next().value}${uzE}${e}${szE}`,ozE=e=>`${wrc.values().next().value}${cOp}${e}${sOp}`,IY5=e=>e.split(" ").map(t=>M4(t)),uOp=(e,t,r)=>{let i=[...t],n=!1,a=!1,o=M4(EWt(e[e.length-1]));for(let[c,d]of i.entries()){let s=M4(d);if(o+s<=r?e[e.length-1]+=d:(e.push(d),o=0),wrc.has(d)&&(n=!0,a=i.slice(c+1).join("").startsWith(cOp)),n){a?d===sOp&&(n=!1,a=!1):d===szE&&(n=!1);continue}o+=s,o===r&&c<i.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},CY5=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(M4(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},qY5=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,a,o=IY5(e),c=[""];for(let[s,u]of e.split(" ").entries()){r.trim!==!1&&(c[c.length-1]=c[c.length-1].trimStart());let f=M4(c[c.length-1]);if(s!==0&&(f>=t&&(r.wordWrap===!1||r.trim===!1)&&(c.push(""),f=0),(f>0||r.trim===!1)&&(c[c.length-1]+=" ",f++)),r.hard&&o[s]>t){let p=t-f,_=1+Math.floor((o[s]-p-1)/t);Math.floor((o[s]-1)/t)<_&&c.push(""),uOp(c,u,t);continue}if(f+o[s]>t&&f>0&&o[s]>0){if(r.wordWrap===!1&&f<t){uOp(c,u,t);continue}c.push("")}if(f+o[s]>t&&r.wordWrap===!1){uOp(c,u,t);continue}c[c.length-1]+=u}r.trim!==!1&&(c=c.map(s=>CY5(s)));let d=[...c.join(`
|
|
2053
2053
|
`)];for(let[s,u]of d.entries()){if(i+=u,wrc.has(u)){let{groups:p}=new RegExp(`(?:\\${uzE}(?<code>\\d+)m|\\${cOp}(?<uri>.*)${sOp})`).exec(d.slice(s).join(""))||{groups:{}};if(p.code!==void 0){let _=Number.parseFloat(p.code);n=_===DY5?void 0:_}else p.uri!==void 0&&(a=p.uri.length===0?void 0:p.uri)}let f=nzE.codes.get(Number(n));d[s+1]===`
|
|
2054
2054
|
`?(a&&(i+=ozE("")),n&&f&&(i+=azE(f))):u===`
|
|
@@ -2223,7 +2223,7 @@ ${g}${O}${A}${H5a}`});var f4o=class{result=OA.Success;logImmediately;logPrefix;s
|
|
|
2223
2223
|
Run ${Lt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
2224
2224
|
Run ${Lt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),lWa(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function wDp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!sKE(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
|
|
2225
2225
|
${await xvx(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Lt.dim(c.currentVersion)+Lt.reset(" \u2192 ")+Lt.green(c.latestVersion);return n+=`
|
|
2226
|
-
`,i?lWa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function xvx(e){let r=await new uKE.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function Gvx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=S2i(u.name,f),_=await X5t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=S2i(s.name,u),p=await X5t({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await yme({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?WQ(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function fKE(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=PZ(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Icc({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await Gvx({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...fKE(s,d,t.logger));else o.push(...fKE(c.versions,void 0,t.logger))}return o}async function Ghn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:EZa(e.packageName,{version:t?"prerelease":"latest"})}var dKE=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Ccc=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ja.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Jgn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.54.
|
|
2226
|
+
`,i?lWa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function xvx(e){let r=await new uKE.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function Gvx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=S2i(u.name,f),_=await X5t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=S2i(s.name,u),p=await X5t({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function lKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await yme({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?WQ(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function fKE(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=PZ(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Icc({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await Gvx({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...fKE(s,d,t.logger));else o.push(...fKE(c.versions,void 0,t.logger))}return o}async function Ghn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:EZa(e.packageName,{version:t?"prerelease":"latest"})}var dKE=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Ccc=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ja.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Jgn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.54.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Lt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new WE}failWithoutThrowing(t,r){this.didSucceed=!1,OJa({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await cWa()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await cKE({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2227
2227
|
`)||(r+=`
|
|
2228
2228
|
`),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=Ebc(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new f4o(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new WE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await cWa()).sendEvent(t)}logger=iOe((t,...r)=>this.log(t,...r));stderr=iOe((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=pKE(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?pKE(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=dKE[this.numTasks++%dKE.length],o=Lt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===OA.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>wWt.indexOf(n.level)>=wWt.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===ja.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await Ghn({cliEnvironment:this.environment,includePreReleases:t}),i=PZ(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Icc({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await PDp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Lt.yellow("?"),style:{answer:n=>Lt.cyan(n),message:n=>Lt.bold(n),highlight:n=>Lt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
2229
2229
|
Cancelled by user.`),new WE):i}}async getInput(t){return await gDp({message:t.message,default:t.default})}};function pKE(e){return`[${e}]:`}var _KE=require("fs/promises");async function EDp({context:e,nameOverride:t,...r}){let i=await wM(t);return i==null?e.failAndThrow(`Directory "${t??J0}" not found.`):await hKE({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function hKE({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ri(ut(e,je.of(EH)))||await ri(ut(e,je.of(vM)))||await ri(ut(e,je.of(gM)))||await ri(ut(e,je.of(fua)))||await ri(ut(e,je.of(dXa)))||await ri(ut(e,je.of(YVc))))&&(o=await yKE({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await Mfp({fernDirectory:e,context:a});return o.length===0&&c==null?a.failAndThrow(`No SDK specifications or docs specifications found. Please ensure one of the following .yml (not .yaml) files is present:
|
|
@@ -2259,7 +2259,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2259
2259
|
|
|
2260
2260
|
Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await jKE({generatorName:t,logger:a});if(c==null)return;let d=Kvx({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return wKE({migrations:d,config:o,logger:a})}function EKE(e){return{"fernapi/fern-typescript-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-typescript-node-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-python-sdk":"https://buildwithfern.com/learn/sdks/generators/python/changelog","fernapi/fern-go-sdk":"https://buildwithfern.com/learn/sdks/generators/go/changelog","fernapi/fern-java-sdk":"https://buildwithfern.com/learn/sdks/generators/java/changelog","fernapi/fern-csharp-sdk":"https://buildwithfern.com/learn/sdks/generators/csharp/changelog","fernapi/fern-php-sdk":"https://buildwithfern.com/learn/sdks/generators/php/changelog","fernapi/fern-ruby-sdk":"https://buildwithfern.com/learn/sdks/generators/ruby/changelog","fernapi/fern-swift-sdk":"https://buildwithfern.com/learn/sdks/generators/swift/changelog"}[e]}async function Jvx({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await I2i({absolutePathToWorkspace:e});if(c==null||!await ri(c))return t.logger.debug("Generators configuration file was not found, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};let d=await(0,Rcc.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=J5a.default.parseDocument(d.toString()),u=s.get("groups");if(u==null)return t.logger.debug("No groups were found within the generators configuration, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};if(!J5a.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${p4o.default.relative(process.cwd(),c)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let f=[],p=[],_=[];for(let h of u.items){let y=h.key.value,b=h.value;if(!J5a.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${p4o.default.relative(process.cwd(),c)}`);continue}if(i!=null&&i!==y){t.logger.debug(`Skipping group ${y} as it does not match the filter: ${i}`);continue}let v=b.get("generators");if(!J5a.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${p4o.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){J5a.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${p4o.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=S2i(m,t),A=r!=null?WQ(r):void 0;if(A!=null&&g!==A){t.logger.debug(`Skipping generator ${m} as it does not match the filter: ${r}`);continue}let j=O.get("version"),S=await X5t({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=S??j;if(S!=null)if(S!==j){t.logger.debug(Lt.green(`Upgrading ${m} from ${j} to ${S}`)),O.set("version",S);let D=0,B=[],R=O.toJSON(),T=await SDp({generatorName:g,from:j,to:S,config:R,logger:t.logger});if(T!=null){D=T.migrationsApplied,B=T.appliedVersions;let q=new Set(Object.keys(R)),z=new Set(Object.keys(T.config));for(let N of q)z.has(N)||O.delete(N);for(let[N,H]of Object.entries(T.config))O.set(N,H);t.logger.debug(Lt.dim(`Applied ${D} migration(s): ${B.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:S,migrationsApplied:D>0?D:void 0,migrationVersions:B.length>0?B:void 0})}else t.logger.debug(Lt.gray(`${m} is already on the latest version: ${j}`)),_.push({generatorName:m,groupName:y,version:j});if(!n){let D=await X5t({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(D!=null){let B=MDp.default.parse(w),R=MDp.default.parse(D);B!=null&&R!=null&&R.major>B.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:D})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:_}}async function SKE({cliContext:e,generator:t,group:r,project:{apiWorkspaces:i},includeMajor:n,channel:a}){let o=[],c=[],d=[];if(await Promise.all(i.map(async s=>{await e.runTaskForWorkspace(s,async u=>{let f=await f_a({absolutePathToWorkspace:s.absoluteFilePath,context:u})??{};if(f==null||f.groups==null){u.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}s.workspaceName==null?u.logger.info("Upgrading generators."):u.logger.info(`Upgrading generators in workspace: ${s.workspaceName}.`);let p=await Jvx({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),_=await I2i({absolutePathToWorkspace:s.absoluteFilePath});_!=null&&p.updatedConfiguration!=null&&await(0,Rcc.writeFile)(_,p.updatedConfiguration),o.push(...p.skippedMajorUpgrades),p.appliedUpgrades.length>0&&c.push({workspace:s.workspaceName,upgrades:p.appliedUpgrades}),p.alreadyUpToDate.length>0&&d.push({workspace:s.workspaceName,upToDate:p.alreadyUpToDate})})})),c.length>0){e.logger.info(""),e.logger.info(Lt.green("Successfully upgraded generators:"));for(let{workspace:s,upgrades:u}of c){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(Lt.green(`${h}Group ${p}:`));for(let y of _){e.logger.info(Lt.green(` - ${y.generatorName}: ${Lt.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(Lt.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=EKE(WQ(y.generatorName));b!=null&&e.logger.info(Lt.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(Lt.dim("Generators already on latest version:"));for(let{workspace:s,upToDate:u}of d){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(Lt.dim(`${h}Group ${p}:`));for(let y of _)e.logger.info(Lt.dim(` - ${y.generatorName}: ${y.version} (latest)`))}}}if(c.length===0&&d.length===0){let s=r!=null?` for group ${r}`:t!=null?` for generator ${t}`:"";e.logger.info(""),e.logger.info(Lt.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(Lt.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(Lt.yellow(` - ${s.generatorName}: ${s.currentVersion} \u2192 ${s.latestMajorVersion}`));let u=t!=null?`fern generator upgrade --generator ${s.generatorName} --include-major`:"fern generator upgrade --include-major";e.logger.info(Lt.yellow(` Run: ${u}`));let f=EKE(WQ(s.generatorName));f!=null&&e.logger.info(Lt.yellow(` Changelog: ${f}`))}}}function BKE(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await AKE({project:await Nm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function IKE(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values($5a),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values($5a),type:"array",description:"The generator output modes to exclude within the outputted list."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:i.output}}),await gKE({project:await Nm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:i.generators?new Set(i.generators):void 0,groupFilter:i.groups?new Set(i.groups):void 0,apiFilter:i.apis?new Set(i.apis):void 0,apiKeyFallback:i.apiFallback,cliContext:t,outputLocation:i.output,includedModes:i["include-mode"]?new Set(i["include-mode"]):void 0,excludedModes:i["exclude-mode"]?new Set(i["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${gM} to the latest stable version.`,i=>i.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to any prompts that may appear during the upgrade process."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(MKE.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor,rc:i.rc}});let n=await Nm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await Icc({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await wDp({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
2261
2261
|
`,includeBoxen:!0});o!=null&&t.logger.info(o)}else await SKE({cliContext:t,generator:i.generator,group:i.group,project:await Nm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0}),includeMajor:i.includeMajor,channel:i.channel})}).command("get",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor}});let n=await OKE({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await Nm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0})});if(n==null){let o=i.api?` for API ${i.api}`:"";t.failAndThrow(`Generator ${i.generator}, in group ${i.group}${o} was not found.`)}let a={};if(i.version&&(a.version=n.version,i.output==null)){process.stdout.write(n.version);return}if(i.language)if(n.language!=null){if(a.language=n.language,i.output==null){process.stdout.write(n.language);return}}else t.logger.warn(`Language information is not available for generator ${n.name} in group ${i.group}`);if(i.repository){let o=n.outputMode.type==="github"?n.outputMode.repo:n.outputMode.type==="githubV2"?n.outputMode.githubV2.repo:void 0;if(o!=null){if(a.repository=o,i.output==null){process.stdout.write(a.repository);return}}else t.logger.warn(`Repository information is not available for generator ${n.name} in group ${i.group}`)}if(i.output)try{await(0,DKE.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var CKE=require("fs/promises");async function qKE({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:i}){await Promise.all(e.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await f_a({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await SZc({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await I2i({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,CKE.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2262
|
-
`+Ii.dump(c)),a.logger.info(Lt.green(`Added ${t} generator`)))})}))}var RKE=require("fs/promises"),zKE=ue(AY(),1);async function NKE({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new _Za,o=Yvx(await a.check({from:await TKE({context:e,filepath:t,flagName:"from"}),to:await TKE({context:e,filepath:r,flagName:"to"})})),c=kvx(e,n),{bump:d,errors:s}=Xvx(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=zKE.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new WE;return{bump:u,nextVersion:f,errors:s}}async function TKE({context:e,filepath:t,flagName:r}){let i=gr.of(Uo(xm(),t));if(!await ri(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new WE;let n=await(0,RKE.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new WE;return a.value}function Yvx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function Xvx(e,t){return{bump:Zvx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function Zvx(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function kvx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=egx(lvc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new WE}}function egx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}var neS=ue(IDp(),1),aeS=ue(Alc(),1),rfc=require("fs/promises"),oeS=ue(require("http"),1),ueS=ue(require("path"),1);var QZE=require("events"),Slc=ue(require("fs"),1),cea=ue(require("path"),1);var mZE=ue(require("os"),1),AZE=300,Zhn=20,z4o=1e7,PZE=mZE.default.platform();var v0x=PZE==="darwin",XBp=PZE==="win32",khn=v0x||XBp,jZE=3e3,wZE=2e4,ZBp=1250;var EUi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(EUi||(EUi={}));var sea;(function(e){e.CHANGE="change",e.RENAME="rename"})(sea||(sea={}));var N4o;(function(e){e.CHANGE="change",e.ERROR="error"})(N4o||(N4o={}));var Df;(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"})(Df||(Df={}));var cY;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cY||(cY={}));var g0x=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,D=Math.min(S,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):h(A)};return m.cancel=p,m.flush=_,m},Plc=g0x;var rIp=ue(require("fs"),1),wlc=ue(require("path"),1);var fA=ue(require("fs"),1),G8=require("util");var jKi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},SUi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kBp=ue(require("process"),1),EZE=kBp.default.getuid?!kBp.default.getuid():!1,SZE=1e4,Qge=()=>{};var F4o={isChangeErrorOk:e=>{if(!F4o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!EZE&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!F4o.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(!F4o.isNodeError(e))throw e;if(!F4o.isChangeErrorOk(e))throw e}},tT=F4o;var eIp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=SZE,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},MZE=new eIp;var wKi=(e,t)=>function(i){return function n(...a){return MZE.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},EKi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var O0x={attempt:{chmod:jKi((0,G8.promisify)(fA.default.chmod),tT.onChangeError),chown:jKi((0,G8.promisify)(fA.default.chown),tT.onChangeError),close:jKi((0,G8.promisify)(fA.default.close),Qge),fsync:jKi((0,G8.promisify)(fA.default.fsync),Qge),mkdir:jKi((0,G8.promisify)(fA.default.mkdir),Qge),realpath:jKi((0,G8.promisify)(fA.default.realpath),Qge),stat:jKi((0,G8.promisify)(fA.default.stat),Qge),unlink:jKi((0,G8.promisify)(fA.default.unlink),Qge),chmodSync:SUi(fA.default.chmodSync,tT.onChangeError),chownSync:SUi(fA.default.chownSync,tT.onChangeError),closeSync:SUi(fA.default.closeSync,Qge),existsSync:SUi(fA.default.existsSync,Qge),fsyncSync:SUi(fA.default.fsync,Qge),mkdirSync:SUi(fA.default.mkdirSync,Qge),realpathSync:SUi(fA.default.realpathSync,Qge),statSync:SUi(fA.default.statSync,Qge),unlinkSync:SUi(fA.default.unlinkSync,Qge)},retry:{close:wKi((0,G8.promisify)(fA.default.close),tT.isRetriableError),fsync:wKi((0,G8.promisify)(fA.default.fsync),tT.isRetriableError),open:wKi((0,G8.promisify)(fA.default.open),tT.isRetriableError),readFile:wKi((0,G8.promisify)(fA.default.readFile),tT.isRetriableError),rename:wKi((0,G8.promisify)(fA.default.rename),tT.isRetriableError),stat:wKi((0,G8.promisify)(fA.default.stat),tT.isRetriableError),write:wKi((0,G8.promisify)(fA.default.write),tT.isRetriableError),writeFile:wKi((0,G8.promisify)(fA.default.writeFile),tT.isRetriableError),closeSync:EKi(fA.default.closeSync,tT.isRetriableError),fsyncSync:EKi(fA.default.fsyncSync,tT.isRetriableError),openSync:EKi(fA.default.openSync,tT.isRetriableError),readFileSync:EKi(fA.default.readFileSync,tT.isRetriableError),renameSync:EKi(fA.default.renameSync,tT.isRetriableError),statSync:EKi(fA.default.statSync,tT.isRetriableError),writeSync:EKi(fA.default.writeSync,tT.isRetriableError),writeFileSync:EKi(fA.default.writeFileSync,tT.isRetriableError)}},DZE=O0x;var jlc=ue(require("fs"),1),Q4o=ue(require("path"),1);var tIp=()=>{};var m0x=()=>{let e=tIp,t=tIp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},BZE=m0x;var A0x=()=>{let{promise:e,resolve:t,isPending:r}=BZE(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},IZE=A0x;var CZE={then:e=>{e()}};var qZE=e=>Array.isArray(e)?e:[e],TZE=e=>typeof e=="function";var P0x=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=qZE(a).map(G=>TZE(G)?G:x=>G.test(x)),c=G=>o.some(x=>x(G)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:D}=IZE(),B=0,R=(G,x,Ee,se)=>{g.has(x)||B>=n||(B+=1,G.directories.push(x),G.directoriesNames.add(Ee),u.push(x),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),g.add(x),!(se>=i)&&(B>=n||Y(x,se+1)))},T=(G,x,Ee)=>{g.has(x)||B>=n||(B+=1,G.files.push(x),G.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),g.add(x))},q=(G,x,Ee,se)=>{g.has(x)||B>=n||(B+=1,G.symlinks.push(x),G.symlinksNames.add(Ee),b.push(x),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(x),g.add(x),r&&(se>=i||B>=n||ye(x,se+1)))},z=(G,x,Ee,se,Ae)=>{d.aborted||c(x)||(se.isDirectory()?R(G,x,Ee,Ae):se.isFile()?T(G,x,Ee):se.isSymbolicLink()&&q(G,x,Ee,Ae))},N=(G,x,Ee,se)=>{if(d.aborted)return;let Ae=x===Q4o.default.sep?"":Q4o.default.sep,Ue=Ee.name,ae=`${x}${Ae}${Ue}`;c(ae)||(Ee.isDirectory()?R(G,ae,Ue,se):Ee.isFile()?T(G,ae,Ue):Ee.isSymbolicLink()&&q(G,ae,Ue,se))},H=(G,x,Ee,se)=>{for(let Ae=0,Ue=Ee.length;Ae<Ue;Ae++)N(G,x,Ee[Ae],se)},Y=(G,x)=>{d.aborted||x>i||B>=n||(w(),jlc.default.readdir(G,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||CZE).then(()=>{let Ue=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Ue,G,se,x),D()})}))},ye=(G,x)=>{w(),jlc.default.realpath(G,(Ee,se)=>{if(Ee||d.aborted)return D();jlc.default.stat(se,(Ae,Ue)=>{if(Ae||d.aborted)return D();let ae=Q4o.default.basename(se),re=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Ue,x),D()})})};return(async(G,x=1)=>(G=Q4o.default.normalize(G),g.add(G),Y(G,x),await S,d.aborted?A:j))(e)},RZE=P0x;var MUi={lang:{debounce:Plc,attempt:e=>{try{return e()}catch(t){return MUi.lang.castError(t)}},castArray:e=>MUi.lang.isArray(e)?e:[e],castError:e=>MUi.lang.isError(e)?e:MUi.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(MUi.lang.isNaN(e))return MUi.lang.isNaN(t);if(MUi.lang.isPrimitive(e)||MUi.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(wlc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rIp.default.realpathSync.native(e):rIp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===wlc.default.sep&&t.length-e.length>wlc.default.sep.length,poll:(e,t=wZE)=>DZE.retry.stat(t)(e,{bigint:!0}).catch(MUi.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await RZE(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},yh=MUi;var Elc=ue(require("path"),1);var iIp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||yh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=AZE){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=yh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Df.CHANGE&&c===Df.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Df.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Df.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Zhn:Math.min(1,this.options.depth??Zhn),o=this.options.limit??z4o,[c,d]=await yh.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())yh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Df.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!khn&&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(Df.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Df.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Elc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Df.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Elc.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(Df.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Df.ADD?this.onTargetAdd(i):r===Df.ADD_DIR?this.onTargetAddDir(i):r===Df.CHANGE?this.onTargetChange(i):r===Df.UNLINK?this.onTargetUnlink(i):r===Df.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=sea.CHANGE,r){if(this.watcher.isClosed())return;let i=Elc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){XBp&&t.code==="EPERM"?this.onWatcherChange(sea.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(N4o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(N4o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(sea.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&khn&&this.options.native!==!1?this.options.depth??Zhn:Math.min(1,this.options.depth??Zhn),i=this.options.limit??z4o,[n,a]=await yh.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(sea.CHANGE,c,t)}))}}},zZE=iIp;var lY={interval:100,intervalId:void 0,fns:new Map,init:()=>{lY.intervalId||(lY.intervalId=setInterval(lY.resolve,lY.interval))},reset:()=>{lY.intervalId&&(clearInterval(lY.intervalId),delete lY.intervalId)},add:(e,t)=>{lY.fns.set(e,Date.now()+t),lY.init()},remove:e=>{lY.fns.delete(e)},resolve:()=>{if(!lY.fns.size)return lY.reset();let e=Date.now();for(let[t,r]of lY.fns)r>=e||(lY.remove(t),t())}},U4o=lY;var L4o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZBp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(yh.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),U4o.remove(s)},s=()=>{d(),c()};U4o.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=ZBp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),U4o.remove(s)},s=()=>{d(),c()};U4o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Df.ADD,EUi.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Df.ADD_DIR,EUi.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Df.UNLINK,EUi.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Df.UNLINK_DIR,EUi.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};L4o.DIR_EVENTS={add:Df.ADD_DIR,rename:Df.RENAME_DIR,unlink:Df.UNLINK_DIR};L4o.FILE_EVENTS={add:Df.ADD,change:Df.CHANGE,rename:Df.RENAME,unlink:Df.UNLINK};var NZE=L4o;var nIp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(yh.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(yh.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(yh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return yh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);yh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aIp=nIp;var oIp=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}},FZE=oIp;var uIp=class{constructor(){this.inos={},this.paths=new aIp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await yh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new FZE(i)}reset(){this.inos={},this.paths=new aIp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Df.ADD,n),[Df.ADD];if(n.isDirectory())return this.updateIno(t,Df.ADD_DIR,n),[Df.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Df.UNLINK,i),[Df.UNLINK];if(i.isDirectory())return this.updateIno(t,Df.UNLINK_DIR,i),[Df.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Df.CHANGE,n),[Df.CHANGE]);if(n.isDirectory())return this.updateIno(t,Df.UNLINK,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK,Df.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD,n),[Df.UNLINK_DIR,Df.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK_DIR,Df.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?EUi.FILE:EUi.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},sIp=uIp;var cIp=class e extends QZE.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cY.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cY.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cY.READY,n)),this._locker=new NZE(this),this._roots=new Set,this._poller=new sIp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(yh.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(cY.CLOSE))}error(t){if(this.isClosed())return!1;let r=yh.lang.castError(t);return this.emit(cY.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cY.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cY.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)yh.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new zZE(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yh.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=cea.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??Zhn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&khn&&u.options.native!==!1)))return!0;if(!khn)break;let s=cea.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=yh.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||khn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Slc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=cea.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||khn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Zhn,c=r.limit??z4o,[d]=await yh.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=yh.fs.getDepth(t);for(let f of d){let p=yh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cY.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cY.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=cea.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sIp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return yh.lang.noop;if(this.pollerExists(t,r))return yh.lang.noop;let n={...r,interval:r.pollingInterval??jZE},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cY.CLOSE,c),Slc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cY.CLOSE,c),Slc.default.unwatchFile(t,i)};return yh.lang.attempt(o),()=>yh.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=yh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!yh.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=cea.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await yh.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=cea.default.dirname(t);return(await yh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=yh.lang.noop){if(yh.lang.isFunction(t))return this.watch([],{},t);if(yh.lang.isUndefined(t))return this.watch([],r,i);if(yh.lang.isFunction(r))return this.watch(t,{},r);if(yh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=yh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==yh.lang.noop&&this.on(cY.ALL,i),r.readdirMap=void 0,this.ready())}},Mlc=cIp;zoc();var fxa=require("fs/promises"),UZE=require("os"),LZE=ue(require("path"),1),j0x=".fern",w0x="logs";function E0x(){return"cli@3.54.0"}var V4o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(gr.of((0,UZE.homedir)()),je.of(j0x)),r=ut(t,je.of(w0x));await ri(r)||await(0,fxa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,je.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${LZE.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2262
|
+
`+Ii.dump(c)),a.logger.info(Lt.green(`Added ${t} generator`)))})}))}var RKE=require("fs/promises"),zKE=ue(AY(),1);async function NKE({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new _Za,o=Yvx(await a.check({from:await TKE({context:e,filepath:t,flagName:"from"}),to:await TKE({context:e,filepath:r,flagName:"to"})})),c=kvx(e,n),{bump:d,errors:s}=Xvx(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=zKE.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new WE;return{bump:u,nextVersion:f,errors:s}}async function TKE({context:e,filepath:t,flagName:r}){let i=gr.of(Uo(xm(),t));if(!await ri(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new WE;let n=await(0,RKE.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new WE;return a.value}function Yvx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function Xvx(e,t){return{bump:Zvx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function Zvx(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function kvx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=egx(lvc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new WE}}function egx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}var neS=ue(IDp(),1),aeS=ue(Alc(),1),rfc=require("fs/promises"),oeS=ue(require("http"),1),ueS=ue(require("path"),1);var QZE=require("events"),Slc=ue(require("fs"),1),cea=ue(require("path"),1);var mZE=ue(require("os"),1),AZE=300,Zhn=20,z4o=1e7,PZE=mZE.default.platform();var v0x=PZE==="darwin",XBp=PZE==="win32",khn=v0x||XBp,jZE=3e3,wZE=2e4,ZBp=1250;var EUi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(EUi||(EUi={}));var sea;(function(e){e.CHANGE="change",e.RENAME="rename"})(sea||(sea={}));var N4o;(function(e){e.CHANGE="change",e.ERROR="error"})(N4o||(N4o={}));var Df;(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"})(Df||(Df={}));var cY;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cY||(cY={}));var g0x=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,D=Math.min(S,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):h(A)};return m.cancel=p,m.flush=_,m},Plc=g0x;var rIp=ue(require("fs"),1),wlc=ue(require("path"),1);var fA=ue(require("fs"),1),G8=require("util");var jKi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},SUi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kBp=ue(require("process"),1),EZE=kBp.default.getuid?!kBp.default.getuid():!1,SZE=1e4,Qge=()=>{};var F4o={isChangeErrorOk:e=>{if(!F4o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!EZE&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!F4o.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(!F4o.isNodeError(e))throw e;if(!F4o.isChangeErrorOk(e))throw e}},tT=F4o;var eIp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=SZE,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},MZE=new eIp;var wKi=(e,t)=>function(i){return function n(...a){return MZE.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},EKi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var O0x={attempt:{chmod:jKi((0,G8.promisify)(fA.default.chmod),tT.onChangeError),chown:jKi((0,G8.promisify)(fA.default.chown),tT.onChangeError),close:jKi((0,G8.promisify)(fA.default.close),Qge),fsync:jKi((0,G8.promisify)(fA.default.fsync),Qge),mkdir:jKi((0,G8.promisify)(fA.default.mkdir),Qge),realpath:jKi((0,G8.promisify)(fA.default.realpath),Qge),stat:jKi((0,G8.promisify)(fA.default.stat),Qge),unlink:jKi((0,G8.promisify)(fA.default.unlink),Qge),chmodSync:SUi(fA.default.chmodSync,tT.onChangeError),chownSync:SUi(fA.default.chownSync,tT.onChangeError),closeSync:SUi(fA.default.closeSync,Qge),existsSync:SUi(fA.default.existsSync,Qge),fsyncSync:SUi(fA.default.fsync,Qge),mkdirSync:SUi(fA.default.mkdirSync,Qge),realpathSync:SUi(fA.default.realpathSync,Qge),statSync:SUi(fA.default.statSync,Qge),unlinkSync:SUi(fA.default.unlinkSync,Qge)},retry:{close:wKi((0,G8.promisify)(fA.default.close),tT.isRetriableError),fsync:wKi((0,G8.promisify)(fA.default.fsync),tT.isRetriableError),open:wKi((0,G8.promisify)(fA.default.open),tT.isRetriableError),readFile:wKi((0,G8.promisify)(fA.default.readFile),tT.isRetriableError),rename:wKi((0,G8.promisify)(fA.default.rename),tT.isRetriableError),stat:wKi((0,G8.promisify)(fA.default.stat),tT.isRetriableError),write:wKi((0,G8.promisify)(fA.default.write),tT.isRetriableError),writeFile:wKi((0,G8.promisify)(fA.default.writeFile),tT.isRetriableError),closeSync:EKi(fA.default.closeSync,tT.isRetriableError),fsyncSync:EKi(fA.default.fsyncSync,tT.isRetriableError),openSync:EKi(fA.default.openSync,tT.isRetriableError),readFileSync:EKi(fA.default.readFileSync,tT.isRetriableError),renameSync:EKi(fA.default.renameSync,tT.isRetriableError),statSync:EKi(fA.default.statSync,tT.isRetriableError),writeSync:EKi(fA.default.writeSync,tT.isRetriableError),writeFileSync:EKi(fA.default.writeFileSync,tT.isRetriableError)}},DZE=O0x;var jlc=ue(require("fs"),1),Q4o=ue(require("path"),1);var tIp=()=>{};var m0x=()=>{let e=tIp,t=tIp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},BZE=m0x;var A0x=()=>{let{promise:e,resolve:t,isPending:r}=BZE(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},IZE=A0x;var CZE={then:e=>{e()}};var qZE=e=>Array.isArray(e)?e:[e],TZE=e=>typeof e=="function";var P0x=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=qZE(a).map(G=>TZE(G)?G:x=>G.test(x)),c=G=>o.some(x=>x(G)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:D}=IZE(),B=0,R=(G,x,Ee,se)=>{g.has(x)||B>=n||(B+=1,G.directories.push(x),G.directoriesNames.add(Ee),u.push(x),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),g.add(x),!(se>=i)&&(B>=n||Y(x,se+1)))},T=(G,x,Ee)=>{g.has(x)||B>=n||(B+=1,G.files.push(x),G.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),g.add(x))},q=(G,x,Ee,se)=>{g.has(x)||B>=n||(B+=1,G.symlinks.push(x),G.symlinksNames.add(Ee),b.push(x),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(x),g.add(x),r&&(se>=i||B>=n||ye(x,se+1)))},z=(G,x,Ee,se,Ae)=>{d.aborted||c(x)||(se.isDirectory()?R(G,x,Ee,Ae):se.isFile()?T(G,x,Ee):se.isSymbolicLink()&&q(G,x,Ee,Ae))},N=(G,x,Ee,se)=>{if(d.aborted)return;let Ae=x===Q4o.default.sep?"":Q4o.default.sep,Ue=Ee.name,ae=`${x}${Ae}${Ue}`;c(ae)||(Ee.isDirectory()?R(G,ae,Ue,se):Ee.isFile()?T(G,ae,Ue):Ee.isSymbolicLink()&&q(G,ae,Ue,se))},H=(G,x,Ee,se)=>{for(let Ae=0,Ue=Ee.length;Ae<Ue;Ae++)N(G,x,Ee[Ae],se)},Y=(G,x)=>{d.aborted||x>i||B>=n||(w(),jlc.default.readdir(G,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||CZE).then(()=>{let Ue=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Ue,G,se,x),D()})}))},ye=(G,x)=>{w(),jlc.default.realpath(G,(Ee,se)=>{if(Ee||d.aborted)return D();jlc.default.stat(se,(Ae,Ue)=>{if(Ae||d.aborted)return D();let ae=Q4o.default.basename(se),re=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Ue,x),D()})})};return(async(G,x=1)=>(G=Q4o.default.normalize(G),g.add(G),Y(G,x),await S,d.aborted?A:j))(e)},RZE=P0x;var MUi={lang:{debounce:Plc,attempt:e=>{try{return e()}catch(t){return MUi.lang.castError(t)}},castArray:e=>MUi.lang.isArray(e)?e:[e],castError:e=>MUi.lang.isError(e)?e:MUi.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(MUi.lang.isNaN(e))return MUi.lang.isNaN(t);if(MUi.lang.isPrimitive(e)||MUi.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(wlc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rIp.default.realpathSync.native(e):rIp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===wlc.default.sep&&t.length-e.length>wlc.default.sep.length,poll:(e,t=wZE)=>DZE.retry.stat(t)(e,{bigint:!0}).catch(MUi.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await RZE(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},yh=MUi;var Elc=ue(require("path"),1);var iIp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||yh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=AZE){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=yh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Df.CHANGE&&c===Df.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Df.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Df.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Zhn:Math.min(1,this.options.depth??Zhn),o=this.options.limit??z4o,[c,d]=await yh.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())yh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Df.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!khn&&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(Df.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Df.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Elc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Df.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Elc.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(Df.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Df.ADD?this.onTargetAdd(i):r===Df.ADD_DIR?this.onTargetAddDir(i):r===Df.CHANGE?this.onTargetChange(i):r===Df.UNLINK?this.onTargetUnlink(i):r===Df.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=sea.CHANGE,r){if(this.watcher.isClosed())return;let i=Elc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){XBp&&t.code==="EPERM"?this.onWatcherChange(sea.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(N4o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(N4o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(sea.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&khn&&this.options.native!==!1?this.options.depth??Zhn:Math.min(1,this.options.depth??Zhn),i=this.options.limit??z4o,[n,a]=await yh.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(sea.CHANGE,c,t)}))}}},zZE=iIp;var lY={interval:100,intervalId:void 0,fns:new Map,init:()=>{lY.intervalId||(lY.intervalId=setInterval(lY.resolve,lY.interval))},reset:()=>{lY.intervalId&&(clearInterval(lY.intervalId),delete lY.intervalId)},add:(e,t)=>{lY.fns.set(e,Date.now()+t),lY.init()},remove:e=>{lY.fns.delete(e)},resolve:()=>{if(!lY.fns.size)return lY.reset();let e=Date.now();for(let[t,r]of lY.fns)r>=e||(lY.remove(t),t())}},U4o=lY;var L4o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZBp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(yh.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),U4o.remove(s)},s=()=>{d(),c()};U4o.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=ZBp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),U4o.remove(s)},s=()=>{d(),c()};U4o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Df.ADD,EUi.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Df.ADD_DIR,EUi.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Df.UNLINK,EUi.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Df.UNLINK_DIR,EUi.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};L4o.DIR_EVENTS={add:Df.ADD_DIR,rename:Df.RENAME_DIR,unlink:Df.UNLINK_DIR};L4o.FILE_EVENTS={add:Df.ADD,change:Df.CHANGE,rename:Df.RENAME,unlink:Df.UNLINK};var NZE=L4o;var nIp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(yh.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(yh.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(yh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return yh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);yh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aIp=nIp;var oIp=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}},FZE=oIp;var uIp=class{constructor(){this.inos={},this.paths=new aIp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await yh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new FZE(i)}reset(){this.inos={},this.paths=new aIp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Df.ADD,n),[Df.ADD];if(n.isDirectory())return this.updateIno(t,Df.ADD_DIR,n),[Df.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Df.UNLINK,i),[Df.UNLINK];if(i.isDirectory())return this.updateIno(t,Df.UNLINK_DIR,i),[Df.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Df.CHANGE,n),[Df.CHANGE]);if(n.isDirectory())return this.updateIno(t,Df.UNLINK,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK,Df.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD,n),[Df.UNLINK_DIR,Df.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK_DIR,Df.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?EUi.FILE:EUi.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},sIp=uIp;var cIp=class e extends QZE.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cY.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cY.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cY.READY,n)),this._locker=new NZE(this),this._roots=new Set,this._poller=new sIp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(yh.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(cY.CLOSE))}error(t){if(this.isClosed())return!1;let r=yh.lang.castError(t);return this.emit(cY.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cY.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cY.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)yh.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new zZE(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yh.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=cea.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??Zhn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&khn&&u.options.native!==!1)))return!0;if(!khn)break;let s=cea.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=yh.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||khn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Slc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=cea.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||khn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Zhn,c=r.limit??z4o,[d]=await yh.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=yh.fs.getDepth(t);for(let f of d){let p=yh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cY.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cY.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=cea.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sIp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return yh.lang.noop;if(this.pollerExists(t,r))return yh.lang.noop;let n={...r,interval:r.pollingInterval??jZE},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cY.CLOSE,c),Slc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cY.CLOSE,c),Slc.default.unwatchFile(t,i)};return yh.lang.attempt(o),()=>yh.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=yh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!yh.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=cea.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await yh.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=cea.default.dirname(t);return(await yh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=yh.lang.noop){if(yh.lang.isFunction(t))return this.watch([],{},t);if(yh.lang.isUndefined(t))return this.watch([],r,i);if(yh.lang.isFunction(r))return this.watch(t,{},r);if(yh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=yh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==yh.lang.noop&&this.on(cY.ALL,i),r.readdirMap=void 0,this.ready())}},Mlc=cIp;zoc();var fxa=require("fs/promises"),UZE=require("os"),LZE=ue(require("path"),1),j0x=".fern",w0x="logs";function E0x(){return"cli@3.54.1"}var V4o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(gr.of((0,UZE.homedir)()),je.of(j0x)),r=ut(t,je.of(w0x));await ri(r)||await(0,fxa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,je.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${LZE.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2263
2263
|
`);await(0,fxa.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
2264
2264
|
`;try{await(0,fxa.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let i={timestamp:t.timestamp,source:E0x(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var BIp=ue(vIp(),1),FkE=ue(C7s(),1),Uge=require("fs/promises"),QkE=require("os"),UkE=ue(aQ(),1),LkE=ue(zkE(),1),Hlc=process.platform==="win32",DIp=Lt.cyan("[docs]:"),X0x="etag",Z0x=23,NkE=e=>e.padEnd(Z0x," "),k0x="preview",eEx="app-preview",tEx="bundle",rEx=".next",iEx="standalone",nEx=".fern",aEx="packages/fern-docs/bundle/.next/server/instrumentation.js",oEx=".npmrc",uEx=".pnpmfile.cjs",sEx="pnpm-workspace.yaml",cEx='Cannot find matching keyid: {"signatures":';function lEx(){return ut(gr.of((0,QkE.homedir)()),je.of(nEx))}function dxa({app:e=!1}){return ut(lEx(),je.of(e?eEx:k0x))}function ryn({app:e=!1}){return ut(dxa({app:e}),je.of(e?rEx:tEx))}function G4o({app:e=!1}){return ut(ryn({app:e}),je.of(iEx))}function fEx({app:e=!1}){return ut(G4o({app:e}),je.of(aEx))}function dEx({app:e=!1}){return ut(G4o({app:e}),je.of(sEx))}function pEx({app:e=!1}){return ut(G4o({app:e}),je.of(uEx))}function _Ex({app:e=!1}){return ut(G4o({app:e}),je.of(oEx))}function dea(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function hEx({app:e=!1}){return ut(dxa({app:e}),je.of(X0x))}var yEx=`module.exports = {
|
|
2265
2265
|
hooks: {
|
package/package.json
CHANGED