fern-api 3.56.10 → 3.57.0
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
|
@@ -1584,7 +1584,7 @@ ${t}`)}return t}getContent(){let t=this.stringifyImports();return t.length>0?t+`
|
|
|
1584
1584
|
`),n=i[0]+`
|
|
1585
1585
|
`,a=i.slice(1).join(`
|
|
1586
1586
|
`);t.write(n.replaceAll("`","\\`")),t.writeNoIndent(a.replaceAll("`","\\`")),t.write("`")}writeIterable({writer:t,iterable:r}){let i=MMB({values:r.values});if(i.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let n of i)n.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeRecord({writer:t,record:r}){let i=SMB({entries:r.entries});if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of i)n.key.write(t),t.write(": "),n.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeObject({writer:t,object:r}){let i=EMB({fields:r.fields});if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of i)t.write(`${n.name}: `),n.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}static array({values:t}){return new this({type:"array",values:t})}static bigint(t){return new this({type:"bigint",value:t})}static blob(t){return new this({type:"blob",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static datetime(t){return new this({type:"datetime",value:t})}static number(t){return new this({type:"number",value:t})}static object({fields:t}){return new this({type:"object",fields:t})}static record({entries:t}){return new this({type:"record",entries:t})}static reference(t){return new this({type:"reference",value:t})}static set({values:t}){return new this({type:"set",values:t})}static string(t){return new this({type:"string",value:t})}static tuple({values:t}){return new this({type:"tuple",values:t})}static unknown(t){return new this({type:"unknown",value:t})}static null(){return new this({type:"null"})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes('"')?`\`${r}\``:`"${r}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of r)t.writeNode(e.unknown(i)),t.writeLine(",");t.dedent(),t.write("]")}writeUnknownObject({writer:t,value:r}){let i=Object.entries(r);if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[n,a]of i)t.write(`${n}: `),t.writeNode(e.unknown(a)),t.writeLine(",");t.dedent(),t.write("}")}};function EMB({fields:e}){return e.filter(t=>!s8i.isNop(t.value))}function SMB({entries:e}){return e.filter(t=>!s8i.isNop(t.key)&&!s8i.isNop(t.value))}function MMB({values:e}){return e.filter(t=>!s8i.isNop(t))}var yya=class extends IE{args;constructor(t){super(),this.args=t}write(t){this.args.export&&t.write("export "),this.args.const?t.write("const "):t.write("let "),t.write(`${this.args.name} = `),t.writeNode(this.args.initializer)}};function BMB(e){return new fya(e)}function IMB(e){return new dya(e)}function CMB(e){return new lya(e)}function qMB(e){return new pya(e)}function TMB(e){return new _ya(e)}function RMB(e){return new hya(e)}function zMB(e){return new _0n(e)}function NMB(e){return new yya(e)}function D4h({generatorConfig:e,isPackagePrivate:t}){let r=e.output.mode;switch(r.type){case"downloadFiles":return;case"publish":return{packageName:r.registriesV2.npm.packageName,version:r.version,private:t,publishInfo:{registryUrl:r.registriesV2.npm.registryUrl,token:r.registriesV2.npm.token},license:void 0,repoUrl:void 0};case"github":if(r.publishInfo!=null&&r.publishInfo.type!=="npm")throw new Error(`Expected to receive npm publish info but received ${r.publishInfo.type} instead`);return{packageName:r.publishInfo!=null?r.publishInfo.packageName:"",version:r.version,private:t,publishInfo:void 0,repoUrl:FMB(r.repoUrl),license:e.license?._visit({basic:i=>i.id,custom:i=>`See ${i.filename}`,_other:()=>{}})};default:throw new Error(`Encountered unknown output mode: ${r}`)}}function FMB(e){if(e!=null)return e.startsWith("https://github.com/")?`git+${e}`:e.startsWith("ssh://github.com/")?`github:${Eio(e).replace("ssh://github.com/","")}`:e.startsWith("https://bitbucket.org/")?`bitbucket:${Eio(e).replace("https://bitbucket.org/","")}`:e.startsWith("ssh://bitbucket.org/")?`bitbucket:${Eio(e).replace("ssh://bitbucket.org/","")}`:e.startsWith("https://gitlab.com/")?`gitlab:${Eio(e).replace("https://gitlab.com/","")}`:e.startsWith("ssh://gitlab.com/")?`gitlab:${Eio(e).replace("ssh://gitlab.com/","")}`:(e.startsWith("git+")||(e=`git+${e}`),e.endsWith(".git")||(e=`${e}.git`),e)}function Eio(e){return e.endsWith(".git")?e.slice(0,-4):e}function Etl({organization:e,workspaceName:t,namespaceExport:r}){return r??`${Wf(mn(e))}${Wf(mn(t))}`}var Qtl=se(ixh(),1);var TDB="value",kwu=class{context;constructor({context:t}){this.context=t}convert(t){let r=t.convertOpts;if(t.value===null)return this.context.isNullable(t.typeReference)?na.TypeLiteral.null():(this.context.errors.add({severity:Wr.Critical,message:"Expected non-null value, but got null"}),na.TypeLiteral.nop());if(t.value===void 0)return na.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,convertOpts:r});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value,convertOpts:r});case"map":return this.convertMap({map:t.typeReference,value:t.value,convertOpts:r});case"named":{let i=this.context.resolveNamedType({typeId:t.typeReference.value});return i==null?na.TypeLiteral.nop():this.convertNamed({named:i,value:t.value,as:t.as,convertOpts:r})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,convertOpts:r});case"unknown":return this.convertUnknown({value:t.value,convertOpts:r});default:de(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:r});return i==null?na.TypeLiteral.nop():na.TypeLiteral.boolean(i)}case"string":{let i=this.context.getValueAsString({value:r});return i==null?na.TypeLiteral.nop():na.TypeLiteral.string(i)}default:de(t)}}convertList({list:t,value:r,convertOpts:i}){return Array.isArray(r)?na.TypeLiteral.array({values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n,convertOpts:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Wr.Critical,message:`Expected array but got: ${typeof r}`}),na.TypeLiteral.nop())}convertSet({set:t,value:r,convertOpts:i}){return Array.isArray(r)?na.TypeLiteral.set({values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n,convertOpts:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Wr.Critical,message:`Expected array but got: ${typeof r}`}),na.TypeLiteral.nop())}convertMap({map:t,value:r,convertOpts:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Wr.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),na.TypeLiteral.nop()):na.TypeLiteral.record({entries:Object.entries(r).map(([n,a])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key",convertOpts:i}),value:this.convert({typeReference:t.value,value:a,convertOpts:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:i,convertOpts:n}){switch(t.type){case"alias":return this.context.customConfig?.useBrandedStringAliases?na.TypeLiteral.reference(na.codeblock(a=>{a.writeNode(na.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})})),a.write("("),a.writeNode(this.convert({typeReference:t.typeReference,value:r,as:i,convertOpts:n})),a.write(")")})):this.convert({typeReference:t.typeReference,value:r,as:i,convertOpts:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:n});case"enum":return this.convertEnum({enum_:t,value:r,convertOpts:n});case"object":return this.convertObject({object_:t,value:r,convertOpts:n});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:n});default:de(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:i}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return na.TypeLiteral.nop();let a=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:a,convertOpts:i});if(o==null)return na.TypeLiteral.nop();if(this.context.customConfig?.includeUtilsOnUnionMembers)return na.TypeLiteral.reference(na.codeblock(d=>{d.writeNode(na.invokeMethod({on:na.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})}),method:this.context.getMethodName(a.discriminantValue.name),arguments_:this.convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:n,unionVariant:a,unionProperties:o,convertOpts:i})}))}));let c={name:this.context.getPropertyName(t.discriminant.name),value:na.TypeLiteral.string(a.discriminantValue.wireValue)};return na.TypeLiteral.object({fields:[c,...o]})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r,convertOpts:i}){let n=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:r.typeId});if(a==null)return;let o=this.convertNamed({named:a,value:t.value,convertOpts:i});if(!o.isObject()){this.context.errors.add({severity:Wr.Critical,message:"Internal error; expected union value to be an object"});return}let c=o.asObjectOrThrow();return[...n,...c.fields]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let a=this.context.getRecord(t.value);return a==null?[...n,{name:TDB,value:this.convert({typeReference:r.typeReference,value:t.value,convertOpts:i})}]:[...n,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:a[r.discriminantValue.wireValue],convertOpts:i})}]}finally{this.context.errors.unscope()}case"noProperties":return n;default:de(r)}}convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:t,unionVariant:r,unionProperties:i,convertOpts:n}){return r.type==="singleProperty"&&this.context.getRecord(t.value)==null&&i.length===1?[this.convert({typeReference:r.typeReference,value:t.value,convertOpts:n})]:i.length>0?[na.TypeLiteral.object({fields:i})]:[]}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r,convertOpts:i}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert({...a,convertOpts:i})}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r,convertOpts:i}){let n=this.context.associateByWireValue({parameters:this.filterReadWriteProperties(t.properties,i),values:this.context.getRecord(r)??{}});return na.TypeLiteral.object({fields:n.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert({...a,convertOpts:i})}}finally{this.context.errors.unscope()}})})}filterReadWriteProperties(t,r){return this.context.customConfig?.experimentalGenerateReadWriteOnlyTypes!==!0||typeof r>"u"||(r.isForRequest&&(t=t.filter(i=>i.propertyAccess!==Qtl.ObjectPropertyAccess.ReadOnly)),r.isForResponse&&(t=t.filter(i=>i.propertyAccess!==Qtl.ObjectPropertyAccess.WriteOnly))),t}convertEnum({enum_:t,value:r}){let i=this.getEnumValue({enum_:t,value:r});return i==null?na.TypeLiteral.nop():na.TypeLiteral.string(i)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Wr.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(n=>n.wireValue===r)==null){this.context.errors.add({severity:Wr.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:i}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:i});return n??na.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:i}){for(let n of t.types)try{return this.convert({typeReference:n,value:r,convertOpts:i})}catch{continue}this.context.errors.add({severity:Wr.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,convertOpts:r}){return na.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:i,convertOpts:n}){switch(t){case"INTEGER":case"UINT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?na.TypeLiteral.nop():na.TypeLiteral.number(a)}case"LONG":case"UINT_64":{let a=this.getValueAsNumber({value:r,as:i});return a==null?na.TypeLiteral.nop():this.context.customConfig?.useBigInt?na.TypeLiteral.bigint(BigInt(a)):na.TypeLiteral.number(a)}case"FLOAT":case"DOUBLE":{let a=this.getValueAsNumber({value:r});return a==null?na.TypeLiteral.nop():na.TypeLiteral.number(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:r,as:i});return a==null?na.TypeLiteral.nop():na.TypeLiteral.boolean(a)}case"BASE_64":case"DATE":case"UUID":case"STRING":{let a=this.context.getValueAsString({value:r});return a==null?na.TypeLiteral.nop():na.TypeLiteral.string(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:r});return a==null?na.TypeLiteral.nop():na.TypeLiteral.datetime(a)}case"BIG_INTEGER":{let a=this.context.getValueAsString({value:r});return a==null?na.TypeLiteral.nop():this.context.customConfig?.useBigInt?na.TypeLiteral.bigint(BigInt(a)):na.TypeLiteral.string(a)}default:de(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 e0u=class{context;constructor({context:t}){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":i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getSingleFileProperty({property:a,record:n})});break;case"fileArray":i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getArrayFileProperty({property:a,record:n})});break;case"bodyProperty":i.bodyPropertyFields.push({name:this.context.getPropertyName(a.name.name),value:this.getBodyProperty({property:a,record:n})});break;default:de(a)}return i}getSingleFileProperty({property:t,record:r}){let i=this.context.getSingleFileValue({property:t,record:r});return i==null?na.TypeLiteral.nop():na.TypeLiteral.blob(i)}getArrayFileProperty({property:t,record:r}){let i=this.context.getFileArrayValues({property:t,record:r});return i==null?na.TypeLiteral.nop():na.TypeLiteral.array({values:i.map(n=>na.TypeLiteral.blob(n))})}getBodyProperty({property:t,record:r}){let i=r[t.name.wireValue];return i==null?na.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var t0u=class e extends Kq{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;moduleName;namespaceExport;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new kwu({context:this}),this.filePropertyMapper=new e0u({context:this}),this.moduleName=RDB({config:r,customConfig:this.customConfig}),this.namespaceExport=Etl({organization:r.organization,workspaceName:r.workspaceName,namespaceExport:this.customConfig?.namespaceExport})}clone(){return new e({ir:this.ir,config:this.config})}getModuleImport(){return{type:"named",moduleName:this.moduleName}}getRootClientName(){return`${this.namespaceExport}Client`}getPropertyName(t){return this.customConfig?.retainOriginalCasing||this.customConfig?.noSerdeLayer?this.formatOriginalPropertyName(t.originalName):t.camelCase.unsafeName}getMethodName(t){return t.camelCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentsTypeReference(r)}getFullyQualifiedReference({declaration:t}){return t.fernFilepath.allParts.length>0?`${t.fernFilepath.allParts.map(r=>r.camelCase.unsafeName).join(".")}.${this.getTypeName(t.name)}`:`${this.getTypeName(t.name)}`}getEnvironmentsTypeReference(t){return na.reference({name:`${this.namespaceExport}Environment`,importFrom:this.getModuleImport(),memberName:this.getTypeName(t)})}formatOriginalPropertyName(t){return t.includes("-")?`"${t}"`:t}};function RDB({config:e,customConfig:t}){return D4h({generatorConfig:e,isPackagePrivate:t?.private??!1})?.packageName??e.organization}var nxh="client",axh="main",zDB={type:"primitive",value:"STRING"},r0u=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig})}async generateSnippetAst({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return na.codeblock(i=>{i.writeNode(na.function_({name:axh,async:!0,parameters:[],body:na.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})})),i.writeNodeStatement(na.invokeFunction({function_:na.reference({name:axh}),arguments_:[]}))})}constructClient({endpoint:t,snippet:r}){return na.variable({name:nxh,const:!0,initializer:na.instantiateClass({class_:na.reference({name:this.context.getRootClientName(),importFrom:this.context.getModuleImport()}),arguments_:[this.getConstructorArgs({endpoint:t,snippet:r})]})})}getConstructorArgs({endpoint:t,snippet:r}){let i=[],n=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return n.length>0&&i.push(...n),t.auth!=null&&(r.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Wr.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(So.PathParameters),this.context.ir.pathParameters!=null&&i.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(So.Headers),this.context.ir.headers!=null&&r.headers!=null&&i.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),i.length===0?na.TypeLiteral.nop():na.TypeLiteral.object({fields:i})}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let i=this.getEnvironmentValue({baseUrl:t,environment:r});return i==null?[]:[{name:"environment",value:i}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Wr.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return na.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let i=this.context.getEnvironmentTypeReferenceFromID(r);if(i==null){this.context.errors.add({severity:Wr.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return na.TypeLiteral.reference(i)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?na.TypeLiteral.object({fields:Object.entries(r).map(([i,n])=>({name:i,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:zDB,value:n})}))}):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):(this.addWarning("The TypeScript SDK v2 Generator does not support Inferred auth scheme yet"),[]);default:de(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Wr.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Wr.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:na.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),value:na.TypeLiteral.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:na.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:na.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:na.TypeLiteral.string(r.clientSecret)}]}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(a)}return i}getConstructorHeaderArg({header:t,value:r}){let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!na.TypeLiteral.isNop(i))return{name:this.context.getPropertyName(t.name.name),value:i}}callMethod({endpoint:t,snippet:r}){return na.invokeMethod({on:na.reference({name:nxh}),method:this.getMethod({endpoint:t}),async:!0,arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}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:de(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(So.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(So.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 this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:de(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Wr.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),na.TypeLiteral.nop()):na.TypeLiteral.blob(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let i=[],{inlinePathParameters:n,inlineFileProperties:a}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!1,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!1};this.context.errors.scope(So.PathParameters);let o=[];t.pathParameters!=null&&o.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(So.RequestBody);let c=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:n})||i.push(...o.map(d=>d.value)),a||i.push(...c.fileFields.map(d=>d.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:n,inlineFileProperties:a})&&i.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:n})?o:[],filePropertyInfo:c})),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(So.QueryParameters);let o=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...u,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(So.Headers);let d=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...u,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(So.RequestBody);let s=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];return this.context.errors.unscope(),na.TypeLiteral.object({fields:[...i,...o,...d,...s]})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:i});default:de(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:de(t)}}getInlinedRequestBodyPropertyObjectFields({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.dynamicTypeLiteralMapper.convert({...a,convertOpts:{isForRequest:!0}})});return i}getPathParameters({namedParameters:t,snippet:r}){let i=[],n=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...a,convertOpts:{isForRequest:!0}})});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var Mio=class extends Hq{constructor({ir:t,config:r}){super(new t0u({ir:t,config:r}))}async generate(t){return super.generate(t)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new r0u({context:t})}};var n0u=require("fs/promises"),oxh=se(require("path"),1);var i0u=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,i){this.context=t,this.ir=r,this.generatorConfig=i,this.dynamicSnippetsGenerator=new Mio({ir:MU(this.ir),config:this.buildGeneratorConfig(this.generatorConfig)})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[i,n]of r.entries())try{let a=SU(n);if(a==null)continue;let o=await this.dynamicSnippetsGenerator.generate(a),c=this.getTestFilePath({outputDir:t,idx:i});await(0,n0u.mkdir)(oxh.default.dirname(c),{recursive:!0}),await(0,n0u.writeFile)(c,o.snippet)}catch(a){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(n.endpoint)}: ${a}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return ot(t,Pe.of(`src/dynamic-snippets/example${r}/snippet.ts`))}buildGeneratorConfig(t){let r=t.output.mode;if(r.type!=="github")throw new Error("GitHub output mode is required for TypeScript dynamic snippet tests");let i=r.publishInfo;if(!i||i.type!=="npm")throw new Error("NPM publish info is required for TypeScript dynamic snippet tests");return{...t,output:{...t.output,mode:{...r,publishInfo:{...i,packageName:"../.."}}}}}};var a0u=class e{context;testSuite;static GENERATORS={csharp:{generator:Mju},go:{generator:zju},java:{generator:Hju},php:{generator:kju},typescript:{generator:i0u,unstable:!0},python:{generator:uwu,unstable:!0},ruby:{generator:bwu},rust:{generator:Mwu},swift:{generator:Hwu}};constructor(t,r){this.context=t,this.testSuite=r}async generateTests({outputDir:t,language:r,skipUnstable:i}){let n=e.GENERATORS[r];if(n==null||n.unstable&&i){this.context.logger.debug(`Skipping dynamic snippets test generation for language "${r}"`);return}return new n.generator(this.context,this.testSuite.ir,this.testSuite.config).generateTests({outputDir:t,requests:this.testSuite.requests})}};async function uxh({ir:e,config:t}){if(e.dynamic==null)throw new Error("Internal error; dynamic IR is not available");return{ir:e.dynamic,config:t,requests:Object.values(e.dynamic.endpoints).flatMap(r=>(r.examples??[]).map(i=>({...i,baseUrl:"https://api.fern.com"})))}}async function sxh({context:e,ir:t,config:r,language:i,outputDir:n,skipUnstable:a}){let o=await uxh({ir:t,config:r});return new a0u(e,o).generateTests({language:i,outputDir:n,skipUnstable:a})}var NOE=se(on(),1),K2n=require("fs/promises"),F3a=se(require("path"),1),N3a=require("path"),FOE=se(VQ(),1);var cxh=se(require("path"),1);async function o0u({schema:e,value:t,context:r,filepathBeingParsed:i}){let n=await e.safeParseAsync(t);if(n.success)return n.data;let a=n.error.errors.map(c=>{let d=c.path.length>0?`${c.message} at "${NDB(c.path)}"`:c.message;return V8t({content:d,prefix:" - "})}),o=[`Failed to parse file: ${cxh.default.relative(process.cwd(),i)}`,...a].join(`
|
|
1587
|
-
`);return r.failAndThrow(o)}function NDB(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var lxh=se(require("path"),1),FDB={dependencies:{}};async function fxh({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return FDB;let i={};for(let[n,a]of Object.entries(t.dependencies))if(UDB(a)){let o=mr.of(lxh.default.join(e,a));await ni(o)?i[n]={type:"local",absoluteFilepath:o,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${o}`)}else{let c=n.substring(1).split("/"),d=c[0],s=c[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===qA.Failure&&r.failAndThrow(),{dependencies:i}}var QDB=/^\.\.\/.*$/;function UDB(e){return QDB.test(e)}var pxh=require("fs/promises");var dxh=It.object({dependencies:It.record(It.string(),It.string())});async function _xh({absolutePathToWorkspace:e,context:t}){let r=ot(e,Pe.of(dY_));if(!await ni(r))return;let i=await(0,pxh.readFile)(r),n=qi.load(i.toString());return await o0u({schema:dxh,value:n,context:t,filepathBeingParsed:r})}async function Utl({absolutePathToWorkspace:e,context:t}){let r=await _xh({absolutePathToWorkspace:e,context:t});return fxh({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}iHo();function hxh(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=s0u(e);switch(r){case"dark":return{type:"dark",...u0u(e,t,"dark")};case"light":return{type:"light",...u0u(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:u0u(e,t,"dark"),light:u0u(e,t,"light")};default:de(r)}}function s0u({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return du(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return du(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return du(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function u0u(e,t,r){let i=vya(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??du.random(),n=vya(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:vya(e.border,t,"border",r)?.toRgb(),sidebarBackground:vya(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:vya(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:vya(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function Dio(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function vya(e,t,r,i){let n=Dio(e,r,i);if(n==null)return;let a=du(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}bE();var S0u=require("fs/promises");var U6h=se(require("path"),1);var bxh=require("fs/promises");var yxh=100;async function LDB({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,bxh.readFile)(i,"utf-8");return[LQ(t,i),n]}));return Object.fromEntries(r)}async function vxh({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=yxh){let n=e.slice(i,i+yxh),a=await LDB({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function l0u({landingPage:e,navigation:t}){return ISe([e?.absolutePath,...VDB(t)])}function VDB(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>c0u({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(i=>c0u({item:i}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>c0u({item:t}));case"versioned":return e.versions.flatMap(t=>l0u({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:l0u({landingPage:t.landingPage,navigation:t.navigation}));default:de(e)}}function c0u({item:e}){switch(e.type){case"apiSection":return ISe([e.overviewAbsolutePath,...e.navigation.flatMap(t=>gxh({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return ISe([e.overviewAbsolutePath,...e.contents.flatMap(t=>c0u({item:t}))]);case"changelog":return e.changelog;case"pythonDocsSection":return[];default:de(e)}}function gxh({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?ISe([e.overviewAbsolutePath,...e.contents.flatMap(t=>gxh({item:t}))]):[]}var irl=require("fs/promises"),F6h=se(pAe(),1);function A0u({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function P0u({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function eqB({absolutePath:e,readFileFn:t=(r,i)=>(0,irl.readFile)(r,i)}){try{let r=await t(e,"utf-8"),{data:i}=(0,F6h.default)(r);if(i.position==null)return;let n=typeof i.position=="string"?parseFloat(i.position):i.position;return typeof n=="number"&&Number.isFinite(n)?n:void 0}catch{return}}async function nrl({directoryPath:e,getDir:t=jC,readFileFn:r=(i,n)=>(0,irl.readFile)(i,n)}){let i=await t(e),n=i.filter(u=>u.type==="file"&&(u.name.endsWith(".md")||u.name.endsWith(".mdx"))),a=i.filter(u=>u.type==="directory"),o=await Promise.all(n.map(u=>eqB({absolutePath:u.absolutePath,readFileFn:r}))),c=n.map(u=>({type:"page",title:P0u({name:u.name}),absolutePath:u.absolutePath,slug:A0u({name:u.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),d=await Promise.all(a.map(async u=>{let f=await nrl({directoryPath:u.absolutePath,getDir:t,readFileFn:r});return{type:"section",title:P0u({name:u.name}),slug:A0u({name:u.name}),icon:void 0,contents:f,collapsed:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0}})),s=[...c.map((u,f)=>({item:u,title:u.type==="page"?u.title:"",position:o[f]})),...d.map(u=>({item:u,title:u.type==="section"?u.title:"",position:void 0}))];return s.sort((u,f)=>{let p=typeof u.position=="number",_=typeof f.position=="number";if(p&&!_)return-1;if(!p&&_)return 1;if(typeof u.position=="number"&&typeof f.position=="number"){let h=u.position-f.position;return h!==0?h:u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}return u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}),s.map(u=>u.item)}function tqB(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function JD(e,t){if(e)return tqB(e)?Jq(e,t):e}async function crl({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:o,products:c,versions:d,navigation:s,navbarLinks:u,footerLinks:f,defaultLanguage:p,metadata:_,redirects:h,logo:y,favicon:b,backgroundImage:v,colors:O,typography:m,layout:g,integrations:A,css:j,js:M,aiChat:w,aiSearch:E,pageActions:B,experimental:q}=e,R=Fio(e.landingPage,r),T=_qB({tabs:o,products:c,versions:d,navigation:s,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),K=T.then(Ue=>vxh({files:l0u({navigation:Ue,landingPage:R}),absolutePathToFernFolder:t})),H=rqB(y,r),z=Jq(b,r),W=iqB(v,r),Oe=m!=null?hqB({rawTypography:m,absoluteFilepathToDocsConfig:r}):void 0,Ae=nqB(j,r),Q=uqB(M,r),U=RqB(_,r),[ce,ae,fe,ve,re,X]=await Promise.all([T,K,Oe,Ae,Q,U]);return{title:a,instances:n,roles:e.roles,pages:ae,landingPage:R,navigation:ce,navbarLinks:qqB(u,r),footerLinks:TqB(f),defaultLanguage:p,languages:e.languages,announcement:e.announcement,metadata:X,redirects:h?.map(Ue=>({...Ue,permanent:Ue?.permanent})),logo:H,favicon:z,backgroundImage:W,colors:hxh(O,i),typography:fe,layout:pqB(g),settings:dqB(e.settings),theme:fqB(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},integrations:{...A,intercom:A?.intercom?A.intercom:void 0},css:ve,js:re,aiChatConfig:E??w,pageActions:sqB(B,r),header:void 0,footer:void 0,experimental:q}}function rqB(e,t){return e!=null?{dark:Jq(e.dark,t),light:Jq(e.light,t),height:e.height,href:e.href!=null?Jr.Url(e.href):void 0,rightText:e.rightText}:void 0}function iqB(e,t){if(e!=null)if(typeof e=="string"){let r=Jq(e,t);return{dark:r,light:r}}else{let r=Jq(e.dark,t),i=Jq(e.light,t);return{dark:r,light:i}}}async function nqB(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,S0u.readFile)(Jq(i,t))).toString()))}}function aqB(e){return Object.hasOwn(e,"url")}function oqB(e){return Object.hasOwn(e,"path")}async function uqB(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:Jq(a,t)}):aqB(a)?r.push({strategy:a.strategy,url:Jr.Url(a.url)}):oqB(a)&&i.push({absolutePath:Jq(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function sqB(e,t){return e==null?void 0:{default:e.default!=null?cqB(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(i=>lqB(i,t))}}}function cqB(e){switch(e){case"copy-page":return Jr.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return Jr.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return Jr.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return Jr.docs.v1.commons.PageActionOption.OpenAi;case"claude":return Jr.docs.v1.commons.PageActionOption.Claude;case"cursor":return Jr.docs.v1.commons.PageActionOption.Cursor;case"vscode":return Jr.docs.v1.commons.PageActionOption.Vscode;default:de(e)}}function lqB(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:JD(e.icon,t),default:e.default}}function fqB(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function dqB(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function pqB(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:j0u(e.pageWidth),contentWidth:j0u(e.contentWidth),sidebarWidth:j0u(e.sidebarWidth),headerHeight:j0u(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?Jr.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?Jr.docs.v1.commons.SearchbarPlacement.HeaderTabs:Jr.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?Jr.docs.v1.commons.SwitcherPlacement.Header:Jr.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?Jr.docs.v1.commons.TabsPlacement.Header:Jr.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?Jr.docs.v1.commons.ContentAlignment.Left:Jr.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?Jr.docs.v1.commons.HeaderPosition.Absolute:Jr.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function j0u(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function Q6h({versions:e,absolutePathToFernFolder:t,context:r}){let i=[];for(let n of e){let a=xo(t,n.path),o=qi.load((await(0,S0u.readFile)(a)).toString()),c=[],d=qSe(o,[],c);c.length>0&&r.logger.warn(`Version file ${n.path} contained null/undefined sections that were ignored: ${c.map(f=>f.join(".")).join(", ")}`);let s=jZ.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(d),u=await srl({tabs:s.tabs,rawNavigationConfig:s.navigation,absolutePathToFernFolder:t,absolutePathToConfig:a,context:r});i.push({landingPage:Fio(s.landingPage,a),version:n.displayName,navigation:u,availability:n.availability,slug:n.slug,hidden:n.hidden,viewers:Z5(n.viewers),orphaned:n.orphaned,featureFlags:X5(n.featureFlag),announcement:n.announcement})}return{type:"versioned",versions:i}}async function _qB({tabs:e,products:t,versions:r,navigation:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o}){if(i!=null)return await srl({tabs:e,rawNavigationConfig:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o});if(t!=null){let c=[];for(let d of t){let s=d.image!=null?xo(n,d.image):void 0;if("path"in d){let u,f=xo(n,d.path),p=qi.load((await(0,S0u.readFile)(f)).toString()),_=[],h=qSe(p,[],_);_.length>0&&o.logger.warn(`Product file ${d.path} contained null/undefined sections that were ignored: ${_.map(b=>b.join(".")).join(", ")}`);let y=jZ.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);d.versions!=null&&d.versions.length>0?u=await Q6h({versions:d.versions,absolutePathToFernFolder:n,context:o}):u=await srl({tabs:y.tabs,rawNavigationConfig:y.navigation,absolutePathToFernFolder:n,absolutePathToConfig:f,context:o}),c.push({type:"internal",landingPage:Fio(y.landingPage,f),product:d.displayName,navigation:u,slug:d.slug,subtitle:d.subtitle,icon:JD(d.icon,a)||"fa-solid fa-code",image:s,viewers:Z5(d.viewers),orphaned:d.orphaned,featureFlags:X5(d.featureFlag),announcement:d.announcement})}else if("href"in d&&d.href!=null)c.push({type:"external",product:d.displayName,href:d.href,target:d.target,subtitle:d.subtitle,icon:JD(d.icon,a)||"fa-solid fa-code",image:s,viewers:Z5(d.viewers),orphaned:d.orphaned,featureFlags:X5(d.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await Q6h({versions:r,absolutePathToFernFolder:n,context:o});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function X5(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function hqB({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await arl({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await arl({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await arl({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function arl({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await yqB(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function yqB(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:Jq(i.path,t),weight:bqB(i.weight),style:i.style})))}function bqB(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function vqB({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(CqB(t)){let o=await Promise.all(t.variants.map(async c=>{let d=await Promise.all(c.layout.map(s=>E0u({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:c.title,subtitle:c.subtitle,icon:JD(c.icon,i),layout:d,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:Z5(c.viewers),orphaned:c.orphaned,featureFlags:X5(c.featureFlag)}}));return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"variants",variants:o},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)}}if(IqB(t)){let o=await Promise.all(t.layout.map(c=>E0u({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:o},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href,target:a.target},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await _3(Jq(a.changelog,i),"{md,mdx}")},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)};de(a)}async function srl({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return BqB(t)?{type:"tabbed",items:await Promise.all(t.map(o=>vqB({tabs:e,item:o,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>E0u({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var gqB="Changelog";async function OqB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){let n=Jq(e.folder,r);await ni(n)||i.failAndThrow(`Folder not found: ${e.folder}`);let a=await nrl({directoryPath:n}),o=U6h.default.basename(n),c=e.title??P0u({name:o}),d=e.slug??A0u({name:o});return{type:"section",title:c,icon:JD(e.icon,r),contents:a,slug:d,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:void 0,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability}}async function E0u({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(L6h(e))return Fio(e,r);if(AqB(e))return{type:"section",title:e.section,icon:JD(e.icon,r),contents:await Promise.all(e.contents.map(n=>E0u({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:Jq(e.path,r),viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability};if(PqB(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:JD(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:Qio(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?mqB({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(n=>w0u(n,r))??[],overviewAbsolutePath:Jq(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)};if(V6h(e))return{type:"link",text:e.link,url:e.href,icon:JD(e.icon,r),target:e.target};if(jqB(e))return{type:"changelog",changelog:await _3(Jq(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:JD(e.icon,r),title:e.title??gqB,slug:e.slug,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)};if(wqB(e))return await OqB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i});if(EqB(e))return{type:"pythonDocsSection",githubUrl:e.pythonDocs,title:e.title??void 0,slug:e.slug??void 0};de(e)}function Fio(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Jq(e.path,t),slug:e.slug,icon:JD(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability}}function w0u(e,t){return typeof e=="string"?[{type:"item",value:e}]:L6h(e)?[Fio(e,t)]:V6h(e)?[{type:"link",text:e.link,url:e.href,icon:JD(e.icon,t),target:e.target}]:SqB(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:Jq(e.summary,t),contents:e.contents?.flatMap(r=>w0u(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,availability:e.availability,icon:JD(e.icon,t),playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)}]:MqB(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:JD(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)}]:Object.entries(e).map(([r,i])=>DqB(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:Jq(i.summary,t),contents:i.contents?.flatMap(n=>w0u(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:JD(i.icon,t),playground:i.playground,availability:i.availability,viewers:Z5(i.viewers),orphaned:i.orphaned,featureFlags:X5(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>w0u(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function mqB({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function L6h(e){return Wl(e)&&typeof e.page=="string"&&typeof e.path=="string"}function AqB(e){return e.section!=null}function PqB(e){return e.api!=null}function V6h(e){return jZ.RawSchemas,Wl(e)&&typeof e.link=="string"&&typeof e.href=="string"}function jqB(e){return Wl(e)&&typeof e.changelog=="string"}function wqB(e){return Wl(e)&&typeof e.folder=="string"}function EqB(e){return Wl(e)&&typeof e.pythonDocs=="string"}function SqB(e){return Wl(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function MqB(e){return Wl(e)&&typeof e.endpoint=="string"}function DqB(e){return!Array.isArray(e)}function Jq(e,t){if(e!=null)return xo(sn(t),e)}function BqB(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function IqB(e){return"layout"in e&&Array.isArray(e.layout)}function CqB(e){return"variants"in e&&Array.isArray(e.variants)}function qqB(e,t){return e?.map(r=>{if(r.type==="github"){let n=r.value;return typeof n=="string"?{type:"github",url:Jr.Url(n),viewers:void 0,target:void 0}:{type:"github",url:Jr.Url(n.url),viewers:orl(n.viewers),target:n.target}}let i=orl(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:JD(r.icon,t),rightIcon:JD(r.rightIcon,t),rounded:r.rounded,viewers:i,links:r.links?.map(n=>({href:n.href,target:n.target,url:Jr.Url(n.url??n.href??"/"),text:n.text,icon:JD(n.icon,t),rightIcon:JD(n.rightIcon,t),rounded:n.rounded,viewers:orl(n.viewers)}))??[]}:{type:r.type,text:r.text,url:Jr.Url(r.href??r.url??"/"),target:r.target,icon:JD(r.icon,t),rightIcon:JD(r.rightIcon,t),rounded:r.rounded,viewers:i}})}function orl(e){if(e!=null)return Array.isArray(e)?e.map(t=>Jr.RoleId(t)):[Jr.RoleId(e)]}function TqB(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:Jr.Url(i)})}),t.length!==0)return t}async function RqB(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await url(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await url(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await url(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function url(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Jq(e,t);return await ni(r)?{type:"filepath",value:r}:{type:"url",value:e}}function Z5(e){if(e!=null){if(typeof e=="string")return[Jr.RoleId(e)];if(e.length!==0)return e.map(Jr.RoleId)}}function Qio(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}var x6h=require("fs/promises");var W6h=It.strictObject({organization:It.string(),version:It.string()});async function _Ae({directory:e,context:t}){let r=ot(e,Pe.of(IC)),i=await(0,x6h.readFile)(r),n=JSON.parse(i.toString()),a=await o0u({schema:W6h,value:n,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:a,organization:a.organization,version:a.version}}var P={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",GO_FIBER:"fernapi/fern-go-fiber",RUBY_MODEL:"fernapi/fern-ruby-model",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var Uio={[P.JAVA]:{version:"2.38.1"},[P.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[P.JAVA_MODEL]:{version:"1.0.0"},[P.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[P.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[P.TYPESCRIPT]:{version:"0.0.247"},[P.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.PYTHON_PYDANTIC]:{version:"1.4.7"},[P.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[P.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[P.GO_FIBER]:{version:"0.23.5"},[P.GO_MODEL]:{version:"0.23.5"},[P.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[P.RUBY_MODEL]:{version:"0.0.8"},[P.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[P.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[P.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[P.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[P.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[P.CSHARP_MODEL]:{version:"0.0.1"},[P.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[P.SWIFT_MODEL]:{version:"0.0.0"},[P.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[P.PHP_MODEL]:{version:"0.0.0"},[P.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[P.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[P.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var G6h="fernapi";function IU(e){return e.includes("/")?e:`${G6h}/${e}`}function lrl(e){let t=`${G6h}/`;return e.startsWith(t)?e.slice(t.length):e}function oen(e,t){let r=zqB(e);return r??t.failAndThrow("Unrecognized generator: "+e)}function zqB(e){if(e=IU(e),NqB(e))return e}function NqB(e){return Object.values(P).includes(e)}var M0u=se(KYa(),1),H6h=se(OX(),1);async function l6t({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:i,includeMajor:n,context:a}){let o=H6h.default.parse(i),c=new M0u.FernRegistryClient({environment:"https://registry.buildwithfern.com"});a?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${n}, prior version: ${o}`);let d={generator:FqB(e,a),releaseTypes:[r??M0u.FernRegistry.generators.ReleaseType.Ga],cliVersion:t==="0.0.0"?void 0:t};!n&&o!=null&&(d.generatorMajorVersion=o.major);let s=await c.generators.versions.getLatestGeneratorRelease(d);if(s.ok)return s.body.version}function FqB(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-go-fiber":return"go-fiber";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-ruby-model":return"ruby-model";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function K6h({generatorsConfiguration:e,groupName:t=e[Ki.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:i}){if(t==null)return r.failAndThrow("No group specified.");let n=e.groups??={},a=n[t];if(a==null){let o=n[t]??={generators:[]};await i(o,t)}else await i(a,t);return e}async function frl({generatorName:e,generatorsConfiguration:t,groupName:r=t[Rca],context:i,cliVersion:n}){let a=oen(e,i),o=lrl(a),c=Uio[a];return await K6h({generatorsConfiguration:t,groupName:r,context:i,update:async d=>{d.generators.some(s=>IU(s.name)===a)&&i.failAndThrow(`${e} is already installed in group ${r}.`),d.generators.push({name:o,...c,version:await l6t({cliVersion:n,generatorName:a,context:i,channel:void 0})??c.version})}})}var f6t=require("fs/promises"),H0n=se(require("path"),1);var DGh=require("buffer"),L0u=se(J6h(),1),F0u=se(LD(),1),g9h=require("child_process"),rHh=se(prl(),1),pHh=require("path"),Dya=se(prl(),1),BHh=require("events"),Trl=Object.defineProperty,GqB=Object.getOwnPropertyDescriptor,Rrl=Object.getOwnPropertyNames,HqB=Object.prototype.hasOwnProperty,Ua=(e,t)=>function(){return e&&(t=(0,e[Rrl(e)[0]])(e=0)),t},KqB=(e,t)=>function(){return t||(0,e[Rrl(e)[0]])((t={exports:{}}).exports,t),t.exports},Xq=(e,t)=>{for(var r in t)Trl(e,r,{get:t[r],enumerable:!0})},$qB=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rrl(t))!HqB.call(e,n)&&n!==r&&Trl(e,n,{get:()=>t[n],enumerable:!(i=GqB(t,n))||i.enumerable});return e},FC=e=>$qB(Trl({},"__esModule",{value:!0}),e);function JqB(...e){let t=new String(e);return U0u.set(t,e),t}function R0u(e){return e instanceof String&&U0u.has(e)}function Y6h(e){return U0u.get(e)||[]}var U0u,xio=Ua({"src/lib/args/pathspec.ts"(){"use strict";U0u=new WeakMap}}),d8i,sen=Ua({"src/lib/errors/git-error.ts"(){"use strict";d8i=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),Gio,Iya=Ua({"src/lib/errors/git-response-error.ts"(){"use strict";sen(),Gio=class extends d8i{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),SGh,MGh=Ua({"src/lib/errors/task-configuration-error.ts"(){"use strict";sen(),SGh=class extends d8i{constructor(e){super(void 0,e)}}}});function BGh(e){return typeof e!="function"?G0n:e}function IGh(e){return typeof e=="function"&&e!==G0n}function CGh(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function qGh(e,t=0){return TGh(e)&&e.length>t?e[t]:void 0}function x0n(e,t=0){if(TGh(e)&&e.length>t)return e[e.length-1-t]}function TGh(e){return G0u(e)}function Hio(e="",t=!0,r=`
|
|
1587
|
+
`);return r.failAndThrow(o)}function NDB(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var lxh=se(require("path"),1),FDB={dependencies:{}};async function fxh({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return FDB;let i={};for(let[n,a]of Object.entries(t.dependencies))if(UDB(a)){let o=mr.of(lxh.default.join(e,a));await ni(o)?i[n]={type:"local",absoluteFilepath:o,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${o}`)}else{let c=n.substring(1).split("/"),d=c[0],s=c[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===qA.Failure&&r.failAndThrow(),{dependencies:i}}var QDB=/^\.\.\/.*$/;function UDB(e){return QDB.test(e)}var pxh=require("fs/promises");var dxh=It.object({dependencies:It.record(It.string(),It.string())});async function _xh({absolutePathToWorkspace:e,context:t}){let r=ot(e,Pe.of(dY_));if(!await ni(r))return;let i=await(0,pxh.readFile)(r),n=qi.load(i.toString());return await o0u({schema:dxh,value:n,context:t,filepathBeingParsed:r})}async function Utl({absolutePathToWorkspace:e,context:t}){let r=await _xh({absolutePathToWorkspace:e,context:t});return fxh({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}iHo();function hxh(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=s0u(e);switch(r){case"dark":return{type:"dark",...u0u(e,t,"dark")};case"light":return{type:"light",...u0u(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:u0u(e,t,"dark"),light:u0u(e,t,"light")};default:de(r)}}function s0u({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return du(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return du(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return du(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function u0u(e,t,r){let i=vya(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??du.random(),n=vya(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:vya(e.border,t,"border",r)?.toRgb(),sidebarBackground:vya(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:vya(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:vya(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function Dio(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function vya(e,t,r,i){let n=Dio(e,r,i);if(n==null)return;let a=du(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}bE();var S0u=require("fs/promises");var U6h=se(require("path"),1);var bxh=require("fs/promises");var yxh=100;async function LDB({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,bxh.readFile)(i,"utf-8");return[LQ(t,i),n]}));return Object.fromEntries(r)}async function vxh({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=yxh){let n=e.slice(i,i+yxh),a=await LDB({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function l0u({landingPage:e,navigation:t}){return ISe([e?.absolutePath,...VDB(t)])}function VDB(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>c0u({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(i=>c0u({item:i}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>c0u({item:t}));case"versioned":return e.versions.flatMap(t=>l0u({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:l0u({landingPage:t.landingPage,navigation:t.navigation}));default:de(e)}}function c0u({item:e}){switch(e.type){case"apiSection":return ISe([e.overviewAbsolutePath,...e.navigation.flatMap(t=>gxh({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return ISe([e.overviewAbsolutePath,...e.contents.flatMap(t=>c0u({item:t}))]);case"changelog":return e.changelog;case"pythonDocsSection":return[];default:de(e)}}function gxh({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?ISe([e.overviewAbsolutePath,...e.contents.flatMap(t=>gxh({item:t}))]):[]}var irl=require("fs/promises"),F6h=se(pAe(),1);function A0u({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function P0u({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function eqB({absolutePath:e,readFileFn:t=(r,i)=>(0,irl.readFile)(r,i)}){try{let r=await t(e,"utf-8"),{data:i}=(0,F6h.default)(r);if(i.position==null)return;let n=typeof i.position=="string"?parseFloat(i.position):i.position;return typeof n=="number"&&Number.isFinite(n)?n:void 0}catch{return}}async function nrl({directoryPath:e,getDir:t=jC,readFileFn:r=(i,n)=>(0,irl.readFile)(i,n)}){let i=await t(e),n=i.filter(u=>u.type==="file"&&(u.name.toLowerCase().endsWith(".md")||u.name.toLowerCase().endsWith(".mdx"))),a=i.filter(u=>u.type==="directory"),o=await Promise.all(n.map(u=>eqB({absolutePath:u.absolutePath,readFileFn:r}))),c=n.map(u=>({type:"page",title:P0u({name:u.name}),absolutePath:u.absolutePath,slug:A0u({name:u.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),d=await Promise.all(a.map(async u=>{let f=await nrl({directoryPath:u.absolutePath,getDir:t,readFileFn:r}),p=f.find(h=>h.type==="page"&&(h.slug==="index"||h.absolutePath.toLowerCase().endsWith("/index.mdx")||h.absolutePath.toLowerCase().endsWith("/index.md"))),_=p?f.filter(h=>h!==p):f;return{type:"section",title:P0u({name:u.name}),slug:A0u({name:u.name}),icon:void 0,contents:_,collapsed:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:p?.type==="page"?p.absolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0}})),s=[...c.map((u,f)=>({item:u,title:u.type==="page"?u.title:"",position:o[f]})),...d.map(u=>({item:u,title:u.type==="section"?u.title:"",position:void 0}))];return s.sort((u,f)=>{let p=typeof u.position=="number",_=typeof f.position=="number";if(p&&!_)return-1;if(!p&&_)return 1;if(typeof u.position=="number"&&typeof f.position=="number"){let h=u.position-f.position;return h!==0?h:u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}return u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}),s.map(u=>u.item)}function tqB(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function JD(e,t){if(e)return tqB(e)?Jq(e,t):e}async function crl({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:o,products:c,versions:d,navigation:s,navbarLinks:u,footerLinks:f,defaultLanguage:p,metadata:_,redirects:h,logo:y,favicon:b,backgroundImage:v,colors:O,typography:m,layout:g,integrations:A,css:j,js:M,aiChat:w,aiSearch:E,pageActions:B,experimental:q}=e,R=Fio(e.landingPage,r),T=_qB({tabs:o,products:c,versions:d,navigation:s,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),K=T.then(Ue=>vxh({files:l0u({navigation:Ue,landingPage:R}),absolutePathToFernFolder:t})),H=rqB(y,r),z=Jq(b,r),W=iqB(v,r),Oe=m!=null?hqB({rawTypography:m,absoluteFilepathToDocsConfig:r}):void 0,Ae=nqB(j,r),Q=uqB(M,r),U=RqB(_,r),[ce,ae,fe,ve,re,X]=await Promise.all([T,K,Oe,Ae,Q,U]);return{title:a,instances:n,roles:e.roles,pages:ae,landingPage:R,navigation:ce,navbarLinks:qqB(u,r),footerLinks:TqB(f),defaultLanguage:p,languages:e.languages,announcement:e.announcement,metadata:X,redirects:h?.map(Ue=>({...Ue,permanent:Ue?.permanent})),logo:H,favicon:z,backgroundImage:W,colors:hxh(O,i),typography:fe,layout:pqB(g),settings:dqB(e.settings),theme:fqB(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},integrations:{...A,intercom:A?.intercom?A.intercom:void 0},css:ve,js:re,aiChatConfig:E??w,pageActions:sqB(B,r),header:void 0,footer:void 0,experimental:q}}function rqB(e,t){return e!=null?{dark:Jq(e.dark,t),light:Jq(e.light,t),height:e.height,href:e.href!=null?Jr.Url(e.href):void 0,rightText:e.rightText}:void 0}function iqB(e,t){if(e!=null)if(typeof e=="string"){let r=Jq(e,t);return{dark:r,light:r}}else{let r=Jq(e.dark,t),i=Jq(e.light,t);return{dark:r,light:i}}}async function nqB(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,S0u.readFile)(Jq(i,t))).toString()))}}function aqB(e){return Object.hasOwn(e,"url")}function oqB(e){return Object.hasOwn(e,"path")}async function uqB(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:Jq(a,t)}):aqB(a)?r.push({strategy:a.strategy,url:Jr.Url(a.url)}):oqB(a)&&i.push({absolutePath:Jq(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function sqB(e,t){return e==null?void 0:{default:e.default!=null?cqB(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(i=>lqB(i,t))}}}function cqB(e){switch(e){case"copy-page":return Jr.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return Jr.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return Jr.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return Jr.docs.v1.commons.PageActionOption.OpenAi;case"claude":return Jr.docs.v1.commons.PageActionOption.Claude;case"cursor":return Jr.docs.v1.commons.PageActionOption.Cursor;case"vscode":return Jr.docs.v1.commons.PageActionOption.Vscode;default:de(e)}}function lqB(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:JD(e.icon,t),default:e.default}}function fqB(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function dqB(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function pqB(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:j0u(e.pageWidth),contentWidth:j0u(e.contentWidth),sidebarWidth:j0u(e.sidebarWidth),headerHeight:j0u(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?Jr.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?Jr.docs.v1.commons.SearchbarPlacement.HeaderTabs:Jr.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?Jr.docs.v1.commons.SwitcherPlacement.Header:Jr.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?Jr.docs.v1.commons.TabsPlacement.Header:Jr.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?Jr.docs.v1.commons.ContentAlignment.Left:Jr.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?Jr.docs.v1.commons.HeaderPosition.Absolute:Jr.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function j0u(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function Q6h({versions:e,absolutePathToFernFolder:t,context:r}){let i=[];for(let n of e){let a=xo(t,n.path),o=qi.load((await(0,S0u.readFile)(a)).toString()),c=[],d=qSe(o,[],c);c.length>0&&r.logger.warn(`Version file ${n.path} contained null/undefined sections that were ignored: ${c.map(f=>f.join(".")).join(", ")}`);let s=jZ.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(d),u=await srl({tabs:s.tabs,rawNavigationConfig:s.navigation,absolutePathToFernFolder:t,absolutePathToConfig:a,context:r});i.push({landingPage:Fio(s.landingPage,a),version:n.displayName,navigation:u,availability:n.availability,slug:n.slug,hidden:n.hidden,viewers:Z5(n.viewers),orphaned:n.orphaned,featureFlags:X5(n.featureFlag),announcement:n.announcement})}return{type:"versioned",versions:i}}async function _qB({tabs:e,products:t,versions:r,navigation:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o}){if(i!=null)return await srl({tabs:e,rawNavigationConfig:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o});if(t!=null){let c=[];for(let d of t){let s=d.image!=null?xo(n,d.image):void 0;if("path"in d){let u,f=xo(n,d.path),p=qi.load((await(0,S0u.readFile)(f)).toString()),_=[],h=qSe(p,[],_);_.length>0&&o.logger.warn(`Product file ${d.path} contained null/undefined sections that were ignored: ${_.map(b=>b.join(".")).join(", ")}`);let y=jZ.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);d.versions!=null&&d.versions.length>0?u=await Q6h({versions:d.versions,absolutePathToFernFolder:n,context:o}):u=await srl({tabs:y.tabs,rawNavigationConfig:y.navigation,absolutePathToFernFolder:n,absolutePathToConfig:f,context:o}),c.push({type:"internal",landingPage:Fio(y.landingPage,f),product:d.displayName,navigation:u,slug:d.slug,subtitle:d.subtitle,icon:JD(d.icon,a)||"fa-solid fa-code",image:s,viewers:Z5(d.viewers),orphaned:d.orphaned,featureFlags:X5(d.featureFlag),announcement:d.announcement})}else if("href"in d&&d.href!=null)c.push({type:"external",product:d.displayName,href:d.href,target:d.target,subtitle:d.subtitle,icon:JD(d.icon,a)||"fa-solid fa-code",image:s,viewers:Z5(d.viewers),orphaned:d.orphaned,featureFlags:X5(d.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await Q6h({versions:r,absolutePathToFernFolder:n,context:o});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function X5(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function hqB({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await arl({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await arl({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await arl({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function arl({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await yqB(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function yqB(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:Jq(i.path,t),weight:bqB(i.weight),style:i.style})))}function bqB(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function vqB({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(CqB(t)){let o=await Promise.all(t.variants.map(async c=>{let d=await Promise.all(c.layout.map(s=>E0u({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:c.title,subtitle:c.subtitle,icon:JD(c.icon,i),layout:d,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:Z5(c.viewers),orphaned:c.orphaned,featureFlags:X5(c.featureFlag)}}));return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"variants",variants:o},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)}}if(IqB(t)){let o=await Promise.all(t.layout.map(c=>E0u({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:o},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href,target:a.target},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:JD(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await _3(Jq(a.changelog,i),"{md,mdx}")},viewers:Z5(a.viewers),orphaned:a.orphaned,featureFlags:X5(a.featureFlag)};de(a)}async function srl({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return BqB(t)?{type:"tabbed",items:await Promise.all(t.map(o=>vqB({tabs:e,item:o,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>E0u({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var gqB="Changelog";async function OqB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){let n=Jq(e.folder,r);await ni(n)||i.failAndThrow(`Folder not found: ${e.folder}`);let a=await nrl({directoryPath:n}),o=a.find(f=>f.type==="page"&&(f.slug==="index"||f.absolutePath.toLowerCase().endsWith("/index.mdx")||f.absolutePath.toLowerCase().endsWith("/index.md"))),c=o?a.filter(f=>f!==o):a,d=U6h.default.basename(n),s=e.title??P0u({name:d}),u=e.slug??A0u({name:d});return{type:"section",title:s,icon:JD(e.icon,r),contents:c,slug:u,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:o?.type==="page"?o.absolutePath:void 0,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability}}async function E0u({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(L6h(e))return Fio(e,r);if(AqB(e))return{type:"section",title:e.section,icon:JD(e.icon,r),contents:await Promise.all(e.contents.map(n=>E0u({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:Jq(e.path,r),viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability};if(PqB(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:JD(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:Qio(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?mqB({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(n=>w0u(n,r))??[],overviewAbsolutePath:Jq(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)};if(V6h(e))return{type:"link",text:e.link,url:e.href,icon:JD(e.icon,r),target:e.target};if(jqB(e))return{type:"changelog",changelog:await _3(Jq(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:JD(e.icon,r),title:e.title??gqB,slug:e.slug,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)};if(wqB(e))return await OqB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i});if(EqB(e))return{type:"pythonDocsSection",githubUrl:e.pythonDocs,title:e.title??void 0,slug:e.slug??void 0};de(e)}function Fio(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Jq(e.path,t),slug:e.slug,icon:JD(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag),availability:e.availability}}function w0u(e,t){return typeof e=="string"?[{type:"item",value:e}]:L6h(e)?[Fio(e,t)]:V6h(e)?[{type:"link",text:e.link,url:e.href,icon:JD(e.icon,t),target:e.target}]:SqB(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:Jq(e.summary,t),contents:e.contents?.flatMap(r=>w0u(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,availability:e.availability,icon:JD(e.icon,t),playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)}]:MqB(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:JD(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:Z5(e.viewers),orphaned:e.orphaned,featureFlags:X5(e.featureFlag)}]:Object.entries(e).map(([r,i])=>DqB(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:Jq(i.summary,t),contents:i.contents?.flatMap(n=>w0u(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:JD(i.icon,t),playground:i.playground,availability:i.availability,viewers:Z5(i.viewers),orphaned:i.orphaned,featureFlags:X5(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>w0u(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function mqB({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function L6h(e){return Wl(e)&&typeof e.page=="string"&&typeof e.path=="string"}function AqB(e){return e.section!=null}function PqB(e){return e.api!=null}function V6h(e){return jZ.RawSchemas,Wl(e)&&typeof e.link=="string"&&typeof e.href=="string"}function jqB(e){return Wl(e)&&typeof e.changelog=="string"}function wqB(e){return Wl(e)&&typeof e.folder=="string"}function EqB(e){return Wl(e)&&typeof e.pythonDocs=="string"}function SqB(e){return Wl(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function MqB(e){return Wl(e)&&typeof e.endpoint=="string"}function DqB(e){return!Array.isArray(e)}function Jq(e,t){if(e!=null)return xo(sn(t),e)}function BqB(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function IqB(e){return"layout"in e&&Array.isArray(e.layout)}function CqB(e){return"variants"in e&&Array.isArray(e.variants)}function qqB(e,t){return e?.map(r=>{if(r.type==="github"){let n=r.value;return typeof n=="string"?{type:"github",url:Jr.Url(n),viewers:void 0,target:void 0}:{type:"github",url:Jr.Url(n.url),viewers:orl(n.viewers),target:n.target}}let i=orl(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:JD(r.icon,t),rightIcon:JD(r.rightIcon,t),rounded:r.rounded,viewers:i,links:r.links?.map(n=>({href:n.href,target:n.target,url:Jr.Url(n.url??n.href??"/"),text:n.text,icon:JD(n.icon,t),rightIcon:JD(n.rightIcon,t),rounded:n.rounded,viewers:orl(n.viewers)}))??[]}:{type:r.type,text:r.text,url:Jr.Url(r.href??r.url??"/"),target:r.target,icon:JD(r.icon,t),rightIcon:JD(r.rightIcon,t),rounded:r.rounded,viewers:i}})}function orl(e){if(e!=null)return Array.isArray(e)?e.map(t=>Jr.RoleId(t)):[Jr.RoleId(e)]}function TqB(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:Jr.Url(i)})}),t.length!==0)return t}async function RqB(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await url(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await url(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await url(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function url(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Jq(e,t);return await ni(r)?{type:"filepath",value:r}:{type:"url",value:e}}function Z5(e){if(e!=null){if(typeof e=="string")return[Jr.RoleId(e)];if(e.length!==0)return e.map(Jr.RoleId)}}function Qio(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}var x6h=require("fs/promises");var W6h=It.strictObject({organization:It.string(),version:It.string()});async function _Ae({directory:e,context:t}){let r=ot(e,Pe.of(IC)),i=await(0,x6h.readFile)(r),n=JSON.parse(i.toString()),a=await o0u({schema:W6h,value:n,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:a,organization:a.organization,version:a.version}}var P={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",GO_FIBER:"fernapi/fern-go-fiber",RUBY_MODEL:"fernapi/fern-ruby-model",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var Uio={[P.JAVA]:{version:"2.38.1"},[P.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[P.JAVA_MODEL]:{version:"1.0.0"},[P.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[P.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[P.TYPESCRIPT]:{version:"0.0.247"},[P.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.PYTHON_PYDANTIC]:{version:"1.4.7"},[P.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[P.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[P.GO_FIBER]:{version:"0.23.5"},[P.GO_MODEL]:{version:"0.23.5"},[P.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[P.RUBY_MODEL]:{version:"0.0.8"},[P.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[P.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[P.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[P.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[P.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[P.CSHARP_MODEL]:{version:"0.0.1"},[P.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[P.SWIFT_MODEL]:{version:"0.0.0"},[P.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[P.PHP_MODEL]:{version:"0.0.0"},[P.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[P.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[P.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var G6h="fernapi";function IU(e){return e.includes("/")?e:`${G6h}/${e}`}function lrl(e){let t=`${G6h}/`;return e.startsWith(t)?e.slice(t.length):e}function oen(e,t){let r=zqB(e);return r??t.failAndThrow("Unrecognized generator: "+e)}function zqB(e){if(e=IU(e),NqB(e))return e}function NqB(e){return Object.values(P).includes(e)}var M0u=se(KYa(),1),H6h=se(OX(),1);async function l6t({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:i,includeMajor:n,context:a}){let o=H6h.default.parse(i),c=new M0u.FernRegistryClient({environment:"https://registry.buildwithfern.com"});a?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${n}, prior version: ${o}`);let d={generator:FqB(e,a),releaseTypes:[r??M0u.FernRegistry.generators.ReleaseType.Ga],cliVersion:t==="0.0.0"?void 0:t};!n&&o!=null&&(d.generatorMajorVersion=o.major);let s=await c.generators.versions.getLatestGeneratorRelease(d);if(s.ok)return s.body.version}function FqB(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-go-fiber":return"go-fiber";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-ruby-model":return"ruby-model";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function K6h({generatorsConfiguration:e,groupName:t=e[Ki.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:i}){if(t==null)return r.failAndThrow("No group specified.");let n=e.groups??={},a=n[t];if(a==null){let o=n[t]??={generators:[]};await i(o,t)}else await i(a,t);return e}async function frl({generatorName:e,generatorsConfiguration:t,groupName:r=t[Rca],context:i,cliVersion:n}){let a=oen(e,i),o=lrl(a),c=Uio[a];return await K6h({generatorsConfiguration:t,groupName:r,context:i,update:async d=>{d.generators.some(s=>IU(s.name)===a)&&i.failAndThrow(`${e} is already installed in group ${r}.`),d.generators.push({name:o,...c,version:await l6t({cliVersion:n,generatorName:a,context:i,channel:void 0})??c.version})}})}var f6t=require("fs/promises"),H0n=se(require("path"),1);var DGh=require("buffer"),L0u=se(J6h(),1),F0u=se(LD(),1),g9h=require("child_process"),rHh=se(prl(),1),pHh=require("path"),Dya=se(prl(),1),BHh=require("events"),Trl=Object.defineProperty,GqB=Object.getOwnPropertyDescriptor,Rrl=Object.getOwnPropertyNames,HqB=Object.prototype.hasOwnProperty,Ua=(e,t)=>function(){return e&&(t=(0,e[Rrl(e)[0]])(e=0)),t},KqB=(e,t)=>function(){return t||(0,e[Rrl(e)[0]])((t={exports:{}}).exports,t),t.exports},Xq=(e,t)=>{for(var r in t)Trl(e,r,{get:t[r],enumerable:!0})},$qB=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rrl(t))!HqB.call(e,n)&&n!==r&&Trl(e,n,{get:()=>t[n],enumerable:!(i=GqB(t,n))||i.enumerable});return e},FC=e=>$qB(Trl({},"__esModule",{value:!0}),e);function JqB(...e){let t=new String(e);return U0u.set(t,e),t}function R0u(e){return e instanceof String&&U0u.has(e)}function Y6h(e){return U0u.get(e)||[]}var U0u,xio=Ua({"src/lib/args/pathspec.ts"(){"use strict";U0u=new WeakMap}}),d8i,sen=Ua({"src/lib/errors/git-error.ts"(){"use strict";d8i=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),Gio,Iya=Ua({"src/lib/errors/git-response-error.ts"(){"use strict";sen(),Gio=class extends d8i{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),SGh,MGh=Ua({"src/lib/errors/task-configuration-error.ts"(){"use strict";sen(),SGh=class extends d8i{constructor(e){super(void 0,e)}}}});function BGh(e){return typeof e!="function"?G0n:e}function IGh(e){return typeof e=="function"&&e!==G0n}function CGh(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function qGh(e,t=0){return TGh(e)&&e.length>t?e[t]:void 0}function x0n(e,t=0){if(TGh(e)&&e.length>t)return e[e.length-1-t]}function TGh(e){return G0u(e)}function Hio(e="",t=!0,r=`
|
|
1588
1588
|
`){return e.split(r).reduce((i,n)=>{let a=t?n.trim():n;return a&&i.push(a),i},[])}function zrl(e,t){return Hio(e,!0).map(r=>t(r))}function Nrl(e){return(0,L0u.exists)(e,L0u.FOLDER)}function wP(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function RGh(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function V0u(e,t){if(Array.isArray(e)){let r=e.indexOf(t);r>=0&&e.splice(r,1)}else e.delete(t);return t}function Ztr(e){return Array.isArray(e)?e:[e]}function zGh(e){return e.replace(/[\s-]+(.)/g,(t,r)=>r.toUpperCase())}function Cya(e){return Ztr(e).map(t=>t instanceof String?t:String(t))}function ES(e,t=0){if(e==null)return t;let r=parseInt(e,10);return Number.isNaN(r)?t:r}function Vio(e,t){let r=[];for(let i=0,n=e.length;i<n;i++)r.push(t,e[i]);return r}function Wio(e){return(Array.isArray(e)?DGh.Buffer.concat(e):e).toString("utf-8")}function NGh(e,t){let r={};return t.forEach(i=>{e[i]!==void 0&&(r[i]=e[i])}),r}function Orl(e=0){return new Promise(t=>setTimeout(t,e))}function mrl(e){if(e!==!1)return e}var Bya,G0n,Kio,W0u=Ua({"src/lib/utils/util.ts"(){"use strict";Frl(),Bya="\0",G0n=()=>{},Kio=Object.prototype.toString.call.bind(Object.prototype.toString)}});function bAe(e,t,r){return t(e)?e:arguments.length>2?r:void 0}function Arl(e,t){let r=R0u(e)?"string":typeof e;return/number|string|boolean/.test(r)&&(!t||!t.includes(r))}function x0u(e){return!!e&&Kio(e)==="[object Object]"}function FGh(e){return typeof e=="function"}var $io,QGh,CU,z0u,G0u,Frl=Ua({"src/lib/utils/argument-filters.ts"(){"use strict";xio(),W0u(),$io=e=>Array.isArray(e),QGh=e=>typeof e=="number",CU=e=>typeof e=="string",z0u=e=>CU(e)||Array.isArray(e)&&e.every(CU),G0u=e=>e==null||"number|boolean|function".includes(typeof e)?!1:typeof e.length=="number"}}),Prl,YqB=Ua({"src/lib/utils/exit-codes.ts"(){"use strict";Prl=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(Prl||{})}}),N0u,XqB=Ua({"src/lib/utils/git-output-streams.ts"(){"use strict";N0u=class UGh{constructor(t,r){this.stdOut=t,this.stdErr=r}asStrings(){return new UGh(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function ZqB(){throw new Error("LineParser:useMatches not implemented")}var l_,uen,kqB=Ua({"src/lib/utils/line-parser.ts"(){"use strict";l_=class{constructor(e,t){this.matches=[],this.useMatches=ZqB,this.parse=(r,i)=>(this.resetMatches(),this._regExp.every((n,a)=>this.addMatch(n,a,r(a)))?this.useMatches(i,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,r){let i=r&&e.exec(r);return i&&this.pushMatch(t,i),!!i}pushMatch(e,t){this.matches.push(...t.slice(1))}},uen=class extends l_{addMatch(e,t,r){return/^remote:\s/.test(String(r))&&super.addMatch(e,t,r)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}});function LGh(...e){let t=process.cwd(),r=Object.assign({baseDir:t,...VGh},...e.filter(i=>typeof i=="object"&&i));return r.baseDir=r.baseDir||t,r.trimmed=r.trimmed===!0,r}var VGh,e1B=Ua({"src/lib/utils/simple-git-options.ts"(){"use strict";VGh={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function Qrl(e,t=[]){return x0u(e)?Object.keys(e).reduce((r,i)=>{let n=e[i];if(R0u(n))r.push(n);else if(Arl(n,["boolean"]))r.push(i+"="+n);else if(Array.isArray(n))for(let a of n)Arl(a,["string","number"])||r.push(i+"="+a);else r.push(i);return r},t):t}function v2(e,t=0,r=!1){let i=[];for(let n=0,a=t<0?e.length:t;n<a;n++)"string|number".includes(typeof e[n])&&i.push(String(e[n]));return Qrl(Url(e),i),r||i.push(...t1B(e)),i}function t1B(e){let t=typeof x0n(e)=="function";return Cya(bAe(x0n(e,t?1:0),$io,[]))}function Url(e){let t=FGh(x0n(e));return bAe(x0n(e,t?1:0),x0u)}function QC(e,t=!0){let r=BGh(x0n(e));return t||IGh(r)?r:void 0}var r1B=Ua({"src/lib/utils/task-options.ts"(){"use strict";Frl(),W0u(),xio()}});function jrl(e,t){return e(t.stdOut,t.stdErr)}function O2(e,t,r,i=!0){return Ztr(r).forEach(n=>{for(let a=Hio(n,i),o=0,c=a.length;o<c;o++){let d=(s=0)=>{if(!(o+s>=c))return a[o+s]};t.some(({parse:s})=>s(d,e))}}),e}var i1B=Ua({"src/lib/utils/task-parser.ts"(){"use strict";W0u()}}),WGh={};Xq(WGh,{ExitCodes:()=>Prl,GitOutputStreams:()=>N0u,LineParser:()=>l_,NOOP:()=>G0n,NULL:()=>Bya,RemoteLineParser:()=>uen,append:()=>wP,appendTaskOptions:()=>Qrl,asArray:()=>Ztr,asCamelCase:()=>zGh,asFunction:()=>BGh,asNumber:()=>ES,asStringArray:()=>Cya,bufferToString:()=>Wio,callTaskParser:()=>jrl,createInstanceConfig:()=>LGh,delay:()=>Orl,filterArray:()=>$io,filterFunction:()=>FGh,filterHasLength:()=>G0u,filterNumber:()=>QGh,filterPlainObject:()=>x0u,filterPrimitives:()=>Arl,filterString:()=>CU,filterStringOrStringArray:()=>z0u,filterType:()=>bAe,first:()=>qGh,folderExists:()=>Nrl,forEachLineWithContent:()=>zrl,getTrailingOptions:()=>v2,including:()=>RGh,isUserFunction:()=>IGh,last:()=>x0n,objectToString:()=>Kio,orVoid:()=>mrl,parseStringResponse:()=>O2,pick:()=>NGh,prefixedArray:()=>Vio,remove:()=>V0u,splitOn:()=>CGh,toLinesWithContent:()=>Hio,trailingFunctionArgument:()=>QC,trailingOptionsArgument:()=>Url});var Td=Ua({"src/lib/utils/index.ts"(){"use strict";Frl(),YqB(),XqB(),kqB(),e1B(),r1B(),i1B(),W0u()}}),xGh={};Xq(xGh,{CheckRepoActions:()=>wrl,checkIsBareRepoTask:()=>HGh,checkIsRepoRootTask:()=>GGh,checkIsRepoTask:()=>n1B});function n1B(e){switch(e){case"bare":return HGh();case"root":return GGh()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:H0u,parser:Lrl}}function GGh(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:H0u,parser(t){return/^\.(git)?$/.test(t.trim())}}}function HGh(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:H0u,parser:Lrl}}function a1B(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}var wrl,H0u,Lrl,KGh=Ua({"src/lib/tasks/check-is-repo.ts"(){"use strict";Td(),wrl=(e=>(e.BARE="bare",e.IN_TREE="tree",e.IS_REPO_ROOT="root",e))(wrl||{}),H0u=({exitCode:e},t,r,i)=>{if(e===128&&a1B(t))return r(Buffer.from("false"));i(t)},Lrl=e=>e.trim()==="true"}});function o1B(e,t){let r=new $Gh(e),i=e?YGh:JGh;return Hio(t).forEach(n=>{let a=n.replace(i,"");r.paths.push(a),(XGh.test(a)?r.folders:r.files).push(a)}),r}var $Gh,JGh,YGh,XGh,u1B=Ua({"src/lib/responses/CleanSummary.ts"(){"use strict";Td(),$Gh=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},JGh=/^[a-z]+\s*/i,YGh=/^[a-z]+\s+[a-z]+\s*/i,XGh=/\/$/}}),Erl={};Xq(Erl,{EMPTY_COMMANDS:()=>K0u,adhocExecTask:()=>ZGh,configurationErrorTask:()=>g2,isBufferTask:()=>e9h,isEmptyTask:()=>t9h,straightThroughBufferTask:()=>kGh,straightThroughStringTask:()=>K7});function ZGh(e){return{commands:K0u,format:"empty",parser:e}}function g2(e){return{commands:K0u,format:"empty",parser(){throw typeof e=="string"?new SGh(e):e}}}function K7(e,t=!1){return{commands:e,format:"utf-8",parser(r){return t?String(r).trim():r}}}function kGh(e){return{commands:e,format:"buffer",parser(t){return t}}}function e9h(e){return e.format==="buffer"}function t9h(e){return e.format==="empty"||!e.commands.length}var K0u,Yq=Ua({"src/lib/tasks/task.ts"(){"use strict";MGh(),K0u=[]}}),r9h={};Xq(r9h,{CONFIG_ERROR_INTERACTIVE_MODE:()=>Vrl,CONFIG_ERROR_MODE_REQUIRED:()=>Wrl,CONFIG_ERROR_UNKNOWN_OPTION:()=>xrl,CleanOptions:()=>I0u,cleanTask:()=>i9h,cleanWithOptionsTask:()=>s1B,isCleanOptionsArray:()=>c1B});function s1B(e,t){let{cleanMode:r,options:i,valid:n}=l1B(e);return r?n.options?(i.push(...t),i.some(p1B)?g2(Vrl):i9h(r,i)):g2(xrl+JSON.stringify(e)):g2(Wrl)}function i9h(e,t){return{commands:["clean",`-${e}`,...t],format:"utf-8",parser(i){return o1B(e==="n",i)}}}function c1B(e){return Array.isArray(e)&&e.every(t=>Grl.has(t))}function l1B(e){let t,r=[],i={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,"").split("").forEach(n=>{f1B(n)?(t=n,i.cleanMode=!0):i.options=i.options&&d1B(r[r.length]=`-${n}`)}),{cleanMode:t,options:r,valid:i}}function f1B(e){return e==="f"||e==="n"}function d1B(e){return/^-[a-z]$/i.test(e)&&Grl.has(e.charAt(1))}function p1B(e){return/^-[^\-]/.test(e)?e.indexOf("i")>0:e==="--interactive"}var Vrl,Wrl,xrl,I0u,Grl,n9h=Ua({"src/lib/tasks/clean.ts"(){"use strict";u1B(),Td(),Yq(),Vrl="Git clean interactive mode is not supported",Wrl='Git clean mode parameter ("n" or "f") is required',xrl="Git clean unknown option found in: ",I0u=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(I0u||{}),Grl=new Set(["i",...Cya(Object.values(I0u))])}});function _1B(e){let t=new o9h;for(let r of a9h(e))t.addValue(r.file,String(r.key),r.value);return t}function h1B(e,t){let r=null,i=[],n=new Map;for(let a of a9h(e,t))a.key===t&&(i.push(r=a.value),n.has(a.file)||n.set(a.file,[]),n.get(a.file).push(r));return{key:t,paths:Array.from(n.keys()),scopes:n,value:r,values:i}}function y1B(e){return e.replace(/^(file):/,"")}function*a9h(e,t=null){let r=e.split("\0");for(let i=0,n=r.length-1;i<n;){let a=y1B(r[i++]),o=r[i++],c=t;if(o.includes(`
|
|
1589
1589
|
`)){let d=CGh(o,`
|
|
1590
1590
|
`);c=d[0],o=d[1]}yield{file:a,key:c,value:o}}}var o9h,b1B=Ua({"src/lib/responses/ConfigList.ts"(){"use strict";Td(),o9h=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||(this._all=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{})),this._all}addFile(e){if(!(e in this.values)){let t=x0n(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,r){let i=this.addFile(e);Object.hasOwn(i,t)?Array.isArray(i[t])?i[t].push(r):i[t]=[i[t],r]:i[t]=r,this._all=void 0}}}});function _rl(e,t){return typeof e=="string"&&Object.hasOwn(Srl,e)?e:t}function v1B(e,t,r,i){let n=["config",`--${i}`];return r&&n.push("--add"),n.push(e,t),{commands:n,format:"utf-8",parser(a){return a}}}function g1B(e,t){let r=["config","--null","--show-origin","--get-all",e];return t&&r.splice(1,0,`--${t}`),{commands:r,format:"utf-8",parser(i){return h1B(i,e)}}}function O1B(e){let t=["config","--list","--show-origin","--null"];return e&&t.push(`--${e}`),{commands:t,format:"utf-8",parser(r){return _1B(r)}}}function m1B(){return{addConfig(e,t,...r){return this._runTask(v1B(e,t,r[0]===!0,_rl(r[1],"local")),QC(arguments))},getConfig(e,t){return this._runTask(g1B(e,_rl(t,void 0)),QC(arguments))},listConfig(...e){return this._runTask(O1B(_rl(e[0],void 0)),QC(arguments))}}}var Srl,u9h=Ua({"src/lib/tasks/config.ts"(){"use strict";b1B(),Td(),Srl=(e=>(e.system="system",e.global="global",e.local="local",e.worktree="worktree",e))(Srl||{})}});function A1B(e){return s9h.has(e)}var hrl,s9h,c9h=Ua({"src/lib/tasks/diff-name-status.ts"(){"use strict";hrl=(e=>(e.ADDED="A",e.COPIED="C",e.DELETED="D",e.MODIFIED="M",e.RENAMED="R",e.CHANGED="T",e.UNMERGED="U",e.UNKNOWN="X",e.BROKEN="B",e))(hrl||{}),s9h=new Set(Object.values(hrl))}});function P1B(...e){return new f9h().param(...e)}function j1B(e){let t=new Set,r={};return zrl(e,i=>{let[n,a,o]=i.split(Bya);t.add(n),(r[n]=r[n]||[]).push({line:ES(a),path:n,preview:o})}),{paths:t,results:r}}function w1B(){return{grep(e){let t=QC(arguments),r=v2(arguments);for(let n of l9h)if(r.includes(n))return this._runTask(g2(`git.grep: use of "${n}" is not supported.`),t);typeof e=="string"&&(e=P1B().param(e));let i=["grep","--null","-n","--full-name",...r,...e];return this._runTask({commands:i,format:"utf-8",parser(n){return j1B(n)}},t)}}}var l9h,Lio,X6h,f9h,d9h=Ua({"src/lib/tasks/grep.ts"(){"use strict";Td(),Yq(),l9h=["-h"],Lio=Symbol("grepQuery"),f9h=class{constructor(){this[X6h]=[]}*[(X6h=Lio,Symbol.iterator)](){for(let e of this[Lio])yield e}and(...e){return e.length&&this[Lio].push("--and","(",...Vio(e,"-e"),")"),this}param(...e){return this[Lio].push(...Vio(e,"-e")),this}}}}),p9h={};Xq(p9h,{ResetMode:()=>C0u,getResetMode:()=>S1B,resetTask:()=>E1B});function E1B(e,t){let r=["reset"];return _9h(e)&&r.push(`--${e}`),r.push(...t),K7(r)}function S1B(e){if(_9h(e))return e;switch(typeof e){case"string":case"undefined":return"soft"}}function _9h(e){return typeof e=="string"&&h9h.includes(e)}var C0u,h9h,y9h=Ua({"src/lib/tasks/reset.ts"(){"use strict";Td(),Yq(),C0u=(e=>(e.MIXED="mixed",e.SOFT="soft",e.HARD="hard",e.MERGE="merge",e.KEEP="keep",e))(C0u||{}),h9h=Cya(Object.values(C0u))}});function M1B(){return(0,F0u.default)("simple-git")}function Z6h(e,t,r){return!t||!String(t).replace(/\s*/,"")?r?(i,...n)=>{e(i,...n),r(i,...n)}:e:(i,...n)=>{e(`%s ${i}`,t,...n),r&&r(i,...n)}}function D1B(e,t,{namespace:r}){if(typeof e=="string")return e;let i=t&&t.namespace||"";return i.startsWith(r)?i.substr(r.length+1):i||r}function Hrl(e,t,r,i=M1B()){let n=e&&`[${e}]`||"",a=[],o=typeof t=="string"?i.extend(t):t,c=D1B(bAe(t,CU),o,i);return s(r);function d(u,f){return wP(a,Hrl(e,c.replace(/^[^:]+/,u),f,i))}function s(u){let f=u&&`[${u}]`||"",p=o&&Z6h(o,f)||G0n,_=Z6h(i,`${n} ${f}`,p);return Object.assign(o?p:_,{label:e,sibling:d,info:_,step:s})}}var b9h=Ua({"src/lib/git-logger.ts"(){"use strict";Td(),F0u.default.formatters.L=e=>String(G0u(e)?e.length:"-"),F0u.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString("utf8"):Kio(e)}}),v9h,B1B=Ua({"src/lib/runners/tasks-pending-queue.ts"(){"use strict";sen(),b9h(),v9h=class Mrl{constructor(t="GitExecutor"){this.logLabel=t,this._queue=new Map}withProgress(t){return this._queue.get(t)}createProgress(t){let r=Mrl.getName(t.commands[0]),i=Hrl(this.logLabel,r);return{task:t,logger:i,name:r}}push(t){let r=this.createProgress(t);return r.logger("Adding task to the queue, commands = %o",t.commands),this._queue.set(t,r),r}fatal(t){for(let[r,{logger:i}]of Array.from(this._queue.entries()))r===t.task?(i.info("Failed %o",t),i("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):i.info("A fatal exception occurred in a previous task, the queue has been purged: %o",t.message),this.complete(r);if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(t){this.withProgress(t)&&this._queue.delete(t)}attempt(t){let r=this.withProgress(t);if(!r)throw new d8i(void 0,"TasksPendingQueue: attempt called for an unknown task");return r.logger("Starting task"),r}static getName(t="empty"){return`task:${t}:${++Mrl.counter}`}static{this.counter=0}}}});function W0n(e,t){return{method:qGh(e.commands)||"",commands:t}}function I1B(e,t){return r=>{t("[ERROR] child process exception %o",r),e.push(Buffer.from(String(r.stack),"ascii"))}}function k6h(e,t,r,i){return n=>{r("%s received %L bytes",t,n),i("%B",n),e.push(n)}}var Drl,C1B=Ua({"src/lib/runners/git-executor-chain.ts"(){"use strict";sen(),Yq(),Td(),B1B(),Drl=class{constructor(e,t,r){this._executor=e,this._scheduler=t,this._plugins=r,this._chain=Promise.resolve(),this._queue=new v9h}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){let t=await this._scheduler.next(),r=()=>this._queue.complete(e);try{let{logger:i}=this._queue.attempt(e);return await(t9h(e)?this.attemptEmptyTask(e,i):this.attemptRemoteTask(e,i))}catch(i){throw this.onFatalException(e,i)}finally{r(),t()}}onFatalException(e,t){let r=t instanceof d8i?Object.assign(t,{task:e}):new d8i(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(r),r}async attemptRemoteTask(e,t){let r=this._plugins.exec("spawn.binary","",W0n(e,e.commands)),i=this._plugins.exec("spawn.args",[...e.commands],W0n(e,e.commands)),n=await this.gitResponse(e,r,i,this.outputHandler,t.step("SPAWN")),a=await this.handleTaskData(e,i,n,t.step("HANDLE"));return t("passing response to task's parser as a %s",e.format),e9h(e)?jrl(e.parser,a):jrl(e.parser,a.asStrings())}async attemptEmptyTask(e,t){return t("empty task bypassing child process to call to task's parser"),e.parser(this)}handleTaskData(e,t,r,i){let{exitCode:n,rejection:a,stdOut:o,stdErr:c}=r;return new Promise((d,s)=>{i("Preparing to handle process response exitCode=%d stdOut=",n);let{error:u}=this._plugins.exec("task.error",{error:a},{...W0n(e,t),...r});if(u&&e.onError)return i.info("exitCode=%s handling with custom error handler"),e.onError(r,u,f=>{i.info("custom error handler treated as success"),i("custom error returned a %s",Kio(f)),d(new N0u(Array.isArray(f)?Buffer.concat(f):f,Buffer.concat(c)))},s);if(u)return i.info("handling as error: exitCode=%s stdErr=%s rejection=%o",n,c.length,a),s(u);i.info("retrieving task output complete"),d(new N0u(Buffer.concat(o),Buffer.concat(c)))})}async gitResponse(e,t,r,i,n){let a=n.sibling("output"),o=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},W0n(e,e.commands));return new Promise(c=>{let d=[],s=[];n.info("%s %o",t,r),n("%O",o);let u=this._beforeSpawn(e,r);if(u)return c({stdOut:d,stdErr:s,exitCode:9901,rejection:u});this._plugins.exec("spawn.before",void 0,{...W0n(e,r),kill(p){u=p||u}});let f=(0,g9h.spawn)(t,r,o);f.stdout.on("data",k6h(d,"stdOut",n,a.step("stdOut"))),f.stderr.on("data",k6h(s,"stdErr",n,a.step("stdErr"))),f.on("error",I1B(s,n)),i&&(n("Passing child process stdOut/stdErr to custom outputHandler"),i(t,f.stdout,f.stderr,[...r])),this._plugins.exec("spawn.after",void 0,{...W0n(e,r),spawned:f,close(p,_){c({stdOut:d,stdErr:s,exitCode:p,rejection:u||_})},kill(p){f.killed||(u=p,f.kill("SIGINT"))}})})}_beforeSpawn(e,t){let r;return this._plugins.exec("spawn.before",void 0,{...W0n(e,t),kill(i){r=i||r}}),r}}}}),O9h={};Xq(O9h,{GitExecutor:()=>m9h});var m9h,q1B=Ua({"src/lib/runners/git-executor.ts"(){"use strict";C1B(),m9h=class{constructor(e,t,r){this.cwd=e,this._scheduler=t,this._plugins=r,this._chain=new Drl(this,this._scheduler,this._plugins)}chain(){return new Drl(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function T1B(e,t,r=G0n){let i=a=>{r(null,a)},n=a=>{a?.task===e&&r(a instanceof Gio?R1B(a):a,void 0)};t.then(i,n)}function R1B(e){let t=i=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${i} should be GitResponseError.git.${i}, this will no longer be available in version 3`),t=G0n};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(r,{}));function r(i,n){return n in e||(i[n]={enumerable:!1,configurable:!1,get(){return t(n),e.git[n]}}),i}}var z1B=Ua({"src/lib/task-callback.ts"(){"use strict";Iya(),Td()}});function eGh(e,t){return ZGh(r=>{if(!Nrl(e))throw new Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||r).cwd=e})}var N1B=Ua({"src/lib/tasks/change-working-directory.ts"(){"use strict";Td(),Yq()}});function yrl(e){let t=["checkout",...e];return t[1]==="-b"&&t.includes("-B")&&(t[1]=V0u(t,"-B")),K7(t)}function F1B(){return{checkout(){return this._runTask(yrl(v2(arguments,1)),QC(arguments))},checkoutBranch(e,t){return this._runTask(yrl(["-b",e,t,...v2(arguments)]),QC(arguments))},checkoutLocalBranch(e){return this._runTask(yrl(["-b",e,...v2(arguments)]),QC(arguments))}}}var Q1B=Ua({"src/lib/tasks/checkout.ts"(){"use strict";Td(),Yq()}});function U1B(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function L1B(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(e){return O2(U1B(),[A9h],e)}})}}}var A9h,V1B=Ua({"src/lib/tasks/count-objects.ts"(){"use strict";Td(),A9h=new l_(/([a-z-]+): (\d+)$/,(e,[t,r])=>{let i=zGh(t);Object.hasOwn(e,i)&&(e[i]=ES(r))})}});function W1B(e){return O2({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},P9h,e)}var P9h,x1B=Ua({"src/lib/parsers/parse-commit.ts"(){"use strict";Td(),P9h=[new l_(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,r,i])=>{e.branch=t,e.commit=i,e.root=!!r}),new l_(/\s*Author:\s(.+)/i,(e,[t])=>{let r=t.split("<"),i=r.pop();!i||!i.includes("@")||(e.author={email:i.substr(0,i.length-1),name:r.join("<").trim()})}),new l_(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,r,i])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(r,10)||0,e.summary.deletions=parseInt(i,10)||0}),new l_(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,r,i])=>{e.summary.changes=parseInt(t,10)||0;let n=parseInt(r,10)||0;i==="-"?e.summary.deletions=n:i==="+"&&(e.summary.insertions=n)})]}});function G1B(e,t,r){return{commands:["-c","core.abbrev=40","commit",...Vio(e,"-m"),...t,...r],format:"utf-8",parser:W1B}}function H1B(){return{commit(t,...r){let i=QC(arguments),n=e(t)||G1B(Ztr(t),Ztr(bAe(r[0],z0u,[])),[...Cya(bAe(r[1],$io,[])),...v2(arguments,0,!0)]);return this._runTask(n,i)}};function e(t){return!z0u(t)&&g2("git.commit: requires the commit message to be supplied as a string/string[]")}}var K1B=Ua({"src/lib/tasks/commit.ts"(){"use strict";x1B(),Td(),Yq()}});function $1B(){return{firstCommit(){return this._runTask(K7(["rev-list","--max-parents=0","HEAD"],!0),QC(arguments))}}}var J1B=Ua({"src/lib/tasks/first-commit.ts"(){"use strict";Td(),Yq()}});function Y1B(e,t){let r=["hash-object",e];return t&&r.push("-w"),K7(r,!0)}var X1B=Ua({"src/lib/tasks/hash-object.ts"(){"use strict";Yq()}});function Z1B(e,t,r){let i=String(r).trim(),n;if(n=j9h.exec(i))return new q0u(e,t,!1,n[1]);if(n=w9h.exec(i))return new q0u(e,t,!0,n[1]);let a="",o=i.split(" ");for(;o.length;)if(o.shift()==="in"){a=o.join(" ");break}return new q0u(e,t,/^re/i.test(i),a)}var q0u,j9h,w9h,k1B=Ua({"src/lib/responses/InitSummary.ts"(){"use strict";q0u=class{constructor(e,t,r,i){this.bare=e,this.path=t,this.existing=r,this.gitDir=i}},j9h=/^Init.+ repository in (.+)$/,w9h=/^Rein.+ in (.+)$/}});function eTB(e){return e.includes(Krl)}function tTB(e=!1,t,r){let i=["init",...r];return e&&!eTB(i)&&i.splice(1,0,Krl),{commands:i,format:"utf-8",parser(n){return Z1B(i.includes("--bare"),t,n)}}}var Krl,rTB=Ua({"src/lib/tasks/init.ts"(){"use strict";k1B(),Krl="--bare"}});function $rl(e){for(let t=0;t<e.length;t++){let r=Jrl.exec(e[t]);if(r)return`--${r[1]}`}return""}function iTB(e){return Jrl.test(e)}var Jrl,Jio=Ua({"src/lib/args/log-format.ts"(){"use strict";Jrl=/^--(stat|numstat|name-only|name-status)(=|$)/}}),E9h,nTB=Ua({"src/lib/responses/DiffSummary.ts"(){"use strict";E9h=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function S9h(e=""){let t=M9h[e];return r=>O2(new E9h,t,r,!1)}var brl,tGh,rGh,iGh,M9h,D9h=Ua({"src/lib/parsers/parse-diff-summary.ts"(){"use strict";Jio(),nTB(),c9h(),Td(),brl=[new l_(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,r,i=""])=>{e.files.push({file:t.trim(),changes:ES(r),insertions:i.replace(/[^+]/g,"").length,deletions:i.replace(/[^-]/g,"").length,binary:!1})}),new l_(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,r,i])=>{e.files.push({file:t.trim(),before:ES(r),after:ES(i),binary:!0})}),new l_(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,r])=>{let i=/(\d+) i/.exec(r),n=/(\d+) d/.exec(r);e.changed=ES(t),e.insertions=ES(i?.[1]),e.deletions=ES(n?.[1])})],tGh=[new l_(/(\d+)\t(\d+)\t(.+)$/,(e,[t,r,i])=>{let n=ES(t),a=ES(r);e.changed++,e.insertions+=n,e.deletions+=a,e.files.push({file:i,changes:n+a,insertions:n,deletions:a,binary:!1})}),new l_(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],rGh=[new l_(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],iGh=[new l_(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,r,i,n,a])=>{e.changed++,e.files.push({file:a??i,changes:0,insertions:0,deletions:0,binary:!1,status:mrl(A1B(t)&&t),from:mrl(!!a&&i!==a&&i),similarity:ES(r)})})],M9h={"":brl,"--stat":brl,"--numstat":tGh,"--name-status":iGh,"--name-only":rGh}}});function aTB(e,t){return t.reduce((r,i,n)=>(r[i]=e[n]||"",r),Object.create({diff:null}))}function B9h(e=Zrl,t=I9h,r=""){let i=S9h(r);return function(n){let a=Hio(n.trim(),!1,Yrl).map(function(o){let c=o.split(Xrl),d=aTB(c[0].split(e),t);return c.length>1&&c[1].trim()&&(d.diff=i(c[1])),d});return{all:a,latest:a.length&&a[0]||null,total:a.length}}}var Yrl,Xrl,Zrl,I9h,C9h=Ua({"src/lib/parsers/parse-list-log-summary.ts"(){"use strict";Td(),D9h(),Jio(),Yrl="\xF2\xF2\xF2\xF2\xF2\xF2 ",Xrl=" \xF2\xF2",Zrl=" \xF2 ",I9h=["hash","date","message","refs","author_name","author_email"]}}),q9h={};Xq(q9h,{diffSummaryTask:()=>oTB,validateLogFormatConfig:()=>$0u});function oTB(e){let t=$rl(e),r=["diff"];return t===""&&(t="--stat",r.push("--stat=4096")),r.push(...e),$0u(r)||{commands:r,format:"utf-8",parser:S9h(t)}}function $0u(e){let t=e.filter(iTB);if(t.length>1)return g2(`Summary flags are mutually exclusive - pick one of ${t.join(",")}`);if(t.length&&e.includes("-z"))return g2(`Summary flag ${t} parsing is not compatible with null termination option '-z'`)}var krl=Ua({"src/lib/tasks/diff.ts"(){"use strict";Jio(),D9h(),Yq()}});function uTB(e,t){let r=[],i=[];return Object.keys(e).forEach(n=>{r.push(n),i.push(String(e[n]))}),[r,i.join(t)]}function sTB(e){return Object.keys(e).reduce((t,r)=>(r in Brl||(t[r]=e[r]),t),{})}function T9h(e={},t=[]){let r=bAe(e.splitter,CU,Zrl),i=x0u(e.format)?e.format:{hash:"%H",date:e.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:e.multiLine?"%B":"%b",author_name:e.mailMap!==!1?"%aN":"%an",author_email:e.mailMap!==!1?"%aE":"%ae"},[n,a]=uTB(i,r),o=[],c=[`--pretty=format:${Yrl}${a}${Xrl}`,...t],d=e.n||e["max-count"]||e.maxCount;if(d&&c.push(`--max-count=${d}`),e.from||e.to){let s=e.symmetric!==!1?"...":"..";o.push(`${e.from||""}${s}${e.to||""}`)}return CU(e.file)&&c.push("--follow",JqB(e.file)),Qrl(sTB(e),c),{fields:n,splitter:r,commands:[...c,...o]}}function cTB(e,t,r){let i=B9h(e,t,$rl(r));return{commands:["log",...r],format:"utf-8",parser:i}}function lTB(){return{log(...r){let i=QC(arguments),n=T9h(Url(arguments),Cya(bAe(arguments[0],$io,[]))),a=t(...r)||$0u(n.commands)||e(n);return this._runTask(a,i)}};function e(r){return cTB(r.splitter,r.fields,r.commands)}function t(r,i){return CU(r)&&CU(i)&&g2("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var Brl,R9h=Ua({"src/lib/tasks/log.ts"(){"use strict";Jio(),xio(),C9h(),Td(),Yq(),krl(),Brl=(e=>(e[e["--pretty"]=0]="--pretty",e[e["max-count"]=1]="max-count",e[e.maxCount=2]="maxCount",e[e.n=3]="n",e[e.file=4]="file",e[e.format=5]="format",e[e.from=6]="from",e[e.to=7]="to",e[e.splitter=8]="splitter",e[e.symmetric=9]="symmetric",e[e.mailMap=10]="mailMap",e[e.multiLine=11]="multiLine",e[e.strictDate=12]="strictDate",e))(Brl||{})}}),T0u,z9h,fTB=Ua({"src/lib/responses/MergeSummary.ts"(){"use strict";T0u=class{constructor(e,t=null,r){this.reason=e,this.file=t,this.meta=r}toString(){return`${this.file}:${this.reason}`}},z9h=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),Irl,N9h,dTB=Ua({"src/lib/responses/PullSummary.ts"(){"use strict";Irl=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},N9h=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function vrl(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function nGh(e){let t=/^\s*(\d+)/.exec(e),r=/delta (\d+)/i.exec(e);return{count:ES(t&&t[1]||"0"),delta:ES(r&&r[1]||"0")}}var F9h,pTB=Ua({"src/lib/parsers/parse-remote-objects.ts"(){"use strict";Td(),F9h=[new uen(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,r])=>{let i=t.toLowerCase(),n=vrl(e.remoteMessages);Object.assign(n,{[i]:ES(r)})}),new uen(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,r])=>{let i=t.toLowerCase(),n=vrl(e.remoteMessages);Object.assign(n,{[i]:ES(r)})}),new uen(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,r,i])=>{let n=vrl(e.remoteMessages);n.total=nGh(t),n.reused=nGh(r),n.packReused=ES(i)})]}});function Q9h(e,t){return O2({remoteMessages:new L9h},U9h,t)}var U9h,L9h,V9h=Ua({"src/lib/parsers/parse-remote-messages.ts"(){"use strict";Td(),pTB(),U9h=[new uen(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...F9h,new uen([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new uen([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,r,i])=>{e.remoteMessages.vulnerabilities={count:ES(t),summary:r,url:i}})],L9h=class{constructor(){this.all=[]}}}});function _TB(e,t){let r=O2(new N9h,W9h,[e,t]);return r.message&&r}var aGh,oGh,uGh,sGh,W9h,cGh,eil,x9h=Ua({"src/lib/parsers/parse-pull.ts"(){"use strict";dTB(),Td(),V9h(),aGh=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,oGh=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,uGh=/^(create|delete) mode \d+ (.+)/,sGh=[new l_(aGh,(e,[t,r,i])=>{e.files.push(t),r&&(e.insertions[t]=r.length),i&&(e.deletions[t]=i.length)}),new l_(oGh,(e,[t,,r,,i])=>r!==void 0||i!==void 0?(e.summary.changes=+t||0,e.summary.insertions=+r||0,e.summary.deletions=+i||0,!0):!1),new l_(uGh,(e,[t,r])=>{wP(e.files,r),wP(t==="create"?e.created:e.deleted,r)})],W9h=[new l_(/^from\s(.+)$/i,(e,[t])=>{e.remote=t}),new l_(/^fatal:\s(.+)$/,(e,[t])=>{e.message=t}),new l_(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,r,i,n])=>{e.branch.local=i,e.hash.local=t,e.branch.remote=n,e.hash.remote=r})],cGh=(e,t)=>O2(new Irl,sGh,[e,t]),eil=(e,t)=>Object.assign(new Irl,cGh(e,t),Q9h(e,t))}}),lGh,G9h,fGh,hTB=Ua({"src/lib/parsers/parse-merge.ts"(){"use strict";fTB(),Td(),x9h(),lGh=[new l_(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new l_(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,r])=>{e.conflicts.push(new T0u(t,r))}),new l_(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,r,i])=>{e.conflicts.push(new T0u(t,r,{deleteRef:i}))}),new l_(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new T0u(t,null))}),new l_(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],G9h=(e,t)=>Object.assign(fGh(e,t),eil(e,t)),fGh=e=>O2(new z9h,lGh,e)}});function dGh(e){return e.length?{commands:["merge",...e],format:"utf-8",parser(t,r){let i=G9h(t,r);if(i.failed)throw new Gio(i);return i}}:g2("Git.merge requires at least one option")}var yTB=Ua({"src/lib/tasks/merge.ts"(){"use strict";Iya(),hTB(),Yq()}});function bTB(e,t,r){let i=r.includes("deleted"),n=r.includes("tag")||/^refs\/tags/.test(e),a=!r.includes("new");return{deleted:i,tag:n,branch:!n,new:!a,alreadyUpdated:a,local:e,remote:t}}var pGh,H9h,_Gh,vTB=Ua({"src/lib/parsers/parse-push.ts"(){"use strict";Td(),V9h(),pGh=[new l_(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new l_(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new l_(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,r,i])=>{e.pushed.push(bTB(t,r,i))}),new l_(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,r,i])=>{e.branch={...e.branch||{},local:t,remote:r,remoteName:i}}),new l_(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,r,i,n])=>{e.update={head:{local:t,remote:r},hash:{from:i,to:n}}})],H9h=(e,t)=>{let r=_Gh(e,t),i=Q9h(e,t);return{...r,...i}},_Gh=(e,t)=>O2({pushed:[]},pGh,[e,t])}}),K9h={};Xq(K9h,{pushTagsTask:()=>gTB,pushTask:()=>til});function gTB(e={},t){return wP(t,"--tags"),til(e,t)}function til(e={},t){let r=["push",...t];return e.branch&&r.splice(1,0,e.branch),e.remote&&r.splice(1,0,e.remote),V0u(r,"-v"),wP(r,"--verbose"),wP(r,"--porcelain"),{commands:r,format:"utf-8",parser:H9h}}var $9h=Ua({"src/lib/tasks/push.ts"(){"use strict";vTB(),Td()}});function OTB(){return{showBuffer(){let e=["show",...v2(arguments,1)];return e.includes("--binary")||e.splice(1,0,"--binary"),this._runTask(kGh(e),QC(arguments))},show(){let e=["show",...v2(arguments,1)];return this._runTask(K7(e),QC(arguments))}}}var mTB=Ua({"src/lib/tasks/show.ts"(){"use strict";Td(),Yq()}}),hGh,J9h,ATB=Ua({"src/lib/responses/FileStatusSummary.ts"(){"use strict";hGh=/^(.+)\0(.+)$/,J9h=class{constructor(e,t,r){if(this.path=e,this.index=t,this.working_dir=r,t==="R"||r==="R"){let i=hGh.exec(e)||[null,e,e];this.from=i[2]||"",this.path=i[1]||""}}}}});function yGh(e){let[t,r]=e.split(Bya);return{from:r||t,to:t}}function yAe(e,t,r){return[`${e}${t}`,r]}function grl(e,...t){return t.map(r=>yAe(e,r,(i,n)=>wP(i.conflicted,n)))}function PTB(e,t){let r=t.trim();switch(" "){case r.charAt(2):return i(r.charAt(0),r.charAt(1),r.substr(3));case r.charAt(1):return i(" ",r.charAt(0),r.substr(2));default:return}function i(n,a,o){let c=`${n}${a}`,d=Y9h.get(c);d&&d(e,o),c!=="##"&&c!=="!!"&&e.files.push(new J9h(o,n,a))}}var bGh,Y9h,X9h,jTB=Ua({"src/lib/responses/StatusSummary.ts"(){"use strict";Td(),ATB(),bGh=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},Y9h=new Map([yAe(" ","A",(e,t)=>wP(e.created,t)),yAe(" ","D",(e,t)=>wP(e.deleted,t)),yAe(" ","M",(e,t)=>wP(e.modified,t)),yAe("A"," ",(e,t)=>wP(e.created,t)&&wP(e.staged,t)),yAe("A","M",(e,t)=>wP(e.created,t)&&wP(e.staged,t)&&wP(e.modified,t)),yAe("D"," ",(e,t)=>wP(e.deleted,t)&&wP(e.staged,t)),yAe("M"," ",(e,t)=>wP(e.modified,t)&&wP(e.staged,t)),yAe("M","M",(e,t)=>wP(e.modified,t)&&wP(e.staged,t)),yAe("R"," ",(e,t)=>{wP(e.renamed,yGh(t))}),yAe("R","M",(e,t)=>{let r=yGh(t);wP(e.renamed,r),wP(e.modified,r.to)}),yAe("!","!",(e,t)=>{wP(e.ignored=e.ignored||[],t)}),yAe("?","?",(e,t)=>wP(e.not_added,t)),...grl("A","A","U"),...grl("D","D","U"),...grl("U","A","D","U"),["##",(e,t)=>{let r=/ahead (\d+)/,i=/behind (\d+)/,n=/^(.+?(?=(?:\.{3}|\s|$)))/,a=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/,c=r.exec(t);e.ahead=c&&+c[1]||0,c=i.exec(t),e.behind=c&&+c[1]||0,c=n.exec(t),e.current=bAe(c?.[1],CU,null),c=a.exec(t),e.tracking=bAe(c?.[1],CU,null),c=o.exec(t),c&&(e.current=bAe(c?.[1],CU,e.current)),e.detached=/\(no branch\)/.test(t)}]]),X9h=function(e){let t=e.split(Bya),r=new bGh;for(let i=0,n=t.length;i<n;){let a=t[i++].trim();a&&(a.charAt(0)==="R"&&(a+=Bya+(t[i++]||"")),PTB(r,a))}return r}}});function wTB(e){return{format:"utf-8",commands:["status","--porcelain","-b","-u","--null",...e.filter(r=>!Z9h.includes(r))],parser(r){return X9h(r)}}}var Z9h,ETB=Ua({"src/lib/tasks/status.ts"(){"use strict";jTB(),Z9h=["--null","-z"]}});function Q0u(e=0,t=0,r=0,i="",n=!0){return Object.defineProperty({major:e,minor:t,patch:r,agent:i,installed:n},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function STB(){return Q0u(0,0,0,"",!1)}function MTB(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:DTB,onError(e,t,r,i){if(e.exitCode===-2)return r(Buffer.from(ril));i(t)}})}}}function DTB(e){return e===ril?STB():O2(Q0u(0,0,0,e),k9h,e)}var ril,k9h,BTB=Ua({"src/lib/tasks/version.ts"(){"use strict";Td(),ril="installed=false",k9h=[new l_(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,r,i,n=""])=>{Object.assign(e,Q0u(ES(t),ES(r),ES(i),n))}),new l_(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,r,i,n=""])=>{Object.assign(e,Q0u(ES(t),ES(r),i,n))})]}}),eHh={};Xq(eHh,{SimpleGitApi:()=>Crl});var Crl,ITB=Ua({"src/lib/simple-git-api.ts"(){"use strict";z1B(),N1B(),Q1B(),V1B(),K1B(),u9h(),J1B(),d9h(),X1B(),rTB(),R9h(),yTB(),$9h(),mTB(),ETB(),Yq(),BTB(),Td(),Crl=class{constructor(e){this._executor=e}_runTask(e,t){let r=this._executor.chain(),i=r.push(e);return t&&T1B(e,i,t),Object.create(this,{then:{value:i.then.bind(i)},catch:{value:i.catch.bind(i)},_executor:{value:r}})}add(e){return this._runTask(K7(["add",...Ztr(e)]),QC(arguments))}cwd(e){let t=QC(arguments);return typeof e=="string"?this._runTask(eGh(e,this._executor),t):typeof e?.path=="string"?this._runTask(eGh(e.path,e.root&&this._executor||void 0),t):this._runTask(g2("Git.cwd: workingDirectory must be supplied as a string"),t)}hashObject(e,t){return this._runTask(Y1B(e,t===!0),QC(arguments))}init(e){return this._runTask(tTB(e===!0,this._executor.cwd,v2(arguments)),QC(arguments))}merge(){return this._runTask(dGh(v2(arguments)),QC(arguments))}mergeFromTo(e,t){return CU(e)&&CU(t)?this._runTask(dGh([e,t,...v2(arguments)]),QC(arguments,!1)):this._runTask(g2("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(e){return this._executor.outputHandler=e,this}push(){let e=til({remote:bAe(arguments[0],CU),branch:bAe(arguments[1],CU)},v2(arguments));return this._runTask(e,QC(arguments))}stash(){return this._runTask(K7(["stash",...v2(arguments)]),QC(arguments))}status(){return this._runTask(wTB(v2(arguments)),QC(arguments))}},Object.assign(Crl.prototype,F1B(),H1B(),m1B(),L1B(),$1B(),w1B(),lTB(),OTB(),MTB())}}),tHh={};Xq(tHh,{Scheduler:()=>iHh});var vGh,iHh,CTB=Ua({"src/lib/runners/scheduler.ts"(){"use strict";Td(),b9h(),vGh=(()=>{let e=0;return()=>{e++;let{promise:t,done:r}=(0,rHh.createDeferred)();return{promise:t,done:r,id:e}}})(),iHh=class{constructor(e=2){this.concurrency=e,this.logger=Hrl("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let e=wP(this.running,this.pending.shift());this.logger("Attempting id=%s",e.id),e.done(()=>{this.logger("Completing id=",e.id),V0u(this.running,e),this.schedule()})}next(){let{promise:e,id:t}=wP(this.pending,vGh());return this.logger("Scheduling id=%s",t),this.schedule(),e}}}}),nHh={};Xq(nHh,{applyPatchTask:()=>qTB});function qTB(e,t){return K7(["apply",...t,...e])}var TTB=Ua({"src/lib/tasks/apply-patch.ts"(){"use strict";Yq()}});function RTB(e,t){return{branch:e,hash:t,success:!0}}function zTB(e){return{branch:e,hash:null,success:!1}}var aHh,NTB=Ua({"src/lib/responses/BranchDeleteSummary.ts"(){"use strict";aHh=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function oHh(e,t){return t===1&&qrl.test(e)}var gGh,qrl,OGh,J0u,FTB=Ua({"src/lib/parsers/parse-branch-delete.ts"(){"use strict";NTB(),Td(),gGh=/(\S+)\s+\(\S+\s([^)]+)\)/,qrl=/^error[^']+'([^']+)'/m,OGh=[new l_(gGh,(e,[t,r])=>{let i=RTB(t,r);e.all.push(i),e.branches[t]=i}),new l_(qrl,(e,[t])=>{let r=zTB(t);e.errors.push(r),e.all.push(r),e.branches[t]=r})],J0u=(e,t)=>O2(new aHh,OGh,[e,t])}}),uHh,QTB=Ua({"src/lib/responses/BranchSummary.ts"(){"use strict";uHh=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(e,t,r,i,n){e==="*"&&(this.detached=t,this.current=r),this.all.push(r),this.branches[r]={current:e==="*",linkedWorkTree:e==="+",name:r,commit:i,label:n}}}}});function mGh(e){return e?e.charAt(0):""}function sHh(e,t=!1){return O2(new uHh,t?[lHh]:cHh,e)}var cHh,lHh,UTB=Ua({"src/lib/parsers/parse-branch.ts"(){"use strict";QTB(),Td(),cHh=[new l_(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,r,i,n])=>{e.push(mGh(t),!0,r,i,n)}),new l_(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,r,i,n])=>{e.push(mGh(t),!1,r,i,n)})],lHh=new l_(/^(\S+)$/s,(e,[t])=>{e.push("*",!1,t,"","")})}}),fHh={};Xq(fHh,{branchLocalTask:()=>VTB,branchTask:()=>LTB,containsDeleteBranchCommand:()=>dHh,deleteBranchTask:()=>xTB,deleteBranchesTask:()=>WTB});function dHh(e){let t=["-d","-D","--delete"];return e.some(r=>t.includes(r))}function LTB(e){let t=dHh(e),r=e.includes("--show-current"),i=["branch",...e];return i.length===1&&i.push("-a"),i.includes("-v")||i.splice(1,0,"-v"),{format:"utf-8",commands:i,parser(n,a){return t?J0u(n,a).all[0]:sHh(n,r)}}}function VTB(){return{format:"utf-8",commands:["branch","-v"],parser(e){return sHh(e)}}}function WTB(e,t=!1){return{format:"utf-8",commands:["branch","-v",t?"-D":"-d",...e],parser(r,i){return J0u(r,i)},onError({exitCode:r,stdOut:i},n,a,o){if(!oHh(String(n),r))return o(n);a(i)}}}function xTB(e,t=!1){let r={format:"utf-8",commands:["branch","-v",t?"-D":"-d",e],parser(i,n){return J0u(i,n).branches[e]},onError({exitCode:i,stdErr:n,stdOut:a},o,c,d){if(!oHh(String(o),i))return d(o);throw new Gio(r.parser(Wio(a),Wio(n)),String(o))}};return r}var GTB=Ua({"src/lib/tasks/branch.ts"(){"use strict";Iya(),FTB(),UTB(),Td()}});function HTB(e){let t=e.trim().replace(/^["']|["']$/g,"");return t&&(0,pHh.normalize)(t)}var _Hh,KTB=Ua({"src/lib/responses/CheckIgnore.ts"(){"use strict";_Hh=e=>e.split(/\n/g).map(HTB).filter(Boolean)}}),hHh={};Xq(hHh,{checkIgnoreTask:()=>$TB});function $TB(e){return{commands:["check-ignore",...e],format:"utf-8",parser:_Hh}}var JTB=Ua({"src/lib/tasks/check-ignore.ts"(){"use strict";KTB()}}),yHh={};Xq(yHh,{cloneMirrorTask:()=>XTB,cloneTask:()=>bHh});function YTB(e){return/^--upload-pack(=|$)/.test(e)}function bHh(e,t,r){let i=["clone",...r];return CU(e)&&i.push(e),CU(t)&&i.push(t),i.find(YTB)?g2("git.fetch: potential exploit argument blocked."):K7(i)}function XTB(e,t,r){return wP(r,"--mirror"),bHh(e,t,r)}var ZTB=Ua({"src/lib/tasks/clone.ts"(){"use strict";Yq(),Td()}});function kTB(e,t){return O2({raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]},vHh,[e,t])}var vHh,eRB=Ua({"src/lib/parsers/parse-fetch.ts"(){"use strict";Td(),vHh=[new l_(/From (.+)$/,(e,[t])=>{e.remote=t}),new l_(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.branches.push({name:t,tracking:r})}),new l_(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.tags.push({name:t,tracking:r})}),new l_(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new l_(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,r,i,n])=>{e.updated.push({name:i,tracking:n,to:r,from:t})})]}}),gHh={};Xq(gHh,{fetchTask:()=>rRB});function tRB(e){return/^--upload-pack(=|$)/.test(e)}function rRB(e,t,r){let i=["fetch",...r];return e&&t&&i.push(e,t),i.find(tRB)?g2("git.fetch: potential exploit argument blocked."):{commands:i,format:"utf-8",parser:kTB}}var iRB=Ua({"src/lib/tasks/fetch.ts"(){"use strict";eRB(),Yq()}});function nRB(e){return O2({moves:[]},OHh,e)}var OHh,aRB=Ua({"src/lib/parsers/parse-move.ts"(){"use strict";Td(),OHh=[new l_(/^Renaming (.+) to (.+)$/,(e,[t,r])=>{e.moves.push({from:t,to:r})})]}}),mHh={};Xq(mHh,{moveTask:()=>oRB});function oRB(e,t){return{commands:["mv","-v",...Ztr(e),t],format:"utf-8",parser:nRB}}var uRB=Ua({"src/lib/tasks/move.ts"(){"use strict";aRB(),Td()}}),AHh={};Xq(AHh,{pullTask:()=>sRB});function sRB(e,t,r){let i=["pull",...r];return e&&t&&i.splice(1,0,e,t),{commands:i,format:"utf-8",parser(n,a){return eil(n,a)},onError(n,a,o,c){let d=_TB(Wio(n.stdOut),Wio(n.stdErr));if(d)return c(new Gio(d));c(a)}}}var cRB=Ua({"src/lib/tasks/pull.ts"(){"use strict";Iya(),x9h(),Td()}});function lRB(e){let t={};return PHh(e,([r])=>t[r]={name:r}),Object.values(t)}function fRB(e){let t={};return PHh(e,([r,i,n])=>{Object.hasOwn(t,r)||(t[r]={name:r,refs:{fetch:"",push:""}}),n&&i&&(t[r].refs[n.replace(/[^a-z]/g,"")]=i)}),Object.values(t)}function PHh(e,t){zrl(e,r=>t(r.split(/\s+/)))}var dRB=Ua({"src/lib/responses/GetRemoteSummary.ts"(){"use strict";Td()}}),jHh={};Xq(jHh,{addRemoteTask:()=>pRB,getRemotesTask:()=>_RB,listRemotesTask:()=>hRB,remoteTask:()=>yRB,removeRemoteTask:()=>bRB});function pRB(e,t,r){return K7(["remote","add",...r,e,t])}function _RB(e){let t=["remote"];return e&&t.push("-v"),{commands:t,format:"utf-8",parser:e?fRB:lRB}}function hRB(e){let t=[...e];return t[0]!=="ls-remote"&&t.unshift("ls-remote"),K7(t)}function yRB(e){let t=[...e];return t[0]!=="remote"&&t.unshift("remote"),K7(t)}function bRB(e){return K7(["remote","remove",e])}var vRB=Ua({"src/lib/tasks/remote.ts"(){"use strict";dRB(),Yq()}}),wHh={};Xq(wHh,{stashListTask:()=>gRB});function gRB(e={},t){let r=T9h(e),i=["stash","list",...r.commands,...t],n=B9h(r.splitter,r.fields,$rl(i));return $0u(i)||{commands:i,format:"utf-8",parser:n}}var ORB=Ua({"src/lib/tasks/stash-list.ts"(){"use strict";Jio(),C9h(),krl(),R9h()}}),EHh={};Xq(EHh,{addSubModuleTask:()=>mRB,initSubModuleTask:()=>ARB,subModuleTask:()=>Y0u,updateSubModuleTask:()=>PRB});function mRB(e,t){return Y0u(["add",e,t])}function ARB(e){return Y0u(["init",...e])}function Y0u(e){let t=[...e];return t[0]!=="submodule"&&t.unshift("submodule"),K7(t)}function PRB(e){return Y0u(["update",...e])}var jRB=Ua({"src/lib/tasks/sub-module.ts"(){"use strict";Yq()}});function wRB(e,t){let r=Number.isNaN(e),i=Number.isNaN(t);return r!==i?r?1:-1:r?SHh(e,t):0}function SHh(e,t){return e===t?0:e>t?1:-1}function ERB(e){return e.trim()}function B0u(e){return typeof e=="string"&&parseInt(e.replace(/^\D+/g,""),10)||0}var AGh,MHh,SRB=Ua({"src/lib/responses/TagList.ts"(){"use strict";AGh=class{constructor(e,t){this.all=e,this.latest=t}},MHh=function(e,t=!1){let r=e.split(`
|
|
@@ -2237,7 +2237,7 @@ ${E3E.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&$Pp(th
|
|
|
2237
2237
|
`+Mea.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Mea.default.cyan(R3E(t,this.opt.mask)):Mea.default.italic(Mea.default.dim("[hidden]")):this.opt.mask?R3E(t,this.opt.mask):Mea.default.italic(Mea.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 noc=se(oQ(),1);var TWE=se(Djp(),1),roc=require("child_process"),Ixa=require("fs"),toc=se(require("path"),1),RWE=se(require("os"),1),zWE=require("crypto"),pwp=se(CWE(),1);var Zac=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var m4o=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var kac=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var eoc=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function ioc(e="",t,r){let i=new _wp(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 qWE(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function Yc5(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 _wp=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=Yc5(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??RWE.default.tmpdir(),r=(0,zWE.randomUUID)(),i=qWE(this.fileOptions.prefix),n=qWE(this.fileOptions.postfix),a=`${i}${r}${n}`,o=toc.default.resolve(t,a),c=toc.default.resolve(t)+toc.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,Ixa.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new Zac(t)}}readTemporaryFile(){try{let t=(0,Ixa.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,TWE.detect)(t)??"utf8";pwp.default.encodingExists(r)||(r="utf8"),this.text=pwp.default.decode(t,r)}}catch(t){throw new kac(t)}}removeTemporaryFile(){try{(0,Ixa.unlinkSync)(this.tempFile)}catch(t){throw new eoc(t)}}launchEditor(){try{let t=(0,roc.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new m4o(t)}}launchEditorAsync(t){try{(0,roc.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new m4o(r)}}};var NWE=se(zEe(),1);var A4o=class extends uQ{_run(t){this.done=t,this.editorResult=new NWE.Subject;let r=Tx(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"?noc.default.dim("Received"):noc.default.dim("Press <enter> to launch your preferred editor."),t&&(r=noc.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),ioc(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 VWE=require("stream");var UWE=se(require("readline"),1),LWE=se(QWE(),1),Cea=class{constructor(t){this.rl||=UWE.default.createInterface(Zc5(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 Zc5(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 LWE.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var P4o=class extends Cea{constructor(t={}){super(t),this.log=new VWE.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return o4o(this.rl,this.bottomBar.split(`
|
|
2238
2238
|
`).length),this}updateBottomBar(t){return o4o(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+`
|
|
2239
2239
|
`}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&&Eac(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var AA=se(zEe(),1),GWE=se(NLo(),1);var aoc=se(zEe(),1),WWE=se(NLo(),1),ooc=function(e,t,r){return typeof e[t]!="function"?(0,aoc.of)(e):(0,aoc.from)((0,WWE.default)(e[t])(r).then(i=>(e[t]=i,e)))};var xWE={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}},Cxa=class extends Cea{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,AA.from)(t):(0,AA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,AA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,AA.from)([t]),this.process=i.pipe((0,AA.concatMap)(this.processQuestion.bind(this)),(0,AA.publish)()),this.process.connect(),this.process.pipe((0,AA.reduce)((n,a)=>(xWE.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,AA.defer)(()=>(0,AA.of)(t).pipe((0,AA.concatMap)(this.setDefaultType.bind(this)),(0,AA.concatMap)(this.filterIfRunnable.bind(this)),(0,AA.concatMap)(()=>ooc(t,"message",this.answers)),(0,AA.concatMap)(()=>ooc(t,"default",this.answers)),(0,AA.concatMap)(()=>ooc(t,"choices",this.answers)),(0,AA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,AA.defer)(()=>(0,AA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,AA.defer)(()=>(0,AA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&xWE.get(this.answers,t.name)!==void 0)return AA.EMPTY;if(t.when===!1)return AA.EMPTY;if(typeof t.when!="function")return(0,AA.of)(t);let{answers:r}=this;return(0,AA.defer)(()=>(0,AA.from)((0,GWE.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,AA.filter)(i=>i!=null)))}};function HWE(e){let t=function(r,i){let n;try{n=new Cxa(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",s4o),this.registerPrompt("input",Sea),this.registerPrompt("number",c4o),this.registerPrompt("confirm",l4o),this.registerPrompt("rawlist",f4o),this.registerPrompt("expand",d4o),this.registerPrompt("checkbox",p4o),this.registerPrompt("password",_4o),this.registerPrompt("editor",A4o)},t.restoreDefaultPrompts(),t}var ywp=HWE();function el5(e,t){ywp.registerPrompt(e,t)}function tl5(){ywp.restoreDefaultPrompts()}var rl5={prompt:ywp,ui:{BottomBar:P4o,Prompt:Cxa},createPromptModule:HWE,registerPrompt:el5,restoreDefaultPrompts:tl5,Separator:jOe},uoc=rl5;var qxa=require("path");function $WE(){let e=il5();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function il5(e=process.argv[1]?(0,qxa.dirname)(process.argv[1]):process.cwd(),t=qxa.sep==="\\"){let r=t?KWE(e):e;return i=>{if(!i)return;let n=t?KWE(i):i,{dir:a,base:o,ext:c}=qxa.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 KWE(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var bwp=e=>{if("flags"in e){let t=JWE(e.flags),r=YWE(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,XWE(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,nl5(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function nl5(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 JWE=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,j4o(r)]).filter(([,t])=>t!==void 0)),YWE=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?XWE(i):void 0]}))};var j4o=e=>e===void 0?void 0:e.variant??e.enabled,XWE=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var soc="0123456789abcdef",coc=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+=soc.charAt(this.bytes[r]>>>4),t+=soc.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+=soc.charAt(this.bytes[r]>>>4),t+=soc.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}},vwp=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??al5()}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 coc.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,coc.ofInner(t)}},al5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ZWE,pLi=()=>ol5().toString(),ol5=()=>(ZWE||(ZWE=new vwp)).generate();var ul5=["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"],kWE=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return ul5.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var EOe=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var cl5=Array.isArray,e8E=Object.prototype,Huk=e8E.hasOwnProperty,gwp=e8E.toString,Owp=cl5||function(e){return gwp.call(e)==="[object Array]"};var t8E=e=>e===Object(e)&&!Owp(e);var Txa=e=>e===void 0,w4o=e=>gwp.call(e)=="[object String]",r8E=e=>w4o(e)&&e.trim().length===0;var i8E=e=>gwp.call(e)=="[object Number]"&&e===e;var mwp=e=>e instanceof Error;function E4o(e){return e===null||typeof e!="object"}function qea(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function n8E(e){return qea(e,"ErrorEvent")}function loc(e){return!Txa(Event)&&ll5(e,Event)}function a8E(e){return qea(e,"Object")}function ll5(e,t){try{return e instanceof t}catch{return!1}}function S4o(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),i8E(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),S4o(n||r,t,r,i))}var fl5=864e5,foc=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=S4o(t.bucketSize,0,100,t._logger),this._refillRate=S4o(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=S4o(t.refillInterval,0,fl5,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 doc=class{add(t){let r=pLi();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 dl5(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var o8E=(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=>o8E(`${e} ${a}`,t,r)}},pl5=e=>e();function u8E(e,t=pl5){return o8E(e,t,dl5())}var zxa="Mobile",_oc="iOS",Rxa="Android",s8E="Tablet",nsk=Rxa+" "+s8E;var _l5="Apple",ask=_l5+" Watch",c8E="Safari",hoc="BlackBerry",l8E="Samsung",hl5=l8E+"Browser",yl5=l8E+" Internet",yoc="Chrome",bl5=yoc+" OS",vl5=yoc+" "+_oc,f8E="Internet Explorer",gl5=f8E+" "+zxa,Pwp="Opera",osk=Pwp+" Mini",d8E="Edge",Ol5="Microsoft "+d8E,jwp="Firefox",ml5=jwp+" "+_oc,wwp="Nintendo",Ewp="PlayStation",poc="Xbox",Al5=Rxa+" "+zxa,Pl5=zxa+" "+c8E,M4o="Windows",jl5=M4o+" Phone";var p8E="Generic",usk=p8E+" "+zxa.toLowerCase(),ssk=p8E+" "+s8E.toLowerCase(),wl5="Konqueror",GY="(\\d+(\\.\\d+)?)",Awp=new RegExp("Version/"+GY),csk=new RegExp(poc,"i"),lsk=new RegExp(Ewp+" \\w+","i"),fsk=new RegExp(wwp+" \\w+","i"),El5=new RegExp(hoc+"|PlayBook|BB10","i"),Sl5={"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 dsk={[gl5]:[new RegExp("rv:"+GY)],[Ol5]:[new RegExp(d8E+"?\\/"+GY)],[yoc]:[new RegExp("("+yoc+"|CrMo)\\/"+GY)],[vl5]:[new RegExp("CriOS\\/"+GY)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+GY)],[c8E]:[Awp],[Pl5]:[Awp],[Pwp]:[new RegExp("("+Pwp+"|OPR)\\/"+GY)],[jwp]:[new RegExp(jwp+"\\/"+GY)],[ml5]:[new RegExp("FxiOS\\/"+GY)],[wl5]:[new RegExp("Konqueror[:/]?"+GY,"i")],[hoc]:[new RegExp(hoc+" "+GY),Awp],[Al5]:[new RegExp("android\\s"+GY,"i")],[yl5]:[new RegExp(hl5+"\\/"+GY)],[f8E]:[new RegExp("(rv:|MSIE )"+GY)],Mozilla:[new RegExp("rv:"+GY)]};var psk=[[new RegExp(poc+"; "+poc+" (.*?)[);]","i"),e=>[poc,e&&e[1]||""]],[new RegExp(wwp,"i"),[wwp,""]],[new RegExp(Ewp,"i"),[Ewp,""]],[El5,[hoc,""]],[new RegExp(M4o,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[jl5,""];if(new RegExp(zxa).test(t)&&!/IEMobile\b/.test(t))return[M4o+" "+zxa,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=Sl5[i]||"";return/arm/i.test(t)&&(n="RT"),[M4o,n]}return[M4o,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[_oc,t.join(".")]}return[_oc,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Txa(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Rxa+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Rxa+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Rxa,t.join(".")]}return[Rxa,""]}],[/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/,[bl5,""]],[/Linux|debian/i,["Linux",""]]];var _8E="utf8";function h8E(e,t){if(!e||typeof e!="string"||Ml5(e))throw new Error(t)}function Ml5(e){return e.trim().length===0}function y8E(e){return e?.replace(/\/+$/,"")}async function b8E(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 boc(){return new Date().toISOString()}function Tea(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var v8E=e=>e instanceof Error;function Swp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var voc=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 g8E(){return"CompressionStream"in globalThis}async function Mwp(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 Rea=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()}},Nxa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function O8E(e){if(e instanceof Rea){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 Dwp(e){return typeof e=="object"&&(e instanceof Rea||e instanceof Nxa)}function m8E(e){return typeof e=="object"&&e instanceof Rea&&e.status===413}var D4o=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new doc,this._events=new voc,this._isInitialized=!1,h8E(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=y8E(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:Dwp},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=u8E("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!g8E()||(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(EOe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(EOe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(EOe.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.evaluationContexts&&this.evaluationContexts.length>0&&(s.evaluation_contexts=this.evaluationContexts);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=>({success:!0,response:bwp(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(t){if(t instanceof Rea)return{type:"api_error",statusCode:t.status};if(t instanceof Nxa){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,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=j4o(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.success)return;let s=d.response;return s.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"),s.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:s?.requestId,quotaLimited:s.quotaLimited}):s}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(EOe.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(EOe.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(EOe.Props,this.props)})}processBeforeEnqueue(t){return t}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);if(n=this.processBeforeEnqueue(n),n===null)return;let a=this.getPersistedProperty(EOe.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(EOe.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Tea(()=>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=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a={api_key:this.apiKey,batch:[n],sent_at:boc()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),c=`${this.host}/batch/`,d=this.disableCompression?null:await Mwp(o,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...d!==null&&{"Content-Encoding":"gzip"}},body:d||o};try{await this.fetchWithRetry(c,s)}catch(u){this._events.emit("error",u)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:boc(),uuid:i?.uuid?i.uuid:pLi()};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 O8E(t)})}async flush(){let t=Swp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Swp([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(EOe.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(EOe.Queue)||[]).slice(n.length);this.setPersistedProperty(EOe.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:boc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await Mwp(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>m8E(_)?!1:Dwp(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(m8E(_)&&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 Nxa||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,_8E)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await b8E(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new Nxa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new Rea(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(EOe.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Dwp(n))throw n;await O8E(n)}};return Promise.race([new Promise((n,a)=>{Tea(()=>{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 SOe={};$t(SOe,{DOMExceptionCoercer:()=>qwp,ErrorCoercer:()=>Twp,ErrorEventCoercer:()=>Rwp,ErrorPropertiesBuilder:()=>Bwp,EventCoercer:()=>Fwp,ObjectCoercer:()=>Nwp,PrimitiveCoercer:()=>Qwp,PromiseRejectionEventCoercer:()=>Uwp,ReduceableCache:()=>Lwp,StringCoercer:()=>zwp,chromeStackLineParser:()=>Iwp,createDefaultStackParser:()=>Wl5,createStackParser:()=>C8E,geckoStackLineParser:()=>Cwp,nodeStackLineParser:()=>M8E,opera10StackLineParser:()=>w8E,opera11StackLineParser:()=>E8E,reverseAndStripFrames:()=>I8E,winjsStackLineParser:()=>j8E});var goc,A8E,Ooc;function P8E(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Ooc&&r.length===A8E||(A8E=r.length,Ooc=r.reduce((i,n)=>{goc||(goc={});let a=goc[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,goc[n]=[s,u];break}}}return i},{})),Ooc}var Bl5=4,Bwp=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&&Owp(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:P8E(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=Bl5){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 zx="?";function _Li(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?zx:r,in_app:!0};return Txa(i)||(a.lineno=i),Txa(n)||(a.colno=n),a}var moc=(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]:zx,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Il5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Cl5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ql5=/\((\S*)(?::(\d+))(?::(\d+))\)/,Iwp=(e,t)=>{let r=Il5.exec(e);if(r){let[,n,a,o]=r;return _Li(t,n,zx,+a,+o)}let i=Cl5.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=ql5.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=moc(i[1]||zx,i[2]);return _Li(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var Tl5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Rl5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Cwp=(e,t)=>{let r=Tl5.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=Rl5.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]||zx;return[a,n]=moc(a,n),_Li(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var zl5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,j8E=(e,t)=>{let r=zl5.exec(e);return r?_Li(t,r[2],r[1]||zx,+r[3],r[4]?+r[4]:void 0):void 0};var Nl5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,w8E=(e,t)=>{let r=Nl5.exec(e);return r?_Li(t,r[2],r[3]||zx,+r[1]):void 0},Fl5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,E8E=(e,t)=>{let r=Fl5.exec(e);return r?_Li(t,r[5],r[3]||r[4]||zx,+r[1],+r[2]):void 0};var Ql5=/^\s*[-]{4,}$/,Ul5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,M8E=(e,t)=>{let r=e.match(Ul5);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||zx,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:S8E(r[3]),colno:S8E(r[4]),in_app:Ll5(d||"",s),platform:t}}if(e.match(Ql5))return{filename:e,platform:t}};function Ll5(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 S8E(e){return parseInt(e||"",10)||void 0}var D8E=/\(error: (.*)\)/,B8E=50;function I8E(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,B8E).map(r=>({...r,filename:r.filename||Vl5(t).filename,function:r.function||zx}))}function Vl5(e){return e[e.length-1]||{}}function Wl5(){return C8E("web:javascript",Iwp,Cwp)}function C8E(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
2240
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=D8E.test(c)?c.replace(D8E,"$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>=B8E)break}}return I8E(n)}}var qwp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=w4o(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 qea(t,"DOMException")}isDOMError(t){return qea(t,"DOMError")}};var Twp=class{match(t){return mwp(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 Rwp=class{constructor(){}match(t){return n8E(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 xl5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,zwp=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(xl5);return n&&(r=n[1],i=n[2]),[r,i]}};var q8E=["fatal","error","warning","log","info","debug"];function Aoc(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 Nwp=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 loc(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=Aoc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return w4o(t)&&!r8E(t)&&q8E.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(v8E(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Fwp=class{match(t){return loc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Aoc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Qwp=class{match(t){return E4o(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Uwp=class{match(t){return qea(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return E4o(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(E4o(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 Lwp=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 z8E=require("fs"),N8E=require("readline"),Poc=new SOe.ReduceableCache(25),F8E=new SOe.ReduceableCache(20),Vwp=7,Gl5=1e3,Hl5=1e4;async function Q8E(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"||Yl5(o)||Xl5(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(F8E.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=kl5(a);if(o.every(d=>Zl5(n,d)))continue;let c=ef5(Poc,n,{});i.push(Kl5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&$l5(e,Poc),Poc.reduce(),e}function Kl5(e,t,r){return new Promise(i=>{let n=(0,z8E.createReadStream)(e),a=(0,N8E.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(){F8E.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]=tf5(_,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 $l5(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;Jl5(r.lineno,r,i)}}function Jl5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=U8E(e);n<e;n++){let a=r[n];if(a===void 0)return void T8E(t);t.pre_context.push(a)}if(r[e]===void 0)return void T8E(t);t.context_line=r[e];let i=L8E(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 T8E(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Yl5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Xl5(e){return e.lineno!==void 0&&e.lineno>Hl5||e.colno!==void 0&&e.colno>Gl5}function Zl5(e,t){let r=Poc.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 kl5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=R8E(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+Vwp:(n.push(i),i=R8E(a)),t++}return n}function R8E(e){return[U8E(e),L8E(e)]}function U8E(e){return Math.max(1,e-Vwp)}function L8E(e){return e+Vwp}function ef5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function tf5(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 rf5(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 V8E(e,t){globalThis.process?.on("uncaughtException",rf5(e,t))}function W8E(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var if5=2e3,c$t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new foc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return t8E(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}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||pLi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(V8E(this.onException.bind(this),this.onFatalError.bind(this)),W8E(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){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(if5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var x8E="5.24.7";var B4o={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function G8E(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 nf5=6e4,af5=1152921504606847e3,of5=["is_not"],Fxa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},uE=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},hLi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},joc=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.strictLocalEvaluation=c.strictLocalEvaluation??!1,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 hLi||d instanceof uE?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 hLi||p instanceof uE?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 uE("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 uE("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 uE("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new uE(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new uE(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new uE(`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 uE(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new uE(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new uE(`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 hLi)throw u;if(u instanceof uE)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new uE("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"?Y8E(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):J8E(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await H8E(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await H8E(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}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(nf5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(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.clearBackoff();return;case 401:throw this.beginBackoff(),new Fxa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new Fxa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Fxa(`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.clearBackoff(),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),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof Fxa&&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=Tea(()=>{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 H8E(e,t,r=""){let i=await G8E(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/af5}function J8E(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 uE("Operator is_not_set is not supported")}else throw new uE(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!of5.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 K8E(String(n))&&String(o).match(String(n))!==null;case"not_regex":return K8E(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 uE("Date operations cannot be performed on boolean values");let s=sf5(String(n));if(s==null&&(s=$8E(n)),s==null)throw new uE(`Invalid date: ${n}`);let u=$8E(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new uE(`Unknown operator: ${a}`)}}function uf5(e,t){if(!(e in t))throw new hLi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Y8E(e,t,r,i=!1){let n=String(e.value);uf5(n,r);let a=r[n];return X8E(a,t,r,i)}function X8E(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=X8E(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof hLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("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=Y8E(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=J8E(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 hLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("can't match cohort without a given cohort property value");return n==="AND"}function K8E(e){try{return new RegExp(e),!0}catch{return!1}}function $8E(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 uE(`${e} is in an invalid date format`)}throw new uE(`The date provided ${e} must be a string, number, or date object`)}function sf5(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 woc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var cf5=100,Z8E=3e4,lf5=5e4,Eoc=class extends D4o{constructor(t,r={}){if(super(t,r),this._memoryStorage=new woc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,cf5):Z8E,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 joc({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,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new c$t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||lf5}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 x8E}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=Z8E){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,_=!1,h,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){_=!0;let M=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:M!==!1,variant:typeof M=="string"?M:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof hLi||j instanceof uE)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!_&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=B4o.UNKNOWN_ERROR;else{h=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(B4o.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(B4o.QUOTA_LIMITED);let M=A.flags[t];if(M===void 0)j.push(B4o.FLAG_MISSING);else{v=M.metadata?.id,O=M.metadata?.version,m=M.reason?.description??M.reason?.code;let w;if(M.metadata?.payload!==void 0)try{w=JSON.parse(M.metadata.payload)}catch{w=M.metadata.payload}p={key:t,enabled:M.enabled,variant:M.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let M={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:_,[`$feature/${t}`]:A,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};b&&(M.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:M,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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=this.options.strictLocalEvaluation??!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 this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}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=Tea(()=>{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(a8E(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??this.options.strictLocalEvaluation??!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,n){if(!c$t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(c$t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!c$t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(c$t.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=pLi(),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"&&kWE(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 k8E=require("async_hooks"),Soc=class{constructor(){this.storage=new k8E.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 exE="posthog-node";function ff5(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[Wwp.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 Wwp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=exE,this.name=exE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(ff5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};c$t.errorPropertiesBuilder=new SOe.ErrorPropertiesBuilder([new SOe.EventCoercer,new SOe.ErrorCoercer,new SOe.ObjectCoercer,new SOe.StringCoercer,new SOe.PrimitiveCoercer],SOe.createStackParser("node:javascript",SOe.nodeStackLineParser),[$WE(),Q8E]);var Qxa=class extends Eoc{getLibraryId(){return"posthog-node"}initializeContext(){return new Soc}};var Moc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Qxa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.56.10",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var I4o=class{async sendEvent(){}async identify(){}async flush(){}};var Uxa=require("fs/promises"),txE=require("os"),rxE=require("path");var df5="id",pf5=".fern",C4o=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Qxa(r),this.userId=t==null?void 0:oFc(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.56.10",...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 d3({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=ot(mr.of((0,txE.homedir)()),Pe.of(pf5),Pe.of(df5));await ni(t)||(await(0,Uxa.mkdir)((0,rxE.dirname)(t),{recursive:!0}),await(0,Uxa.writeFile)(t,Xme())),this.persistedDistinctId=(await(0,Uxa.readFile)(t)).toString()}return this.persistedDistinctId}};var xwp;async function Lxa(){return xwp==null&&(xwp=await _f5()),xwp}async function _f5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new I4o;let r=await dZo();return r!=null?new C4o({token:r,posthogApiKey:e}):await esa()!=null?new Moc({posthogApiKey:e}):new C4o({token:void 0,posthogApiKey:e})}catch{return new I4o}}var q4o=se(require("process"),1);var axE=se(lLc(),1),oxE=se(nxE(),1);function vV(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=L8t(e),e.length===0))return 0;e=e.replace((0,oxE.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(axE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Doc(e){let t=0;for(let r of e.split(`
|
|
2240
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=D8E.test(c)?c.replace(D8E,"$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>=B8E)break}}return I8E(n)}}var qwp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=w4o(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 qea(t,"DOMException")}isDOMError(t){return qea(t,"DOMError")}};var Twp=class{match(t){return mwp(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 Rwp=class{constructor(){}match(t){return n8E(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 xl5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,zwp=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(xl5);return n&&(r=n[1],i=n[2]),[r,i]}};var q8E=["fatal","error","warning","log","info","debug"];function Aoc(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 Nwp=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 loc(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=Aoc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return w4o(t)&&!r8E(t)&&q8E.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(v8E(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Fwp=class{match(t){return loc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Aoc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Qwp=class{match(t){return E4o(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Uwp=class{match(t){return qea(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return E4o(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(E4o(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 Lwp=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 z8E=require("fs"),N8E=require("readline"),Poc=new SOe.ReduceableCache(25),F8E=new SOe.ReduceableCache(20),Vwp=7,Gl5=1e3,Hl5=1e4;async function Q8E(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"||Yl5(o)||Xl5(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(F8E.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=kl5(a);if(o.every(d=>Zl5(n,d)))continue;let c=ef5(Poc,n,{});i.push(Kl5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&$l5(e,Poc),Poc.reduce(),e}function Kl5(e,t,r){return new Promise(i=>{let n=(0,z8E.createReadStream)(e),a=(0,N8E.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(){F8E.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]=tf5(_,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 $l5(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;Jl5(r.lineno,r,i)}}function Jl5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=U8E(e);n<e;n++){let a=r[n];if(a===void 0)return void T8E(t);t.pre_context.push(a)}if(r[e]===void 0)return void T8E(t);t.context_line=r[e];let i=L8E(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 T8E(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Yl5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Xl5(e){return e.lineno!==void 0&&e.lineno>Hl5||e.colno!==void 0&&e.colno>Gl5}function Zl5(e,t){let r=Poc.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 kl5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=R8E(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+Vwp:(n.push(i),i=R8E(a)),t++}return n}function R8E(e){return[U8E(e),L8E(e)]}function U8E(e){return Math.max(1,e-Vwp)}function L8E(e){return e+Vwp}function ef5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function tf5(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 rf5(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 V8E(e,t){globalThis.process?.on("uncaughtException",rf5(e,t))}function W8E(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var if5=2e3,c$t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new foc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return t8E(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}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||pLi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(V8E(this.onException.bind(this),this.onFatalError.bind(this)),W8E(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){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(if5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var x8E="5.24.7";var B4o={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function G8E(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 nf5=6e4,af5=1152921504606847e3,of5=["is_not"],Fxa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},uE=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},hLi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},joc=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.strictLocalEvaluation=c.strictLocalEvaluation??!1,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 hLi||d instanceof uE?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 hLi||p instanceof uE?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 uE("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 uE("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 uE("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new uE(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new uE(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new uE(`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 uE(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new uE(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new uE(`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 hLi)throw u;if(u instanceof uE)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new uE("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"?Y8E(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):J8E(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await H8E(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await H8E(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}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(nf5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(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.clearBackoff();return;case 401:throw this.beginBackoff(),new Fxa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new Fxa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Fxa(`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.clearBackoff(),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),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof Fxa&&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=Tea(()=>{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 H8E(e,t,r=""){let i=await G8E(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/af5}function J8E(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 uE("Operator is_not_set is not supported")}else throw new uE(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!of5.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 K8E(String(n))&&String(o).match(String(n))!==null;case"not_regex":return K8E(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 uE("Date operations cannot be performed on boolean values");let s=sf5(String(n));if(s==null&&(s=$8E(n)),s==null)throw new uE(`Invalid date: ${n}`);let u=$8E(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new uE(`Unknown operator: ${a}`)}}function uf5(e,t){if(!(e in t))throw new hLi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Y8E(e,t,r,i=!1){let n=String(e.value);uf5(n,r);let a=r[n];return X8E(a,t,r,i)}function X8E(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=X8E(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof hLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("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=Y8E(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=J8E(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 hLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("can't match cohort without a given cohort property value");return n==="AND"}function K8E(e){try{return new RegExp(e),!0}catch{return!1}}function $8E(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 uE(`${e} is in an invalid date format`)}throw new uE(`The date provided ${e} must be a string, number, or date object`)}function sf5(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 woc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var cf5=100,Z8E=3e4,lf5=5e4,Eoc=class extends D4o{constructor(t,r={}){if(super(t,r),this._memoryStorage=new woc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,cf5):Z8E,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 joc({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,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new c$t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||lf5}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 x8E}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=Z8E){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,_=!1,h,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){_=!0;let M=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:M!==!1,variant:typeof M=="string"?M:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof hLi||j instanceof uE)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!_&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=B4o.UNKNOWN_ERROR;else{h=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(B4o.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(B4o.QUOTA_LIMITED);let M=A.flags[t];if(M===void 0)j.push(B4o.FLAG_MISSING);else{v=M.metadata?.id,O=M.metadata?.version,m=M.reason?.description??M.reason?.code;let w;if(M.metadata?.payload!==void 0)try{w=JSON.parse(M.metadata.payload)}catch{w=M.metadata.payload}p={key:t,enabled:M.enabled,variant:M.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let M={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:_,[`$feature/${t}`]:A,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};b&&(M.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:M,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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=this.options.strictLocalEvaluation??!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 this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}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=Tea(()=>{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(a8E(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??this.options.strictLocalEvaluation??!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,n){if(!c$t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(c$t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!c$t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(c$t.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=pLi(),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"&&kWE(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 k8E=require("async_hooks"),Soc=class{constructor(){this.storage=new k8E.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 exE="posthog-node";function ff5(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[Wwp.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 Wwp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=exE,this.name=exE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(ff5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};c$t.errorPropertiesBuilder=new SOe.ErrorPropertiesBuilder([new SOe.EventCoercer,new SOe.ErrorCoercer,new SOe.ObjectCoercer,new SOe.StringCoercer,new SOe.PrimitiveCoercer],SOe.createStackParser("node:javascript",SOe.nodeStackLineParser),[$WE(),Q8E]);var Qxa=class extends Eoc{getLibraryId(){return"posthog-node"}initializeContext(){return new Soc}};var Moc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Qxa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.57.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var I4o=class{async sendEvent(){}async identify(){}async flush(){}};var Uxa=require("fs/promises"),txE=require("os"),rxE=require("path");var df5="id",pf5=".fern",C4o=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Qxa(r),this.userId=t==null?void 0:oFc(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.57.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 d3({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=ot(mr.of((0,txE.homedir)()),Pe.of(pf5),Pe.of(df5));await ni(t)||(await(0,Uxa.mkdir)((0,rxE.dirname)(t),{recursive:!0}),await(0,Uxa.writeFile)(t,Xme())),this.persistedDistinctId=(await(0,Uxa.readFile)(t)).toString()}return this.persistedDistinctId}};var xwp;async function Lxa(){return xwp==null&&(xwp=await _f5()),xwp}async function _f5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new I4o;let r=await dZo();return r!=null?new C4o({token:r,posthogApiKey:e}):await esa()!=null?new Moc({posthogApiKey:e}):new C4o({token:void 0,posthogApiKey:e})}catch{return new I4o}}var q4o=se(require("process"),1);var axE=se(lLc(),1),oxE=se(nxE(),1);function vV(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=L8t(e),e.length===0))return 0;e=e.replace((0,oxE.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(axE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Doc(e){let t=0;for(let r of e.split(`
|
|
2241
2241
|
`))t=Math.max(t,vV(r));return t}var ExE=se(Hwp(),1);var yf5=/[\p{Lu}]/u,bf5=/[\p{Ll}]/u,cxE=/^[\p{Lu}](?![\p{Lu}])/gu,dxE=/([\p{Alpha}\p{N}_]|$)/u,Kwp=/[_.\- ]+/,vf5=new RegExp("^"+Kwp.source),lxE=new RegExp(Kwp.source+dxE.source,"gu"),fxE=new RegExp("\\d+"+dxE.source,"gu"),gf5=(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&&yf5.test(s)?(e=e.slice(0,d)+"-"+e.slice(d),n=!1,o=a,a=!0,d++):a&&o&&bf5.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},Of5=(e,t)=>(cxE.lastIndex=0,e.replace(cxE,r=>t(r))),mf5=(e,t)=>(lxE.lastIndex=0,fxE.lastIndex=0,e.replace(lxE,(r,i)=>t(i)).replace(fxE,r=>t(r)));function $wp(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?Kwp.test(e)?"":t.pascalCase?i(e):r(e):(e!==r(e)&&(e=gf5(e,r,i,t.preserveConsecutiveUppercase)),e=e.replace(vf5,""),e=t.preserveConsecutiveUppercase?Of5(e,r):r(e),t.pascalCase&&(e=i(e.charAt(0))+e.slice(1)),mf5(e,i))}var Zwp=se(_xE(),1);var hxE=(e=0)=>t=>`\x1B[${t+e}m`,yxE=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,bxE=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,qB={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]}},dfk=Object.keys(qB.modifier),wf5=Object.keys(qB.color),Ef5=Object.keys(qB.bgColor),pfk=[...wf5,...Ef5];function Sf5(){let e=new Map;for(let[t,r]of Object.entries(qB)){for(let[i,n]of Object.entries(r))qB[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=qB[i],e.set(n[0],n[1]);Object.defineProperty(qB,t,{value:r,enumerable:!1})}return Object.defineProperty(qB,"codes",{value:e,enumerable:!1}),qB.color.close="\x1B[39m",qB.bgColor.close="\x1B[49m",qB.color.ansi=hxE(),qB.color.ansi256=yxE(),qB.color.ansi16m=bxE(),qB.bgColor.ansi=hxE(10),qB.bgColor.ansi256=yxE(10),qB.bgColor.ansi16m=bxE(10),Object.defineProperties(qB,{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=>qB.rgbToAnsi256(...qB.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)=>qB.ansi256ToAnsi(qB.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>qB.ansi256ToAnsi(qB.hexToAnsi256(t)),enumerable:!1}}),qB}var Mf5=Sf5(),vxE=Mf5;var Boc=new Set(["\x1B","\x9B"]),Df5=39,Ywp="\x07",mxE="[",Bf5="]",AxE="m",Xwp=`${Bf5}8;;`,gxE=e=>`${Boc.values().next().value}${mxE}${e}${AxE}`,OxE=e=>`${Boc.values().next().value}${Xwp}${e}${Ywp}`,If5=e=>e.split(" ").map(t=>vV(t)),Jwp=(e,t,r)=>{let i=[...t],n=!1,a=!1,o=vV(L8t(e[e.length-1]));for(let[c,d]of i.entries()){let s=vV(d);if(o+s<=r?e[e.length-1]+=d:(e.push(d),o=0),Boc.has(d)&&(n=!0,a=i.slice(c+1).join("").startsWith(Xwp)),n){a?d===Ywp&&(n=!1,a=!1):d===AxE&&(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())},Cf5=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(vV(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},qf5=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,a,o=If5(e),c=[""];for(let[s,u]of e.split(" ").entries()){r.trim!==!1&&(c[c.length-1]=c[c.length-1].trimStart());let f=vV(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(""),Jwp(c,u,t);continue}if(f+o[s]>t&&f>0&&o[s]>0){if(r.wordWrap===!1&&f<t){Jwp(c,u,t);continue}c.push("")}if(f+o[s]>t&&r.wordWrap===!1){Jwp(c,u,t);continue}c[c.length-1]+=u}r.trim!==!1&&(c=c.map(s=>Cf5(s)));let d=[...c.join(`
|
|
2242
2242
|
`)];for(let[s,u]of d.entries()){if(i+=u,Boc.has(u)){let{groups:p}=new RegExp(`(?:\\${mxE}(?<code>\\d+)m|\\${Xwp}(?<uri>.*)${Ywp})`).exec(d.slice(s).join(""))||{groups:{}};if(p.code!==void 0){let _=Number.parseFloat(p.code);n=_===Df5?void 0:_}else p.uri!==void 0&&(a=p.uri.length===0?void 0:p.uri)}let f=vxE.codes.get(Number(n));d[s+1]===`
|
|
2243
2243
|
`?(a&&(i+=OxE("")),n&&f&&(i+=gxE(f))):u===`
|
|
@@ -2400,7 +2400,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2400
2400
|
Run ${Ot.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
2401
2401
|
Run ${Ot.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Vxa(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function ZTp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!iaS(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+=`
|
|
2402
2402
|
${await zR5(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Ot.dim(c.currentVersion)+Ot.reset(" \u2192 ")+Ot.green(c.latestVersion);return n+=`
|
|
2403
|
-
`,i?Vxa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function zR5(e){let r=await new raS.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 NR5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await aaS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=oen(u.name,f),_=await l6t({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 aaS({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=oen(s.name,u),p=await l6t({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 aaS({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 vAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?IU(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 oaS(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=A2(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 h_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await NR5({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(...oaS(s,d,t.logger));else o.push(...oaS(c.versions,void 0,t.logger))}return o}async function zbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:seo(e.packageName,{version:t?"prerelease":"latest"})}var uaS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],y_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ma.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Wmn(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.
|
|
2403
|
+
`,i?Vxa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function zR5(e){let r=await new raS.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 NR5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await aaS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=oen(u.name,f),_=await l6t({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 aaS({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=oen(s.name,u),p=await l6t({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 aaS({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 vAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?IU(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 oaS(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=A2(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 h_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await NR5({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(...oaS(s,d,t.logger));else o.push(...oaS(c.versions,void 0,t.logger))}return o}async function zbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:seo(e.packageName,{version:t?"prerelease":"latest"})}var uaS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],y_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ma.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Wmn(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.57.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ot.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new yS}failWithoutThrowing(t,r){this.didSucceed=!1,vZa({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Lxa()).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 naS({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2404
2404
|
`)||(r+=`
|
|
2405
2405
|
`),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=sAc(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 zWo(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 yS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await Lxa()).sendEvent(t)}logger=ome((t,...r)=>this.log(t,...r));stderr=ome((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=saS(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?saS(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=uaS[this.numTasks++%uaS.length],o=Ot.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===qA.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=>U8t.indexOf(n.level)>=U8t.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Ma.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 zbn({cliEnvironment:this.environment,includePreReleases:t}),i=A2(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await h_c({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await YTp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ot.yellow("?"),style:{answer:n=>Ot.cyan(n),message:n=>Ot.bold(n),highlight:n=>Ot.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
2406
2406
|
Cancelled by user.`),new yS):i}}async getInput(t){return await KTp({message:t.message,default:t.default})}};function saS(e){return`[${e}]:`}var caS=require("fs/promises");async function kTp({context:e,nameOverride:t,...r}){let i=await XM(t);return i==null?e.failAndThrow(`Directory "${t??mE}" not found.`):await laS({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function laS({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ni(ot(e,Pe.of(m7)))||await ni(ot(e,Pe.of(WM)))||await ni(ot(e,Pe.of(xM)))||await ni(ot(e,Pe.of(Tca)))||await ni(ot(e,Pe.of(K2a)))||await ni(ot(e,Pe.of(Q5c))))&&(o=await faS({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await pbp({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:
|
|
@@ -2436,7 +2436,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2436
2436
|
|
|
2437
2437
|
Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await gaS({generatorName:t,logger:a});if(c==null)return;let d=QR5({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return OaS({migrations:d,config:o,logger:a})}function maS(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 LR5({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await len({absolutePathToWorkspace:e});if(c==null||!await ni(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,g_c.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=$Ga.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(!$Ga.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${FWo.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(!$Ga.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${FWo.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(!$Ga.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${FWo.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){$Ga.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${FWo.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=oen(m,t),A=r!=null?IU(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"),M=await l6t({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=M??j;if(M!=null)if(M!==j){t.logger.debug(Ot.green(`Upgrading ${m} from ${j} to ${M}`)),O.set("version",M);let E=0,B=[],q=O.toJSON(),R=await eRp({generatorName:g,from:j,to:M,config:q,logger:t.logger});if(R!=null){E=R.migrationsApplied,B=R.appliedVersions;let T=new Set(Object.keys(q)),K=new Set(Object.keys(R.config));for(let H of T)K.has(H)||O.delete(H);for(let[H,z]of Object.entries(R.config))O.set(H,z);t.logger.debug(Ot.dim(`Applied ${E} migration(s): ${B.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:M,migrationsApplied:E>0?E:void 0,migrationVersions:B.length>0?B:void 0})}else t.logger.debug(Ot.gray(`${m} is already on the latest version: ${j}`)),_.push({generatorName:m,groupName:y,version:j});if(!n){let E=await l6t({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(E!=null){let B=tRp.default.parse(w),q=tRp.default.parse(E);B!=null&&q!=null&&q.major>B.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:E})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:_}}async function AaS({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 qya({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 LR5({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),_=await len({absolutePathToWorkspace:s.absoluteFilePath});_!=null&&p.updatedConfiguration!=null&&await(0,g_c.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(Ot.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(Ot.green(`${h}Group ${p}:`));for(let y of _){e.logger.info(Ot.green(` - ${y.generatorName}: ${Ot.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(Ot.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=maS(IU(y.generatorName));b!=null&&e.logger.info(Ot.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(Ot.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(Ot.dim(`${h}Group ${p}:`));for(let y of _)e.logger.info(Ot.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(Ot.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(Ot.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(Ot.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(Ot.yellow(` Run: ${u}`));let f=maS(IU(s.generatorName));f!=null&&e.logger.info(Ot.yellow(` Changelog: ${f}`))}}}function waS(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 baS({project:await jm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function EaS(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(KGa),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(KGa),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 _aS({project:await jm(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 ${xM} 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(PaS.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 jm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await h_c({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await ZTp({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
2438
2438
|
`,includeBoxen:!0});o!=null&&t.logger.info(o)}else await AaS({cliContext:t,generator:i.generator,group:i.group,project:await jm(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 haS({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await jm(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,jaS.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var SaS=require("fs/promises");async function MaS({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 qya({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await frl({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await len({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,SaS.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2439
|
-
`+qi.dump(c)),a.logger.info(Ot.green(`Added ${t} generator`)))})}))}var BaS=require("fs/promises"),IaS=se(OX(),1);async function CaS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new Yka,o=VR5(await a.check({from:await DaS({context:e,filepath:t,flagName:"from"}),to:await DaS({context:e,filepath:r,flagName:"to"})})),c=GR5(e,n),{bump:d,errors:s}=WR5(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=IaS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new yS;return{bump:u,nextVersion:f,errors:s}}async function DaS({context:e,filepath:t,flagName:r}){let i=mr.of(xo(OO(),t));if(!await ni(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new yS;let n=await(0,BaS.readFile)(i,"utf-8"),a=sa.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new yS;return a.value}function VR5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function WR5(e,t){return{bump:xR5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function xR5(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 GR5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=HR5(HAc(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 yS}}function HR5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}bE();var KdS=se(nRp(),1),$dS=se(nhc(),1),Fhc=require("fs/promises"),JdS=se(require("http"),1),YdS=se(require("path"),1);var MlS=require("events"),chc=se(require("fs"),1),Mra=se(require("path"),1);var llS=se(require("os"),1),flS=300,Wbn=20,c8o=1e7,dlS=llS.default.platform();var iV5=dlS==="darwin",Pzp=dlS==="win32",xbn=iV5||Pzp,plS=3e3,_lS=2e4,jzp=1250;var $Li;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})($Li||($Li={}));var Sra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Sra||(Sra={}));var l8o;(function(e){e.CHANGE="change",e.ERROR="error"})(l8o||(l8o={}));var Rf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Rf||(Rf={}));var oX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(oX||(oX={}));var nV5=(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,M=A>=t||j>=a;return[g,M]},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,M=t-A,w=a-j,E=Math.min(M,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),M=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return M?f(A):h(A)};return m.cancel=p,m.flush=_,m},ahc=nV5;var Mzp=se(require("fs"),1),uhc=se(require("path"),1);var jA=se(require("fs"),1),Vx=require("util");var uJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},JLi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var wzp=se(require("process"),1),hlS=wzp.default.getuid?!wzp.default.getuid():!1,ylS=1e4,VOe=()=>{};var f8o={isChangeErrorOk:e=>{if(!f8o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!hlS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!f8o.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(!f8o.isNodeError(e))throw e;if(!f8o.isChangeErrorOk(e))throw e}},TT=f8o;var Ezp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=ylS,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()}}}}},blS=new Ezp;var sJi=(e,t)=>function(i){return function n(...a){return blS.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)})}},cJi=(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 aV5={attempt:{chmod:uJi((0,Vx.promisify)(jA.default.chmod),TT.onChangeError),chown:uJi((0,Vx.promisify)(jA.default.chown),TT.onChangeError),close:uJi((0,Vx.promisify)(jA.default.close),VOe),fsync:uJi((0,Vx.promisify)(jA.default.fsync),VOe),mkdir:uJi((0,Vx.promisify)(jA.default.mkdir),VOe),realpath:uJi((0,Vx.promisify)(jA.default.realpath),VOe),stat:uJi((0,Vx.promisify)(jA.default.stat),VOe),unlink:uJi((0,Vx.promisify)(jA.default.unlink),VOe),chmodSync:JLi(jA.default.chmodSync,TT.onChangeError),chownSync:JLi(jA.default.chownSync,TT.onChangeError),closeSync:JLi(jA.default.closeSync,VOe),existsSync:JLi(jA.default.existsSync,VOe),fsyncSync:JLi(jA.default.fsync,VOe),mkdirSync:JLi(jA.default.mkdirSync,VOe),realpathSync:JLi(jA.default.realpathSync,VOe),statSync:JLi(jA.default.statSync,VOe),unlinkSync:JLi(jA.default.unlinkSync,VOe)},retry:{close:sJi((0,Vx.promisify)(jA.default.close),TT.isRetriableError),fsync:sJi((0,Vx.promisify)(jA.default.fsync),TT.isRetriableError),open:sJi((0,Vx.promisify)(jA.default.open),TT.isRetriableError),readFile:sJi((0,Vx.promisify)(jA.default.readFile),TT.isRetriableError),rename:sJi((0,Vx.promisify)(jA.default.rename),TT.isRetriableError),stat:sJi((0,Vx.promisify)(jA.default.stat),TT.isRetriableError),write:sJi((0,Vx.promisify)(jA.default.write),TT.isRetriableError),writeFile:sJi((0,Vx.promisify)(jA.default.writeFile),TT.isRetriableError),closeSync:cJi(jA.default.closeSync,TT.isRetriableError),fsyncSync:cJi(jA.default.fsyncSync,TT.isRetriableError),openSync:cJi(jA.default.openSync,TT.isRetriableError),readFileSync:cJi(jA.default.readFileSync,TT.isRetriableError),renameSync:cJi(jA.default.renameSync,TT.isRetriableError),statSync:cJi(jA.default.statSync,TT.isRetriableError),writeSync:cJi(jA.default.writeSync,TT.isRetriableError),writeFileSync:cJi(jA.default.writeFileSync,TT.isRetriableError)}},vlS=aV5;var ohc=se(require("fs"),1),d8o=se(require("path"),1);var Szp=()=>{};var oV5=()=>{let e=Szp,t=Szp,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}},glS=oV5;var uV5=()=>{let{promise:e,resolve:t,isPending:r}=glS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},OlS=uV5;var mlS={then:e=>{e()}};var AlS=e=>Array.isArray(e)?e:[e],PlS=e=>typeof e=="function";var sV5=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=AlS(a).map(Q=>PlS(Q)?Q:U=>Q.test(U)),c=Q=>o.some(U=>U(Q)),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:M,increment:w,decrement:E}=OlS(),B=0,q=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.directories.push(U),Q.directoriesNames.add(ce),u.push(U),f.add(ce),p.propertyIsEnumerable(ce)||(p[ce]=[]),p[ce].push(U),g.add(U),!(ae>=i)&&(B>=n||W(U,ae+1)))},R=(Q,U,ce)=>{g.has(U)||B>=n||(B+=1,Q.files.push(U),Q.filesNames.add(ce),_.push(U),h.add(ce),y.propertyIsEnumerable(ce)||(y[ce]=[]),y[ce].push(U),g.add(U))},T=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.symlinks.push(U),Q.symlinksNames.add(ce),b.push(U),v.add(ce),O.propertyIsEnumerable(ce)||(O[ce]=[]),O[ce].push(U),g.add(U),r&&(ae>=i||B>=n||Oe(U,ae+1)))},K=(Q,U,ce,ae,fe)=>{d.aborted||c(U)||(ae.isDirectory()?q(Q,U,ce,fe):ae.isFile()?R(Q,U,ce):ae.isSymbolicLink()&&T(Q,U,ce,fe))},H=(Q,U,ce,ae)=>{if(d.aborted)return;let fe=U===d8o.default.sep?"":d8o.default.sep,ve=ce.name,re=`${U}${fe}${ve}`;c(re)||(ce.isDirectory()?q(Q,re,ve,ae):ce.isFile()?R(Q,re,ve):ce.isSymbolicLink()&&T(Q,re,ve,ae))},z=(Q,U,ce,ae)=>{for(let fe=0,ve=ce.length;fe<ve;fe++)H(Q,U,ce[fe],ae)},W=(Q,U)=>{d.aborted||U>i||B>=n||(w(),ohc.default.readdir(Q,{withFileTypes:!0},(ce,ae)=>{if(ce||d.aborted||!ae.length)return E();(s(ae)||mlS).then(()=>{let ve=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ve,Q,ae,U),E()})}))},Oe=(Q,U)=>{w(),ohc.default.realpath(Q,(ce,ae)=>{if(ce||d.aborted)return E();ohc.default.stat(ae,(fe,ve)=>{if(fe||d.aborted)return E();let re=d8o.default.basename(ae),X=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ve,U),E()})})};return(async(Q,U=1)=>(Q=d8o.default.normalize(Q),g.add(Q),W(Q,U),await M,d.aborted?A:j))(e)},jlS=sV5;var YLi={lang:{debounce:ahc,attempt:e=>{try{return e()}catch(t){return YLi.lang.castError(t)}},castArray:e=>YLi.lang.isArray(e)?e:[e],castError:e=>YLi.lang.isError(e)?e:YLi.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(YLi.lang.isNaN(e))return YLi.lang.isNaN(t);if(YLi.lang.isPrimitive(e)||YLi.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(uhc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Mzp.default.realpathSync.native(e):Mzp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===uhc.default.sep&&t.length-e.length>uhc.default.sep.length,poll:(e,t=_lS)=>vlS.retry.stat(t)(e,{bigint:!0}).catch(YLi.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 jlS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mh=YLi;var shc=se(require("path"),1);var Dzp=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||Mh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=flS){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=Mh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Rf.CHANGE&&c===Rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),o=this.options.limit??c8o,[c,d]=await Mh.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())Mh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!xbn&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(shc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(shc.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Rf.ADD?this.onTargetAdd(i):r===Rf.ADD_DIR?this.onTargetAddDir(i):r===Rf.CHANGE?this.onTargetChange(i):r===Rf.UNLINK?this.onTargetUnlink(i):r===Rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Sra.CHANGE,r){if(this.watcher.isClosed())return;let i=shc.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){Pzp&&t.code==="EPERM"?this.onWatcherChange(Sra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(l8o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(l8o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Sra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&xbn&&this.options.native!==!1?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),i=this.options.limit??c8o,[n,a]=await Mh.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(Sra.CHANGE,c,t)}))}}},wlS=Dzp;var uX={interval:100,intervalId:void 0,fns:new Map,init:()=>{uX.intervalId||(uX.intervalId=setInterval(uX.resolve,uX.interval))},reset:()=>{uX.intervalId&&(clearInterval(uX.intervalId),delete uX.intervalId)},add:(e,t)=>{uX.fns.set(e,Date.now()+t),uX.init()},remove:e=>{uX.fns.delete(e)},resolve:()=>{if(!uX.fns.size)return uX.reset();let e=Date.now();for(let[t,r]of uX.fns)r>=e||(uX.remove(t),t())}},p8o=uX;var _8o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=jzp){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(Mh.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),p8o.remove(s)},s=()=>{d(),c()};p8o.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=jzp){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),p8o.remove(s)},s=()=>{d(),c()};p8o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD,$Li.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD_DIR,$Li.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK,$Li.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK_DIR,$Li.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}}};_8o.DIR_EVENTS={add:Rf.ADD_DIR,rename:Rf.RENAME_DIR,unlink:Rf.UNLINK_DIR};_8o.FILE_EVENTS={add:Rf.ADD,change:Rf.CHANGE,rename:Rf.RENAME,unlink:Rf.UNLINK};var ElS=_8o;var Bzp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mh.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(Mh.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(Mh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Izp=Bzp;var Czp=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}},SlS=Czp;var qzp=class{constructor(){this.inos={},this.paths=new Izp,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 Mh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new SlS(i)}reset(){this.inos={},this.paths=new Izp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Rf.ADD,n),[Rf.ADD];if(n.isDirectory())return this.updateIno(t,Rf.ADD_DIR,n),[Rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Rf.UNLINK,i),[Rf.UNLINK];if(i.isDirectory())return this.updateIno(t,Rf.UNLINK_DIR,i),[Rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Rf.CHANGE,n),[Rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,Rf.UNLINK,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK,Rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD,n),[Rf.UNLINK_DIR,Rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK_DIR,Rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?$Li.FILE:$Li.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)}}},Tzp=qzp;var Rzp=class e extends MlS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(oX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(oX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(oX.READY,n)),this._locker=new ElS(this),this._roots=new Set,this._poller=new Tzp,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&&(Mh.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(oX.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mh.lang.castError(t);return this.emit(oX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(oX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(oX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mh.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)Mh.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 wlS(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=Mh.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=Mra.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??Wbn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&xbn&&u.options.native!==!1)))return!0;if(!xbn)break;let s=Mra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mh.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||xbn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:chc.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=Mra.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||xbn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Wbn,c=r.limit??c8o,[d]=await Mh.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=Mh.fs.getDepth(t);for(let f of d){let p=Mh.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(oX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(oX.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=Mra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new Tzp,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 Mh.lang.noop;if(this.pollerExists(t,r))return Mh.lang.noop;let n={...r,interval:r.pollingInterval??plS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(oX.CLOSE,c),chc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(oX.CLOSE,c),chc.default.unwatchFile(t,i)};return Mh.lang.attempt(o),()=>Mh.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=Mh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mh.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=Mra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mh.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=Mra.default.dirname(t);return(await Mh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mh.lang.noop){if(Mh.lang.isFunction(t))return this.watch([],{},t);if(Mh.lang.isUndefined(t))return this.watch([],r,i);if(Mh.lang.isFunction(r))return this.watch(t,{},r);if(Mh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mh.lang.noop&&this.on(oX.ALL,i),r.readdirMap=void 0,this.ready())}},lhc=Rzp;xlc();var l9a=require("fs/promises"),DlS=require("os"),BlS=se(require("path"),1),cV5=".fern",lV5="logs";function fV5(){return"cli@3.56.10"}var h8o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ot(mr.of((0,DlS.homedir)()),Pe.of(cV5)),r=ot(t,Pe.of(lV5));await ni(r)||await(0,l9a.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ot(r,Pe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${BlS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2439
|
+
`+qi.dump(c)),a.logger.info(Ot.green(`Added ${t} generator`)))})}))}var BaS=require("fs/promises"),IaS=se(OX(),1);async function CaS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new Yka,o=VR5(await a.check({from:await DaS({context:e,filepath:t,flagName:"from"}),to:await DaS({context:e,filepath:r,flagName:"to"})})),c=GR5(e,n),{bump:d,errors:s}=WR5(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=IaS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new yS;return{bump:u,nextVersion:f,errors:s}}async function DaS({context:e,filepath:t,flagName:r}){let i=mr.of(xo(OO(),t));if(!await ni(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new yS;let n=await(0,BaS.readFile)(i,"utf-8"),a=sa.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new yS;return a.value}function VR5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function WR5(e,t){return{bump:xR5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function xR5(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 GR5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=HR5(HAc(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 yS}}function HR5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}bE();var KdS=se(nRp(),1),$dS=se(nhc(),1),Fhc=require("fs/promises"),JdS=se(require("http"),1),YdS=se(require("path"),1);var MlS=require("events"),chc=se(require("fs"),1),Mra=se(require("path"),1);var llS=se(require("os"),1),flS=300,Wbn=20,c8o=1e7,dlS=llS.default.platform();var iV5=dlS==="darwin",Pzp=dlS==="win32",xbn=iV5||Pzp,plS=3e3,_lS=2e4,jzp=1250;var $Li;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})($Li||($Li={}));var Sra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Sra||(Sra={}));var l8o;(function(e){e.CHANGE="change",e.ERROR="error"})(l8o||(l8o={}));var Rf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Rf||(Rf={}));var oX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(oX||(oX={}));var nV5=(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,M=A>=t||j>=a;return[g,M]},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,M=t-A,w=a-j,E=Math.min(M,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),M=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return M?f(A):h(A)};return m.cancel=p,m.flush=_,m},ahc=nV5;var Mzp=se(require("fs"),1),uhc=se(require("path"),1);var jA=se(require("fs"),1),Vx=require("util");var uJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},JLi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var wzp=se(require("process"),1),hlS=wzp.default.getuid?!wzp.default.getuid():!1,ylS=1e4,VOe=()=>{};var f8o={isChangeErrorOk:e=>{if(!f8o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!hlS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!f8o.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(!f8o.isNodeError(e))throw e;if(!f8o.isChangeErrorOk(e))throw e}},TT=f8o;var Ezp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=ylS,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()}}}}},blS=new Ezp;var sJi=(e,t)=>function(i){return function n(...a){return blS.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)})}},cJi=(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 aV5={attempt:{chmod:uJi((0,Vx.promisify)(jA.default.chmod),TT.onChangeError),chown:uJi((0,Vx.promisify)(jA.default.chown),TT.onChangeError),close:uJi((0,Vx.promisify)(jA.default.close),VOe),fsync:uJi((0,Vx.promisify)(jA.default.fsync),VOe),mkdir:uJi((0,Vx.promisify)(jA.default.mkdir),VOe),realpath:uJi((0,Vx.promisify)(jA.default.realpath),VOe),stat:uJi((0,Vx.promisify)(jA.default.stat),VOe),unlink:uJi((0,Vx.promisify)(jA.default.unlink),VOe),chmodSync:JLi(jA.default.chmodSync,TT.onChangeError),chownSync:JLi(jA.default.chownSync,TT.onChangeError),closeSync:JLi(jA.default.closeSync,VOe),existsSync:JLi(jA.default.existsSync,VOe),fsyncSync:JLi(jA.default.fsync,VOe),mkdirSync:JLi(jA.default.mkdirSync,VOe),realpathSync:JLi(jA.default.realpathSync,VOe),statSync:JLi(jA.default.statSync,VOe),unlinkSync:JLi(jA.default.unlinkSync,VOe)},retry:{close:sJi((0,Vx.promisify)(jA.default.close),TT.isRetriableError),fsync:sJi((0,Vx.promisify)(jA.default.fsync),TT.isRetriableError),open:sJi((0,Vx.promisify)(jA.default.open),TT.isRetriableError),readFile:sJi((0,Vx.promisify)(jA.default.readFile),TT.isRetriableError),rename:sJi((0,Vx.promisify)(jA.default.rename),TT.isRetriableError),stat:sJi((0,Vx.promisify)(jA.default.stat),TT.isRetriableError),write:sJi((0,Vx.promisify)(jA.default.write),TT.isRetriableError),writeFile:sJi((0,Vx.promisify)(jA.default.writeFile),TT.isRetriableError),closeSync:cJi(jA.default.closeSync,TT.isRetriableError),fsyncSync:cJi(jA.default.fsyncSync,TT.isRetriableError),openSync:cJi(jA.default.openSync,TT.isRetriableError),readFileSync:cJi(jA.default.readFileSync,TT.isRetriableError),renameSync:cJi(jA.default.renameSync,TT.isRetriableError),statSync:cJi(jA.default.statSync,TT.isRetriableError),writeSync:cJi(jA.default.writeSync,TT.isRetriableError),writeFileSync:cJi(jA.default.writeFileSync,TT.isRetriableError)}},vlS=aV5;var ohc=se(require("fs"),1),d8o=se(require("path"),1);var Szp=()=>{};var oV5=()=>{let e=Szp,t=Szp,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}},glS=oV5;var uV5=()=>{let{promise:e,resolve:t,isPending:r}=glS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},OlS=uV5;var mlS={then:e=>{e()}};var AlS=e=>Array.isArray(e)?e:[e],PlS=e=>typeof e=="function";var sV5=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=AlS(a).map(Q=>PlS(Q)?Q:U=>Q.test(U)),c=Q=>o.some(U=>U(Q)),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:M,increment:w,decrement:E}=OlS(),B=0,q=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.directories.push(U),Q.directoriesNames.add(ce),u.push(U),f.add(ce),p.propertyIsEnumerable(ce)||(p[ce]=[]),p[ce].push(U),g.add(U),!(ae>=i)&&(B>=n||W(U,ae+1)))},R=(Q,U,ce)=>{g.has(U)||B>=n||(B+=1,Q.files.push(U),Q.filesNames.add(ce),_.push(U),h.add(ce),y.propertyIsEnumerable(ce)||(y[ce]=[]),y[ce].push(U),g.add(U))},T=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.symlinks.push(U),Q.symlinksNames.add(ce),b.push(U),v.add(ce),O.propertyIsEnumerable(ce)||(O[ce]=[]),O[ce].push(U),g.add(U),r&&(ae>=i||B>=n||Oe(U,ae+1)))},K=(Q,U,ce,ae,fe)=>{d.aborted||c(U)||(ae.isDirectory()?q(Q,U,ce,fe):ae.isFile()?R(Q,U,ce):ae.isSymbolicLink()&&T(Q,U,ce,fe))},H=(Q,U,ce,ae)=>{if(d.aborted)return;let fe=U===d8o.default.sep?"":d8o.default.sep,ve=ce.name,re=`${U}${fe}${ve}`;c(re)||(ce.isDirectory()?q(Q,re,ve,ae):ce.isFile()?R(Q,re,ve):ce.isSymbolicLink()&&T(Q,re,ve,ae))},z=(Q,U,ce,ae)=>{for(let fe=0,ve=ce.length;fe<ve;fe++)H(Q,U,ce[fe],ae)},W=(Q,U)=>{d.aborted||U>i||B>=n||(w(),ohc.default.readdir(Q,{withFileTypes:!0},(ce,ae)=>{if(ce||d.aborted||!ae.length)return E();(s(ae)||mlS).then(()=>{let ve=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ve,Q,ae,U),E()})}))},Oe=(Q,U)=>{w(),ohc.default.realpath(Q,(ce,ae)=>{if(ce||d.aborted)return E();ohc.default.stat(ae,(fe,ve)=>{if(fe||d.aborted)return E();let re=d8o.default.basename(ae),X=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ve,U),E()})})};return(async(Q,U=1)=>(Q=d8o.default.normalize(Q),g.add(Q),W(Q,U),await M,d.aborted?A:j))(e)},jlS=sV5;var YLi={lang:{debounce:ahc,attempt:e=>{try{return e()}catch(t){return YLi.lang.castError(t)}},castArray:e=>YLi.lang.isArray(e)?e:[e],castError:e=>YLi.lang.isError(e)?e:YLi.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(YLi.lang.isNaN(e))return YLi.lang.isNaN(t);if(YLi.lang.isPrimitive(e)||YLi.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(uhc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Mzp.default.realpathSync.native(e):Mzp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===uhc.default.sep&&t.length-e.length>uhc.default.sep.length,poll:(e,t=_lS)=>vlS.retry.stat(t)(e,{bigint:!0}).catch(YLi.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 jlS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mh=YLi;var shc=se(require("path"),1);var Dzp=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||Mh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=flS){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=Mh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Rf.CHANGE&&c===Rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),o=this.options.limit??c8o,[c,d]=await Mh.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())Mh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!xbn&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(shc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(shc.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Rf.ADD?this.onTargetAdd(i):r===Rf.ADD_DIR?this.onTargetAddDir(i):r===Rf.CHANGE?this.onTargetChange(i):r===Rf.UNLINK?this.onTargetUnlink(i):r===Rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Sra.CHANGE,r){if(this.watcher.isClosed())return;let i=shc.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){Pzp&&t.code==="EPERM"?this.onWatcherChange(Sra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(l8o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(l8o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Sra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&xbn&&this.options.native!==!1?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),i=this.options.limit??c8o,[n,a]=await Mh.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(Sra.CHANGE,c,t)}))}}},wlS=Dzp;var uX={interval:100,intervalId:void 0,fns:new Map,init:()=>{uX.intervalId||(uX.intervalId=setInterval(uX.resolve,uX.interval))},reset:()=>{uX.intervalId&&(clearInterval(uX.intervalId),delete uX.intervalId)},add:(e,t)=>{uX.fns.set(e,Date.now()+t),uX.init()},remove:e=>{uX.fns.delete(e)},resolve:()=>{if(!uX.fns.size)return uX.reset();let e=Date.now();for(let[t,r]of uX.fns)r>=e||(uX.remove(t),t())}},p8o=uX;var _8o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=jzp){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(Mh.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),p8o.remove(s)},s=()=>{d(),c()};p8o.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=jzp){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),p8o.remove(s)},s=()=>{d(),c()};p8o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD,$Li.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD_DIR,$Li.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK,$Li.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK_DIR,$Li.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}}};_8o.DIR_EVENTS={add:Rf.ADD_DIR,rename:Rf.RENAME_DIR,unlink:Rf.UNLINK_DIR};_8o.FILE_EVENTS={add:Rf.ADD,change:Rf.CHANGE,rename:Rf.RENAME,unlink:Rf.UNLINK};var ElS=_8o;var Bzp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mh.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(Mh.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(Mh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Izp=Bzp;var Czp=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}},SlS=Czp;var qzp=class{constructor(){this.inos={},this.paths=new Izp,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 Mh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new SlS(i)}reset(){this.inos={},this.paths=new Izp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Rf.ADD,n),[Rf.ADD];if(n.isDirectory())return this.updateIno(t,Rf.ADD_DIR,n),[Rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Rf.UNLINK,i),[Rf.UNLINK];if(i.isDirectory())return this.updateIno(t,Rf.UNLINK_DIR,i),[Rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Rf.CHANGE,n),[Rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,Rf.UNLINK,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK,Rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD,n),[Rf.UNLINK_DIR,Rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK_DIR,Rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?$Li.FILE:$Li.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)}}},Tzp=qzp;var Rzp=class e extends MlS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(oX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(oX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(oX.READY,n)),this._locker=new ElS(this),this._roots=new Set,this._poller=new Tzp,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&&(Mh.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(oX.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mh.lang.castError(t);return this.emit(oX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(oX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(oX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mh.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)Mh.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 wlS(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=Mh.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=Mra.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??Wbn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&xbn&&u.options.native!==!1)))return!0;if(!xbn)break;let s=Mra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mh.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||xbn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:chc.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=Mra.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||xbn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Wbn,c=r.limit??c8o,[d]=await Mh.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=Mh.fs.getDepth(t);for(let f of d){let p=Mh.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(oX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(oX.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=Mra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new Tzp,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 Mh.lang.noop;if(this.pollerExists(t,r))return Mh.lang.noop;let n={...r,interval:r.pollingInterval??plS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(oX.CLOSE,c),chc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(oX.CLOSE,c),chc.default.unwatchFile(t,i)};return Mh.lang.attempt(o),()=>Mh.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=Mh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mh.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=Mra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mh.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=Mra.default.dirname(t);return(await Mh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mh.lang.noop){if(Mh.lang.isFunction(t))return this.watch([],{},t);if(Mh.lang.isUndefined(t))return this.watch([],r,i);if(Mh.lang.isFunction(r))return this.watch(t,{},r);if(Mh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mh.lang.noop&&this.on(oX.ALL,i),r.readdirMap=void 0,this.ready())}},lhc=Rzp;xlc();var l9a=require("fs/promises"),DlS=require("os"),BlS=se(require("path"),1),cV5=".fern",lV5="logs";function fV5(){return"cli@3.57.0"}var h8o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ot(mr.of((0,DlS.homedir)()),Pe.of(cV5)),r=ot(t,Pe.of(lV5));await ni(r)||await(0,l9a.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ot(r,Pe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${BlS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2440
2440
|
`);await(0,l9a.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)+`
|
|
2441
2441
|
`;try{await(0,l9a.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:fV5(),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 rNp=se(xzp(),1),SdS=se(WJs(),1),WOe=require("fs/promises"),MdS=require("os"),DdS=se(VQ(),1),BdS=se(wdS(),1),Mhc=process.platform==="win32",tNp=Ot.cyan("[docs]:"),zV5="etag",NV5=23,EdS=e=>e.padEnd(NV5," "),FV5="preview",QV5="app-preview",UV5="bundle",LV5=".next",VV5="standalone",WV5=".fern",xV5="packages/fern-docs/bundle/.next/server/instrumentation.js",GV5=".npmrc",HV5=".pnpmfile.cjs",KV5="pnpm-workspace.yaml",$V5='Cannot find matching keyid: {"signatures":';function JV5(){return ot(mr.of((0,MdS.homedir)()),Pe.of(WV5))}function f9a({app:e=!1}){return ot(JV5(),Pe.of(e?QV5:FV5))}function Kbn({app:e=!1}){return ot(f9a({app:e}),Pe.of(e?LV5:UV5))}function v8o({app:e=!1}){return ot(Kbn({app:e}),Pe.of(VV5))}function YV5({app:e=!1}){return ot(v8o({app:e}),Pe.of(xV5))}function XV5({app:e=!1}){return ot(v8o({app:e}),Pe.of(KV5))}function ZV5({app:e=!1}){return ot(v8o({app:e}),Pe.of(HV5))}function kV5({app:e=!1}){return ot(v8o({app:e}),Pe.of(GV5))}function Ira(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function e35({app:e=!1}){return ot(f9a({app:e}),Pe.of(zV5))}var t35=`module.exports = {
|
|
2442
2442
|
hooks: {
|
|
@@ -2522,7 +2522,7 @@ More information: https://mdxjs.com/docs/troubleshooting-mdx`);return n.stack=""
|
|
|
2522
2522
|
`)}function Ex5(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function Sx5(e){switch(e){case"fatal":return Ma.Error;case"error":return Ma.Error;case"warning":return Ma.Warn;default:de(e)}}function Mx5(e){switch(e){case"fatal":return Ot.red("[error]");case"error":return Ot.red("[error]");case"warning":return Ot.yellow("[warning]");default:de(e)}}function Dx5({stats:e,context:t,logWarnings:r,elapsedMillis:i=0}){let{numFatal:n,numErrors:a,numWarnings:o}=e,c=i>0?` in ${(i/1e3).toFixed(3)} seconds.`:".",d=`Found ${n+a} errors and ${o} warnings`+c;!r&&o>0&&(d+=" Run fern check --warnings to print out the warnings not shown."),n+a>0?t.logger.error(d):o>0?t.logger.warn(d):t.logger.info(Ot.green("\u2713 All checks passed"))}function Bx5(e){let t=0,r=0,i=0;for(let n of e)switch(n.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":i+=1;continue;default:de(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function DhS({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,errorOnBrokenLinks:n,excludeRules:a}){e.config.settings?.substituteEnvVars&&(e.config=kz(e.config,{onError:u=>i.failAndThrow(u)}));let o=performance.now(),c=await m9a(e,i,t,r,!1,a),d=performance.now()-o,s=c.some(u=>u.severity==="fatal"||u.severity==="error");return n&&(s=s||c.some(u=>u.name==="valid-markdown-links")),{violations:c,elapsedMillis:d,hasErrors:s}}async function P9a({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,logSummary:o=!0,excludeRules:c}){e.config.settings?.substituteEnvVars&&(e.config=kz(e.config,{onError:p=>i.failAndThrow(p)}));let d=performance.now(),s=await m9a(e,i,t,r,!1,c),u=performance.now()-d,{hasErrors:f}=A9a({violations:s,context:i,logWarnings:n,logSummary:o,logBreadcrumbs:!1,elapsedMillis:u});return a&&(f=f||s.some(p=>p.name==="valid-markdown-links")),{hasErrors:f}}async function BhS({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,excludeRules:o}){let{hasErrors:c}=await P9a({workspace:e,context:i,logWarnings:n,apiWorkspaces:t,ossWorkspaces:r,errorOnBrokenLinks:a,excludeRules:o});c&&i.failAndThrow()}async function IhS({loadProject:e,cliContext:t,port:r,bundlePath:i,brokenLinks:n,legacyPreview:a,backendPort:o,forceDownload:c}){let d=await e(),s=d.docsWorkspaces;s!=null&&(a&&(await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --legacy"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info(`Starting server on port ${r}`),await ONp({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await P9a({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await Dx(f),excludeRules:_}):await P9a({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await Dx(f),excludeRules:_})},context:u,port:r,bundlePath:i})})),await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --beta"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info("Bootstrapping docs preview (this may take a few seconds)..."),await vNp({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await P9a({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await Dx(f),excludeRules:_}):await P9a({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await Dx(f),excludeRules:_})},context:u,port:r,bundlePath:i,backendPort:o,forceDownload:c})}))}var Qra=require("fs/promises"),oSe=se(EyS(),1);async function R55({previewUrl:e,files:t,token:r}){let i=t.join(","),n=`https://${e}/api/fern-docs/get-slug-for-file?files=${encodeURIComponent(i)}`,a=await fetch(n,{method:"GET",headers:{FERN_TOKEN:r}});if(!a.ok){let o=await a.text();throw new Error(`Failed to get slugs for files: ${a.status} ${a.statusText} - ${o}`)}return await a.json()}async function SyS({browser:e,url:t,outputPath:r,token:i}){let n=await e.newPage();try{await n.setViewport({width:1440,height:900,deviceScaleFactor:2}),i&&await n.setExtraHTTPHeaders({FERN_TOKEN:i});let a=await n.goto(t,{waitUntil:"networkidle2",timeout:3e4});return!a||a.status()===404?(await n.close(),!1):(await n.screenshot({path:r,fullPage:!0}),await n.close(),!0)}catch{return await n.close(),!1}}function z55(e){return e.replace(/\//g,"-")}function CFp(e,t,r,i,n,a){for(let o=0;o<n;o++){let c=(r*n+o)*4,d=(i*n+o)*4,s=Math.abs((e[c]??0)-(t[d]??0)),u=Math.abs((e[c+1]??0)-(t[d+1]??0)),f=Math.abs((e[c+2]??0)-(t[d+2]??0));if(s>a||u>a||f>a)return!0}return!1}function N55(e,t,r,i,n,a,o=.1,c=5e3,d=100){let s=Math.floor(o*255),u=-1,f=Math.min(n,a);for(let j=0;j<f;j++)if(CFp(e,t,j,j,r,s)){u=j;break}if(u===-1)if(n!==a)u=f;else return[];let p=20,_=u,h=Math.max(n,a);for(let j=0;j<h;j++){let M=n-1-j,w=a-1-j;if(M<0||w<0){_=Math.max(n,a)-1-j+1;break}if(CFp(e,t,M,w,r,s)){let E=1;for(let B=j+1;B<Math.min(j+p,h);B++){let q=n-1-B,R=a-1-B;if(q<0||R<0){E++;continue}if(CFp(e,t,q,R,r,s))E++;else break}if(E>=p){_=Math.min(M,w);break}}}_<u&&(_=u);let y=Math.max(0,u-d),b=Math.min(i-1,_+d),v=100,O=r,m=0;for(let j=u;j<=Math.min(_,i-1);j++)for(let M=0;M<r;M++){let w=(j*r+M)*4,E=Math.abs((e[w]??0)-(t[w]??0)),B=Math.abs((e[w+1]??0)-(t[w+1]??0)),q=Math.abs((e[w+2]??0)-(t[w+2]??0));(E>s||B>s||q>s)&&(M<O&&(O=M),M>m&&(m=M))}O>m?(O=0,m=r-1):(O=Math.max(0,O-v),m=Math.min(r-1,m+v));let g={minX:O,minY:y,maxX:m,maxY:b};return(g.maxX-g.minX)*(g.maxY-g.minY)<c?[]:[g]}function MyS(e,t,r=50){let i=Math.max(0,t.minX-r),n=Math.max(0,t.minY-r),a=Math.min(e.width,t.maxX+r),o=Math.min(e.height,t.maxY+r),c=a-i,d=o-n,s=new oSe.PNG({width:c,height:d});return oSe.PNG.bitblt(e,s,i,n,c,d,0,0),s}function DyS(e,t,r,i,n,a,o){let[c,d,s,u]=a;for(let f=0;f<o;f++){for(let p=t;p<t+i;p++){let _=((r+f)*e.width+p)*4,h=((r+n-1-f)*e.width+p)*4;e.data[_]=c,e.data[_+1]=d,e.data[_+2]=s,e.data[_+3]=u,e.data[h]=c,e.data[h+1]=d,e.data[h+2]=s,e.data[h+3]=u}for(let p=r;p<r+n;p++){let _=(p*e.width+(t+f))*4,h=(p*e.width+(t+i-1-f))*4;e.data[_]=c,e.data[_+1]=d,e.data[_+2]=s,e.data[_+3]=u,e.data[h]=c,e.data[h+1]=d,e.data[h+2]=s,e.data[h+3]=u}}}function F55(e,t,r=20,i=!0){let n=e.width+r+t.width,a=Math.max(e.height,t.height),o=new oSe.PNG({width:n,height:a});if(o.data.fill(255),oSe.PNG.bitblt(e,o,0,0,e.width,e.height,0,0),oSe.PNG.bitblt(t,o,0,0,t.width,t.height,e.width+r,0),i){let c=[255,196,0,255],d=3;DyS(o,0,0,e.width,e.height,c,d),DyS(o,e.width+r,0,t.width,t.height,c,d)}return o}async function Q55({beforePath:e,afterPath:t,comparisonBasePath:r}){let i=oSe.PNG.sync.read(await(0,Qra.readFile)(e)),n=oSe.PNG.sync.read(await(0,Qra.readFile)(t)),a=i.height,o=n.height,c=Math.max(i.width,n.width),d=Math.max(i.height,n.height),s=new oSe.PNG({width:c,height:d}),u=new oSe.PNG({width:c,height:d});s.data.fill(255),u.data.fill(255),oSe.PNG.bitblt(i,s,0,0,i.width,i.height,0,0),oSe.PNG.bitblt(n,u,0,0,n.width,n.height,0,0);let f=new Uint8Array(s.data.buffer,s.data.byteOffset,s.data.length),p=new Uint8Array(u.data.buffer,u.data.byteOffset,u.data.length),_=N55(f,p,c,d,a,o),h=[];if(_.length===0)return h;let y=r.endsWith(".png")?r.slice(0,r.length-4):r;for(let b=0;b<_.length;b++){let v=_[b];if(v==null)continue;let O=v.maxX-v.minX,m=v.maxY-v.minY,g=O*m,A=c*d,j=g/A*100,M=MyS(s,v),w=MyS(u,v),E=F55(M,w,20,!0),B=`${y}-region-${b+1}.png`,q=oSe.PNG.sync.write(E);await(0,Qra.writeFile)(B,new Uint8Array(q)),h.push({changePercent:j,boundingBox:v,comparisonPath:B})}return h}function U55(e){if(e.instances==null||e.instances.length===0)throw new Error("No docs instances configured in docs.yml");let t=e.instances[0];if(t==null)throw new Error("No docs instances configured in docs.yml");let i=t["custom-domain"]??t.url;!i.startsWith("https://")&&!i.startsWith("http://")&&(i=`https://${i}`);try{let n=new URL(i),a=n.pathname!=="/"?n.pathname.replace(/\/$/,""):null;return{baseUrl:`${n.protocol}//${n.host}`,basePath:a}}catch{return{baseUrl:i,basePath:null}}}async function ByS({cliContext:e,project:t,previewUrl:r,files:i,outputDir:n}){let a=t.docsWorkspaces;if(a==null)return e.failAndThrow("No docs workspace found. Make sure you have a docs.yml file."),{diffs:[]};let o=await e.runTask(async h=>gV(h));if(o==null)return e.failAndThrow("Failed to authenticate. Please run 'fern login' first."),{diffs:[]};let c=process.env.FERN_TOKEN??o.value,d=U55(a.config),s=r;s.startsWith("https://")?s=s.slice(8):s.startsWith("http://")&&(s=s.slice(7));let u=s.indexOf("/");u!==-1&&(s=s.slice(0,u));let f=await e.runTask(async h=>(h.logger.info(`Resolving slugs for ${i.length} file(s)...`),R55({previewUrl:s,files:i,token:c})));f.authed&&e.logger.warn("The docs require authentication. Screenshots may not capture the full content without proper auth.");let p=mr.of(n.startsWith("/")?n:ot(OO(),Pe.of(n)));await ni(p)||await(0,Qra.mkdir)(p,{recursive:!0});let _=[];return await e.runTask(async h=>{h.logger.info("Starting browser for screenshot capture...");let y=await Cpc({headless:!0,args:["--ignore-certificate-errors","--no-sandbox","--disable-setuid-sandbox"]});try{for(let b of f.mappings){if(b.slug==null){h.logger.warn(`Could not find slug for file: ${b.filePath}`);continue}let v=b.slug,O=z55(v),m=ot(p,Pe.of(`${O}-before.png`)),g=ot(p,Pe.of(`${O}-after.png`)),A=ot(p,Pe.of(`${O}-comparison.png`)),j=`${d.baseUrl}/${v}`,M=`https://${s}/${v}`;h.logger.info(`Capturing screenshots for: ${v}`);let w=await SyS({browser:y,url:j,outputPath:m,token:c});if(!await SyS({browser:y,url:M,outputPath:g,token:c})){h.logger.warn(`Could not capture preview page for: ${v}`);continue}let B=!w;if(w){let q=await Q55({beforePath:m,afterPath:g,comparisonBasePath:A});q.length===0?(h.logger.info(" No visual changes detected"),_.push({file:b.filePath,slug:v,comparison:null,changePercent:0,isNewPage:B})):q.forEach((R,T)=>{h.logger.info(` Region ${T+1}: ${R.changePercent.toFixed(2)}% (split & cropped)`),_.push({file:b.filePath,slug:v,comparison:R.comparisonPath,changePercent:R.changePercent,isNewPage:B})})}else h.logger.info(" New page (no production version)"),_.push({file:b.filePath,slug:v,comparison:null,changePercent:null,isNewPage:B})}}finally{await y.close()}}),{diffs:_}}var L55=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i;function V55(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),L55.test(t)}async function IyS({cliContext:e,previewUrl:t}){if(!V55(t)){e.failAndThrow(`Invalid preview URL: ${t}
|
|
2523
2523
|
Only preview sites can be deleted with this command.
|
|
2524
2524
|
Preview URLs follow the pattern: {org}-preview-{hash}.docs.buildwithfern.com
|
|
2525
|
-
Example: acme-preview-abc123.docs.buildwithfern.com`);return}let r=await e.runTask(async i=>gV(i));if(r==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async i=>{i.logger.info(`Deleting preview site: ${t}`);let a=await xxt({token:r.value}).docs.v2.write.deleteDocsSite({url:t});if(a.ok)i.logger.info(Ot.green(`Successfully deleted preview site: ${t}`));else switch(a.error.error){case"UnauthorizedError":return i.failAndThrow("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":return i.failAndThrow(`Preview site not found: ${t}`);default:return i.failAndThrow(`Failed to delete preview site: ${t}`,a.error)}})}async function CyS({cliContext:e,limit:t,page:r}){let i=await e.runTask(async n=>gV(n));if(i==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async n=>{n.logger.info("Fetching preview deployments...");let o=await xxt({token:i.value}).docs.v2.read.listAllDocsUrls({page:r,limit:t??100});if(!o.ok)return n.failAndThrow("Failed to fetch docs URLs",o.error);let c=/-preview-[a-f0-9-]+\.docs\.buildwithfern\.com$/,d=o.body.urls.filter(s=>c.test(s.domain)).map(s=>({url:s.basePath!=null?`${s.domain}${s.basePath}`:s.domain,organizationId:s.organizationId,updatedAt:s.updatedAt}));if(d.length===0){n.logger.info("No preview deployments found.");return}n.logger.info(Ot.bold(`
|
|
2525
|
+
Example: acme-preview-abc123.docs.buildwithfern.com`);return}let r=await e.runTask(async i=>gV(i));if(r==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async i=>{i.logger.info(`Deleting preview site: ${t}`);let a=await xxt({token:r.value}).docs.v2.write.deleteDocsSite({url:t});if(a.ok)i.logger.info(Ot.green(`Successfully deleted preview site: ${t}`));else switch(a.error.error){case"UnauthorizedError":return i.failAndThrow("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":return i.failAndThrow(`Preview site not found: ${t}`);default:return i.failAndThrow(`Failed to delete preview site: ${t}`,a.error)}})}async function CyS({cliContext:e,limit:t,page:r}){let i=await e.runTask(async n=>gV(n));if(i==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async n=>{n.logger.info("Fetching preview deployments...");let o=await xxt({token:i.value}).docs.v2.read.listAllDocsUrls({page:r,limit:t??100,preview:!0});if(!o.ok)return n.failAndThrow("Failed to fetch docs URLs",o.error);let c=/-preview-[a-f0-9-]+\.docs\.buildwithfern\.com$/,d=o.body.urls.filter(s=>c.test(s.domain)).map(s=>({url:s.basePath!=null?`${s.domain}${s.basePath}`:s.domain,organizationId:s.organizationId,updatedAt:s.updatedAt}));if(d.length===0){n.logger.info("No preview deployments found.");return}n.logger.info(Ot.bold(`
|
|
2526
2526
|
Found ${d.length} preview deployment(s):
|
|
2527
2527
|
`));for(let s of d){let u=new Date(s.updatedAt).toLocaleString();n.logger.info(` ${Ot.cyan(s.url)}`),n.logger.info(` Organization: ${s.organizationId}`),n.logger.info(` Updated: ${u}
|
|
2528
2528
|
`)}})}var GyS=require("fs/promises");var QyS=Symbol.for("immer-nothing"),qyS=Symbol.for("immer-draftable"),uSe=Symbol.for("immer-state"),W55=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function GOe(e,...t){if(process.env.NODE_ENV!=="production"){let r=W55[e],i=typeof r=="function"?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var I8o=Object.getPrototypeOf;function S9a(e){return!!e&&!!e[uSe]}function Lra(e){return e?UyS(e)||Array.isArray(e)||!!e[qyS]||!!e.constructor?.[qyS]||T8o(e)||Byc(e):!1}var x55=Object.prototype.constructor.toString(),TyS=new WeakMap;function UyS(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let i=TyS.get(r);return i===void 0&&(i=Function.toString.call(r),TyS.set(r,i)),i===x55}function Eyc(e,t,r=!0){Dyc(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((i,n)=>t(n,i,e))}function Dyc(e){let t=e[uSe];return t?t.type_:Array.isArray(e)?1:T8o(e)?2:Byc(e)?3:0}function RFp(e,t){return Dyc(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function LyS(e,t,r){let i=Dyc(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function G55(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function T8o(e){return e instanceof Map}function Byc(e){return e instanceof Set}function Ura(e){return e.copy_||e.base_}function zFp(e,t){if(T8o(e))return new Map(e);if(Byc(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=UyS(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[uSe];let n=Reflect.ownKeys(i);for(let a=0;a<n.length;a++){let o=n[a],c=i[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(i[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(I8o(e),i)}else{let i=I8o(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function LFp(e,t=!1){return Iyc(e)||S9a(e)||!Lra(e)||(Dyc(e)>1&&Object.defineProperties(e,{set:wyc,add:wyc,clear:wyc,delete:wyc}),Object.freeze(e),t&&Object.values(e).forEach(r=>LFp(r,!0))),e}function H55(){GOe(2)}var wyc={value:H55};function Iyc(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var K55={};function Vra(e){let t=K55[e];return t||GOe(0,e),t}var C8o;function VyS(){return C8o}function $55(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function RyS(e,t){t&&(Vra("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function NFp(e){FFp(e),e.drafts_.forEach(J55),e.drafts_=null}function FFp(e){e===C8o&&(C8o=e.parent_)}function zyS(e){return C8o=$55(C8o,e)}function J55(e){let t=e[uSe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function NyS(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[uSe].modified_&&(NFp(t),GOe(4)),Lra(e)&&(e=Syc(t,e),t.parent_||Myc(t,e)),t.patches_&&Vra("Patches").generateReplacementPatches_(r[uSe].base_,e,t.patches_,t.inversePatches_)):e=Syc(t,r,[]),NFp(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==QyS?e:void 0}function Syc(e,t,r){if(Iyc(t))return t;let i=e.immer_.shouldUseStrictIteration(),n=t[uSe];if(!n)return Eyc(t,(a,o)=>FyS(e,n,t,a,o,r),i),t;if(n.scope_!==e)return t;if(!n.modified_)return Myc(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let a=n.copy_,o=a,c=!1;n.type_===3&&(o=new Set(a),a.clear(),c=!0),Eyc(o,(d,s)=>FyS(e,n,a,d,s,r,c),i),Myc(e,a,!1),r&&e.patches_&&Vra("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function FyS(e,t,r,i,n,a,o){if(n==null||typeof n!="object"&&!o)return;let c=Iyc(n);if(!(c&&!o)){if(process.env.NODE_ENV!=="production"&&n===r&&GOe(5),S9a(n)){let d=a&&t&&t.type_!==3&&!RFp(t.assigned_,i)?a.concat(i):void 0,s=Syc(e,n,d);if(LyS(r,i,s),S9a(s))e.canAutoFreeze_=!1;else return}else o&&r.add(n);if(Lra(n)&&!c){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[i]===n&&c)return;Syc(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&(T8o(r)?r.has(i):Object.prototype.propertyIsEnumerable.call(r,i))&&Myc(e,n)}}}function Myc(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&LFp(t,r)}function Y55(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:VyS(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=VFp;r&&(n=[i],a=q8o);let{revoke:o,proxy:c}=Proxy.revocable(n,a);return i.draft_=c,i.revoke_=o,c}var VFp={get(e,t){if(t===uSe)return e;let r=Ura(e);if(!RFp(r,t))return X55(e,r,t);let i=r[t];return e.finalized_||!Lra(i)?i:i===qFp(e.base_,t)?(TFp(e),e.copy_[t]=UFp(i,e)):i},has(e,t){return t in Ura(e)},ownKeys(e){return Reflect.ownKeys(Ura(e))},set(e,t,r){let i=WyS(Ura(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=qFp(Ura(e),t),a=n?.[uSe];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(G55(r,n)&&(r!==void 0||RFp(e.base_,t)))return!0;TFp(e),QFp(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return qFp(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,TFp(e),QFp(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Ura(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){GOe(11)},getPrototypeOf(e){return I8o(e.base_)},setPrototypeOf(){GOe(12)}},q8o={};Eyc(VFp,(e,t)=>{q8o[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});q8o.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&GOe(13),q8o.set.call(this,e,t,void 0)};q8o.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&GOe(14),VFp.set.call(this,e[0],t,r,e[0])};function qFp(e,t){let r=e[uSe];return(r?Ura(r):e)[t]}function X55(e,t,r){let i=WyS(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function WyS(e,t){if(!(t in e))return;let r=I8o(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=I8o(r)}}function QFp(e){e.modified_||(e.modified_=!0,e.parent_&&QFp(e.parent_))}function TFp(e){e.copy_||(e.copy_=zFp(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Z55=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,i)=>{if(typeof t=="function"&&typeof r!="function"){let a=r;r=t;let o=this;return function(d=a,...s){return o.produce(d,u=>r.call(this,u,...s))}}typeof r!="function"&&GOe(6),i!==void 0&&typeof i!="function"&&GOe(7);let n;if(Lra(t)){let a=zyS(this),o=UFp(t,void 0),c=!0;try{n=r(o),c=!1}finally{c?NFp(a):FFp(a)}return RyS(a,i),NyS(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===QyS&&(n=void 0),this.autoFreeze_&&LFp(n,!0),i){let a=[],o=[];Vra("Patches").generateReplacementPatches_(t,n,a,o),i(a,o)}return n}else GOe(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(o,...c)=>this.produceWithPatches(o,d=>t(d,...c));let i,n;return[this.produce(t,r,(o,c)=>{i=o,n=c}),i,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Lra(e)||GOe(8),S9a(e)&&(e=k55(e));let t=zyS(this),r=UFp(e,void 0);return r[uSe].isManual_=!0,FFp(t),r}finishDraft(e,t){let r=e&&e[uSe];(!r||!r.isManual_)&&GOe(9);let{scope_:i}=r;return RyS(i,t),NyS(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let i=Vra("Patches").applyPatches_;return S9a(e)?i(e,t):this.produce(e,n=>i(n,t))}};function UFp(e,t){let r=T8o(e)?Vra("MapSet").proxyMap_(e,t):Byc(e)?Vra("MapSet").proxySet_(e,t):Y55(e,t);return(t?t.scope_:VyS()).drafts_.push(r),r}function k55(e){return S9a(e)||GOe(10,e),xyS(e)}function xyS(e){if(!Lra(e)||Iyc(e))return e;let t=e[uSe],r,i=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=zFp(e,t.scope_.immer_.useStrictShallowCopy_),i=t.scope_.immer_.shouldUseStrictIteration()}else r=zFp(e,!0);return Eyc(r,(n,a)=>{LyS(r,n,xyS(a))},i),t&&(t.finalized_=!1),r}var e65=new Z55,Cyc=e65.produce;function t65(e){return e.endsWith(`
|
package/package.json
CHANGED