@mintlify/cli 4.1.63 → 4.1.64

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.
@@ -0,0 +1,17 @@
1
+ import { createRequire as __mintCreateRequire } from 'node:module';
2
+ import { fileURLToPath as __mintFileURLToPath } from 'node:url';
3
+ import { dirname as __mintDirname } from 'node:path';
4
+ const require = __mintCreateRequire(import.meta.url);
5
+ const __filename = __mintFileURLToPath(import.meta.url);
6
+ const __dirname = __mintDirname(__filename);
7
+ import{dirname as e,posix as t,sep as n}from"path";import{createReadStream as r}from"node:fs";import{createInterface as i}from"node:readline";import{AsyncLocalStorage as a}from"node:async_hooks";function o(){let e=s();return async t=>{for(let n of t)n.module=e(n.filename);return t}}function s(r=process.argv[1]?e(process.argv[1]):process.cwd(),i=n===`\\`){let a=i?c(r):r;return e=>{if(!e)return;let n=i?c(e):e,{dir:r,base:o,ext:s}=t.parse(n);(s===`.js`||s===`.mjs`||s===`.cjs`)&&(o=o.slice(0,-1*s.length));let l=decodeURIComponent(o);r||=`.`;let u=r.lastIndexOf(`/node_modules`);if(u>-1)return`${r.slice(u+14).replace(/\//g,`.`)}:${l}`;if(r.startsWith(a)){let e=r.slice(a.length+1).replace(/\//g,`.`);return e?`${e}:${l}`:l}return l}}function c(e){return e.replace(/^[A-Z]:/,``).replace(/\\/g,`/`)}const l=e=>{if(`flags`in e){let t=d(e.flags),n=f(e.flags);return{...e,featureFlags:t,featureFlagPayloads:n}}{let t=e.featureFlags??{},n=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,m(t)])),r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,u(e,t,n[e])]));return{...e,featureFlags:t,featureFlagPayloads:n,flags:r}}};function u(e,t,n){return{key:e,enabled:typeof t==`string`||t,variant:typeof t==`string`?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:n?JSON.stringify(n):void 0,description:void 0}}}const d=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,p(t)]).filter(([,e])=>e!==void 0)),f=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(e=>{let n=t[e];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(e=>{let n=t[e].metadata?.payload;return[e,n?m(n):void 0]}))},p=e=>e===void 0?void 0:e.variant??e.enabled,m=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},h=`0123456789abcdef`
8
+ /*! For license information please see uuidv7.mjs.LICENSE.txt */
9
+ /**
10
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
11
+ *
12
+ * @license Apache-2.0
13
+ * @copyright 2021-2023 LiosK
14
+ * @packageDocumentation
15
+ */
16
+ ;var g=class e{constructor(e){this.bytes=e}static ofInner(t){if(t.length===16)return new e(t);throw TypeError(`not 128-bit length`)}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||t<0||n<0||r<0||i<0||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw RangeError(`invalid field value`);let a=/* @__PURE__ */ 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|n>>>8,a[7]=n,a[8]=128|r>>>24,a[9]=r>>>16,a[10]=r>>>8,a[11]=r,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,new e(a)}static parse(t){let n;switch(t.length){case 32:n=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:n=/^([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:n=/^\{([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:n=/^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(``)}if(n){let t=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<16;e+=4){let r=parseInt(n.substring(2*e,2*e+8),16);t[e+0]=r>>>24,t[e+1]=r>>>16,t[e+2]=r>>>8,t[e+3]=r}return new e(t)}throw SyntaxError(`could not parse UUID string`)}toString(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=h.charAt(this.bytes[t]>>>4),e+=h.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+=`-`);return e}toHex(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=h.charAt(this.bytes[t]>>>4),e+=h.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error(`unreachable`);if(e<=7)return this.bytes.every(e=>e===0)?`NIL`:`VAR_0`;if(e<=11)return`VAR_10`;if(e<=13)return`VAR_110`;if(e<=15)return this.bytes.every(e=>e===255)?`MAX`:`VAR_RESERVED`;throw Error(`unreachable`)}getVersion(){return this.getVariant()===`VAR_10`?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},ee=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??te()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return g.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 e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,g.ofInner(e)}};const te=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())});let ne;const _=()=>re().toString(),re=()=>(ne||=new ee).generate(),ie=/* @__PURE__ */ `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`.split(`,`),ae=function(e,t=[]){if(!e)return!1;let n=e.toLowerCase();return ie.concat(t).some(e=>{let t=e.toLowerCase();return n.indexOf(t)!==-1})};var v=/*#__PURE__*/ function(e){return e.AnonymousId=`anonymous_id`,e.DistinctId=`distinct_id`,e.Props=`props`,e.FeatureFlagDetails=`feature_flag_details`,e.FeatureFlags=`feature_flags`,e.FeatureFlagPayloads=`feature_flag_payloads`,e.BootstrapFeatureFlagDetails=`bootstrap_feature_flag_details`,e.BootstrapFeatureFlags=`bootstrap_feature_flags`,e.BootstrapFeatureFlagPayloads=`bootstrap_feature_flag_payloads`,e.OverrideFeatureFlags=`override_feature_flags`,e.Queue=`queue`,e.OptedOut=`opted_out`,e.SessionId=`session_id`,e.SessionStartTimestamp=`session_start_timestamp`,e.SessionLastTimestamp=`session_timestamp`,e.PersonProperties=`person_properties`,e.GroupProperties=`group_properties`,e.InstalledAppBuild=`installed_app_build`,e.InstalledAppVersion=`installed_app_version`,e.SessionReplay=`session_replay`,e.SurveyLastSeenDate=`survey_last_seen_date`,e.SurveysSeen=`surveys_seen`,e.Surveys=`surveys`,e.RemoteConfig=`remote_config`,e.FlagsEndpointWasHit=`flags_endpoint_was_hit`,e}({});const oe=Array.isArray,y=Object.prototype;y.hasOwnProperty;const b=y.toString,se=oe||function(e){return b.call(e)===`[object Array]`},ce=e=>e===void 0,x=e=>b.call(e)==`[object String]`,le=e=>x(e)&&e.trim().length===0,ue=e=>b.call(e)==`[object Number]`,de=e=>e instanceof Error;function fe(e,t){try{return e instanceof t}catch{return!1}}function pe(e){return typeof e!=`object`||!e}function me(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function S(e){return!ce(Event)&&fe(e,Event)}function he(e){return me(e,`Object`)}function C(e,t,n,r,i){return t>n&&(r.warn(`min cannot be greater than max.`),t=n),ue(e)?e>n?(r.warn(` cannot be greater than max: `+n+`. Using max value instead.`),n):e<t?(r.warn(` cannot be less than min: `+t+`. Using min value instead.`),t):e:(r.warn(` must be a number. using max or fallback. max: `+n+`, fallback: `+i),C(i||n,t,n,r))}var ge=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=C(e.bucketSize,0,100,e._logger),this._refillRate=C(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=C(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,r=Math.floor(n/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess+=r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),r=this._buckets[n];return r?this._applyRefill(r,t):(r={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=r),r.tokens===0||(r.tokens--,r.tokens===0&&this._onBucketRateLimited?.(e),r.tokens===0)}stop(){this._buckets={}}},_e=class{add(e){let t=_();return this.promiseByIds[t]=e,e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds),t=e.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function ve(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}const w=(e,t,n)=>{function r(r,...i){t(()=>{let t=n[r];t(e,...i)})}return{info:(...e)=>{r(`log`,...e)},warn:(...e)=>{r(`warn`,...e)},error:(...e)=>{r(`error`,...e)},critical:(...t)=>{n.error(e,...t)},createLogger:r=>w(`${e} ${r}`,t,n)}},ye=e=>e();function be(e,t=ye){return w(e,t,ve())}function xe(e,t){if(!e||typeof e!=`string`||Se(e))throw Error(t)}function Se(e){return e.trim().length===0}function Ce(e){return e?.replace(/\/+$/,``)}async function we(e,t){let n=null;for(let r=0;r<t.retryCount+1;r++){r>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(n=e,!t.retryCheck(e))throw e}}throw n}function T(){return(/* @__PURE__ */ new Date()).toISOString()}function E(e,t){let n=setTimeout(e,t);return n?.unref&&n?.unref(),n}const Te=e=>e instanceof Error;function D(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}var Ee=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events[`*`]||[])n(e,t)}};function De(){return`CompressionStream`in globalThis}async function O(e,t=!0){try{let t=new Blob([e],{type:`text/plain`}).stream().pipeThrough(new CompressionStream(`gzip`));return await new Response(t).blob()}catch(e){return t&&console.error(`Failed to gzip compress data`,e),null}}var k=class extends Error{constructor(e,t){super(`HTTP error while fetching PostHog: status=`+e.status+`, reqByteLength=`+t),this.response=e,this.reqByteLength=t,this.name=`PostHogFetchHttpError`}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},A=class extends Error{constructor(e){super(`Network error while fetching PostHog`,e instanceof Error?{cause:e}:{}),this.error=e,this.name=`PostHogFetchNetworkError`}};async function j(e){if(e instanceof k){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 M(e){return typeof e==`object`&&(e instanceof k||e instanceof A)}function N(e){return typeof e==`object`&&e instanceof k&&e.status===413}var Oe=class{constructor(e,t={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new _e,this._events=new Ee,this._isInitialized=!1,xe(e,`You must pass your PostHog project's api key.`),this.apiKey=e,this.host=Ce(t.host||`https://us.i.posthog.com`),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:M},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=t.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this.evaluationEnvironments=t?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=be(`[PostHog]`,this.logMsgIfDebug.bind(this)),this.disableCompression=!De()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(v.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(v.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(v.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on(`*`,(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};this.enqueue(`identify`,r,n)})}async identifyStatelessImmediate(e,t,n){let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};await this.sendImmediate(`identify`,r,n)}captureStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue(`capture`,i,r)})}async captureStatelessImmediate(e,t,n,r){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate(`capture`,i,r)}aliasStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue(`alias`,i,r)})}async aliasStatelessImmediate(e,t,n,r){let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate(`alias`,i,r)}groupIdentifyStateless(e,t,n,r,i,a){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:`$groupidentify`,properties:{$group_type:e,$group_key:t,$group_set:n||{},...a||{}}});this.enqueue(`capture`,o,r)})}async getRemoteConfig(){await this._initPromise;let e=this.host;e===`https://us.i.posthog.com`?e=`https://us-assets.i.posthog.com`:e===`https://eu.i.posthog.com`&&(e=`https://eu-assets.i.posthog.com`);let t=`${e}/array/${this.apiKey}/config`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this._logger.error(`Remote config could not be loaded`,e),this._events.emit(`error`,e)})}async getFlags(e,t={},n={},r={},i={},a=!0){await this._initPromise;let o=a?`&config=true`:``,s=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:r,...i};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(c.evaluation_environments=this.evaluationEnvironments);let u={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`},body:JSON.stringify(c)};return this._logger.info(`Flags URL`,s),this.fetchWithRetry(s,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>l(e)).catch(e=>{this._events.emit(`error`,e)})}async getFeatureFlagStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,n,r,i,a);if(o===void 0)return{response:void 0,requestId:void 0};let s=p(o.response);return s===void 0&&(s=!1),{response:s,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,n,r,i,a,[e]);if(o!==void 0)return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,n,r,i,a,[e]);if(!o)return;let s=o[e];return s===void 0?null:s}async getFeatureFlagPayloadsStateless(e,t={},n={},r={},i,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)).payloads}async getFeatureFlagsStateless(e,t={},n={},r={},i,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,n,r,i,a);return o?{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o={};(i??this.disableGeoip)&&(o.geoip_disable=!0),a&&(o.flag_keys_to_evaluate=a);let s=await this.getFlags(e,t,n,r,o);if(s!==void 0)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}):s}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this._logger.info(`Loading surveys is disabled.`),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}},n=(await this.fetchWithRetry(e,t).then(e=>{if(e.status!==200||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,n=Error(t);this._logger.error(n),this._events.emit(`error`,Error(t))}else return e.json()}).catch(e=>{this._logger.error(`Surveys API could not be loaded`,e),this._events.emit(`error`,e)}))?.surveys;return n&&this._logger.info(`Surveys fetched from API: `,JSON.stringify(n)),n??[]}get props(){return this._props||=this.getPersistedProperty(v.Props),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(v.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(v.Props,this.props)})}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r=this.prepareMessage(e,t,n),i=this.getPersistedProperty(v.Queue)||[];i.length>=this.maxQueueSize&&(i.shift(),this._logger.info(`Queue is full, the oldest event is dropped.`)),i.push({message:r}),this.setPersistedProperty(v.Queue,i),this._events.emit(e,r),i.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=E(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r={api_key:this.apiKey,batch:[this.prepareMessage(e,t,n)],sent_at:T()};this.historicalMigration&&(r.historical_migration=!0);let i=JSON.stringify(r),a=`${this.host}/batch/`,o=this.disableCompression?null:await O(i,this.isDebug),s={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...o!==null&&{"Content-Encoding":`gzip`}},body:o||i};try{await this.fetchWithRetry(a,s)}catch(e){this._events.emit(`error`,e)}}prepareMessage(e,t,n){let r={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:T(),uuid:n?.uuid?n.uuid:_()};return(n?.disableGeoip??this.disableGeoip)&&(r.properties||={},r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&=(clearTimeout(this._flushTimer),void 0)}flushBackground(){this.flush().catch(async e=>{await j(e)})}async flush(){let e=D([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),D([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==``&&(t[`User-Agent`]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(v.Queue)||[];if(!e.length)return;let t=[],n=e.length;for(;e.length>0&&t.length<n;){let n=e.slice(0,this.maxBatchSize),r=n.map(e=>e.message),i=()=>{let t=(this.getPersistedProperty(v.Queue)||[]).slice(n.length);this.setPersistedProperty(v.Queue,t),e=t},a={api_key:this.apiKey,batch:r,sent_at:T()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),s=`${this.host}/batch/`,c=this.disableCompression?null:await O(o,this.isDebug),l={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...c!==null&&{"Content-Encoding":`gzip`}},body:c||o},u={retryCheck:e=>!N(e)&&M(e)};try{await this.fetchWithRetry(s,l,u)}catch(e){if(N(e)&&r.length>1){this.maxBatchSize=Math.max(1,Math.floor(r.length/2)),this._logger.warn(`Received 413 when sending batch of size ${r.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof A||i(),this._events.emit(`error`,e),e}i(),t.push(...r)}this._events.emit(`flush`,t)}async fetchWithRetry(e,t,n,r){AbortSignal.timeout??=function(e){let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};let i=t.body?t.body:``,a=-1;try{a=i instanceof Blob?i.size:Buffer.byteLength(i,`utf8`)}catch{a=i instanceof Blob?i.size:new TextEncoder().encode(i).length}return await we(async()=>{let n=null;try{n=await this.fetch(e,{signal:AbortSignal.timeout(r??this.requestTimeout),...t})}catch(e){throw new A(e)}if(t.mode!==`no-cors`&&(n.status<200||n.status>=400))throw new k(n,a);return n},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;return this.clearFlushTimer(),Promise.race([new Promise((n,r)=>{E(()=>{this._logger.error(`Timed out while shutting down PostHog`),t=!0,r(`Timeout while shutting down PostHog. Some events may not have been sent.`)},e)}),(async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(v.Queue)||[]).length===0||(await this.flush(),t)););}catch(e){if(!M(e))throw e;await j(e)}})()])}async shutdown(e=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(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};let P,F,I;function ke(e){let t=globalThis._posthogChunkIds;if(!t)return;let n=Object.keys(t);return I&&n.length===F||(F=n.length,I=n.reduce((n,r)=>{P||={};let i=P[r];if(i)n[i[0]]=i[1];else{let i=e(r);for(let e=i.length-1;e>=0;e--){let a=i[e]?.filename,o=t[r];if(a&&o){n[a]=o,P[r]=[a,o];break}}}return n},{})),I}var Ae=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:`generic`},r=this.buildCoercingContext(n,t,0).apply(e),i=this.buildParsingContext(),a=this.parseStacktrace(r,i);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:`error`}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&se(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:`Error`,value:`Unknown error`,stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let r;return e.stack!=``&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,+!!e.synthetic),t.chunkIdMap)),{...e,cause:n,stack:r}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??`generic`,handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:`raw`,frames:e.stack});let r=[n];return e.cause!=null&&r.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),r}buildParsingContext(){return{chunkIdMap:ke(this.stackParser)}}buildCoercingContext(e,t,n=0){let r=(n,r)=>{if(r<=4){let i=this.buildCoercingContext(e,t,r);return this.applyCoercers(n,i)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,n),next:e=>r(e,n+1)}}};const je=/^\s*[-]{4,}$/,Me=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Ne=(e,t)=>{let n=e.match(Me);if(n){let e,r,i,a,o;if(n[1]){i=n[1];let t=i.lastIndexOf(`.`);if(i[t-1]===`.`&&t--,t>0){e=i.slice(0,t),r=i.slice(t+1);let n=e.indexOf(`.Module`);n>0&&(i=i.slice(n+1),e=e.slice(0,n))}a=void 0}r&&(a=e,o=r),r===`<anonymous>`&&(o=void 0,i=void 0),i===void 0&&(o||=`?`,i=a?`${a}.${o}`:o);let s=n[2]?.startsWith(`file://`)?n[2].slice(7):n[2],c=n[5]===`native`;return s?.match(/\/[A-Z]:/)&&(s=s.slice(1)),!s&&n[5]&&!c&&(s=n[5]),{filename:s?decodeURI(s):void 0,module:void 0,function:i,lineno:L(n[3]),colno:L(n[4]),in_app:Pe(s||``,c),platform:t}}if(e.match(je))return{filename:e,platform:t}};function Pe(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 L(e){return parseInt(e||``,10)||void 0}const R=/\(error: (.*)\)/;function Fe(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>({...e,filename:e.filename||Ie(t).filename,function:e.function||`?`}))}function Ie(e){return e[e.length-1]||{}}function Le(e,...t){return(n,r=0)=>{let i=[],a=n.split(`
17
+ `);for(let n=r;n<a.length;n++){let r=a[n];if(r.length>1024)continue;let o=R.test(r)?r.replace(R,`$1`):r;if(!o.match(/\S*Error: /)){for(let n of t){let t=n(o,e);if(t){i.push(t);break}}if(i.length>=50)break}}return Fe(i)}}var Re=class{match(e){return de(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message==`string`?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};const ze=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var Be=class{match(e){return typeof e==`string`}coerce(e,t){let[n,r]=this.getInfos(e);return{type:n??`Error`,value:r??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t=`Error`,n=e,r=e.match(ze);return r&&(t=r[1],n=r[2]),[t,n]}};const Ve=[`fatal`,`error`,`warning`,`log`,`info`,`debug`];function z(e,t=40){let n=Object.keys(e);if(n.sort(),!n.length)return`[object has no keys]`;for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`, `);if(!(r.length>t))return e===n.length||r.length<=t?r:`${r.slice(0,t)}...`}return``}var He=class{match(e){return typeof e==`object`&&!!e}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:`error`,synthetic:!0}}getType(e){return S(e)?e.constructor.name:`Error`}getValue(e){if(`name`in e&&typeof e.name==`string`){let t=`'${e.name}' captured as exception`;return`message`in e&&typeof e.message==`string`&&(t+=` with message: '${e.message}'`),t}if(`message`in e&&typeof e.message==`string`)return e.message;let t=this.getObjectClassName(e),n=z(e);return`${t&&t!==`Object`?`'${t}'`:`Object`} captured as exception with keys: ${n}`}isSeverityLevel(e){return x(e)&&!le(e)&&Ve.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(Te(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Ue=class{match(e){return S(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${z(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},We=class{match(e){return pe(e)}coerce(e,t){return{type:`Error`,value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},B=class{constructor(e){this._maxSize=e,this._cache=/* @__PURE__ */ new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};const V=new B(25),H=new B(20);async function Ge(e){let t={};for(let n=e.length-1;n>=0;n--){let r=e[n],i=r?.filename;!r||typeof i!=`string`||typeof r.lineno!=`number`||Ye(i)||Xe(r)||(t[i]||(t[i]=[]),t[i].push(r.lineno))}let n=Object.keys(t);if(n.length==0)return e;let r=[];for(let e of n){if(H.get(e))continue;let n=t[e];if(!n)continue;n.sort((e,t)=>e-t);let i=Qe(n);if(i.every(t=>Ze(e,t)))continue;let a=$e(V,e,{});r.push(Ke(e,i,a))}return await Promise.all(r).catch(()=>{}),e&&e.length>0&&qe(e,V),V.reduce(),e}function Ke(e,t,n){return new Promise(a=>{let o=r(e),s=i({input:o});function c(){o.destroy(),a()}let l=0,u=0,d=t[u];if(d===void 0)return void c();let f=d[0],p=d[1];function m(){H.set(e,1),s.close(),s.removeAllListeners(),c()}o.on(`error`,m),s.on(`error`,m),s.on(`close`,c),s.on(`line`,e=>{if(l++,!(l<f)&&(n[l]=et(e,0),l>=p)){if(u===t.length-1){s.close(),s.removeAllListeners();return}u++;let e=t[u];if(e===void 0){s.close(),s.removeAllListeners();return}f=e[0],p=e[1]}})})}function qe(e,t){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno==`number`){let e=t.get(n.filename);if(e===void 0)continue;Je(n.lineno,n,e)}}function Je(e,t,n){if(t.lineno===void 0||n===void 0)return;t.pre_context=[];for(let r=G(e);r<e;r++){let e=n[r];if(e===void 0)return void U(t);t.pre_context.push(e)}if(n[e]===void 0)return void U(t);t.context_line=n[e];let r=K(e);t.post_context=[];for(let i=e+1;i<=r;i++){let e=n[i];if(e===void 0)break;t.post_context.push(e)}}function U(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Ye(e){return e.startsWith(`node:`)||e.endsWith(`.min.js`)||e.endsWith(`.min.cjs`)||e.endsWith(`.min.mjs`)||e.startsWith(`data:`)}function Xe(e){return e.lineno!==void 0&&e.lineno>1e4||e.colno!==void 0&&e.colno>1e3}function Ze(e,t){let n=V.get(e);if(n===void 0)return!1;for(let e=t[0];e<=t[1];e++)if(n[e]===void 0)return!1;return!0}function Qe(e){if(!e.length)return[];let t=0,n=e[0];if(typeof n!=`number`)return[];let r=W(n),i=[];for(;;){if(t===e.length-1){i.push(r);break}let n=e[t+1];if(typeof n!=`number`)break;n<=r[1]?r[1]=n+7:(i.push(r),r=W(n)),t++}return i}function W(e){return[G(e),K(e)]}function G(e){return Math.max(1,e-7)}function K(e){return e+7}function $e(e,t,n){let r=e.get(t);return r===void 0?(e.set(t,n),n):r}function et(e,t){let n=e,r=n.length;if(r<=150)return n;t>r&&(t=r);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,r);return a>r-5&&(a=r),a===r&&(i=Math.max(a-140,0)),n=n.slice(i,a),i>0&&(n=`...${n}`),a<r&&(n+=`...`),n}function tt(e,t){let n=!1;return Object.assign(r=>{let i=global.process.listeners(`uncaughtException`).filter(e=>e.name!==`domainUncaughtExceptionClear`&&!0!==e._posthogErrorHandler).length===0;e(r,{mechanism:{type:`onuncaughtexception`,handled:!1}}),!n&&i&&(n=!0,t(r))},{_posthogErrorHandler:!0})}function nt(e,t){globalThis.process?.on(`uncaughtException`,tt(e,t))}function rt(e){globalThis.process?.on(`unhandledRejection`,t=>e(t,{mechanism:{type:`onunhandledrejection`,handled:!1}}))}var q=class e{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new ge({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(e,t,n,r){let i={...r};n||(i.$process_person_profile=!1);let a=this.errorPropertiesBuilder.buildFromUnknown(e,t);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:`$exception`,distinctId:n||_(),properties:{...a,...i}}}startAutocaptureIfEnabled(){this.isEnabled()&&(nt(this.onException.bind(this),this.onFatalError.bind(this)),rt(this.onException.bind(this)))}onException(t,n){this.client.addPendingPromise((async()=>{let r=await e.buildEventMessage(t,n),i=r.properties?.$exception_list[0]?.type??`Exception`;return this._rateLimiter.consumeRateLimit(i)?void this._logger.info(`Skipping exception capture because of client rate limiting.`,{exception:i}):this.client.capture(r)})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};async function it(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`SubtleCrypto API not available`);let n=await t.digest(`SHA-1`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const at=[`is_not`];var J=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name=`ClientError`,this.message=t,Object.setPrototypeOf(this,e.prototype)}},Y=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},X=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ot=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:r,host:i,customHeaders:a,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=r,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=a,this.onLoad=o.onLoad,this.cacheProvider=o.cacheProvider,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}async getFeatureFlag(e,t,n={},r={},i={}){await this.loadFeatureFlags();let a,o;if(!this.loadedSuccessfullyOnce)return a;if(o=this.featureFlagsByKey[e],o!==void 0)try{a=(await this.computeFlagAndPayloadLocally(o,t,n,r,i)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof X||t instanceof Y?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(/* @__PURE__ */ Error(`Error computing flag locally: ${e}: ${t}`))}return a}async getAllFlagsAndPayloads(e,t={},n={},r={},i){await this.loadFeatureFlags();let a={},o={},s=this.featureFlags.length==0,c=i?i.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,l={};return await Promise.all(c.map(async i=>{try{let{value:s,payload:c}=await this.computeFlagAndPayloadLocally(i,e,t,n,r,void 0,l);a[i.key]=s,c&&(o[i.key]=c)}catch(e){e instanceof X||e instanceof Y?this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${i.key}: ${e.message}`)):e instanceof Error&&this.onError?.(/* @__PURE__ */ Error(`Error computing flag locally: ${i.key}: ${e}`)),s=!0}})),{response:a,payloads:o,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,n={},r={},i={},a,o,s=!1){if(s||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let c;c=a===void 0?await this.computeFlagValueLocally(e,t,n,r,i,o):a;let l=this.getFeatureFlagPayload(e.key,c);return{value:c,payload:l}}async computeFlagValueLocally(e,t,n={},r={},i={},a={}){if(e.ensure_experience_continuity)throw new Y(`Flag has experience continuity enabled`);if(!e.active)return!1;let o=(e.filters||{}).aggregation_group_type_index;if(o==null)return await this.matchFeatureFlagProperties(e,t,r,a);{let t=this.groupTypeMapping[String(o)];if(!t)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${o} for feature flag ${e.key}`)),new Y(`Flag has unknown group type index`);if(!(t in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;let r=i[t];return await this.matchFeatureFlagProperties(e,n[t],r,a)}}getFeatureFlagPayload(e,t){let n=null;if(!1!==t&&t!=null&&(typeof t==`boolean`?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t==`string`&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n==`object`)return n;if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n,r){let i=e.key;if(!this.featureFlagsByKey)throw new Y(`Feature flags not available for dependency evaluation`);if(!(`dependency_chain`in e))throw new Y(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new Y(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(a.length===0)throw new Y(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let e of a){if(!(e in r)){let a=this.featureFlagsByKey[e];if(a){if(a.active)try{r[e]=await this.matchFeatureFlagProperties(a,t,n,r)}catch(t){throw new Y(`Error evaluating flag dependency '${e}' for flag '${i}': ${t}`)}else r[e]=!1}else throw new Y(`Missing flag dependency '${e}' for flag '${i}'`)}if(r[e]==null)throw new Y(`Dependency '${e}' could not be evaluated`)}let o=r[i];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return typeof e==`boolean`?e===t||typeof t==`string`&&t!==``&&!0===e:typeof e==`string`&&t===e}async matchFeatureFlagProperties(e,t,n,r={}){let i=e.filters||{},a=i.groups||[],o=!1,s;for(let c of a)try{if(await this.isConditionMatch(e,t,c,n,r)){let n=c.variant,r=i.multivariate?.variants||[];s=n&&r.some(e=>e.key===n)?n:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(e instanceof X)throw e;if(e instanceof Y)o=!0;else throw e}if(s!==void 0)return s;if(o)throw new Y(`Can't determine if feature flag is enabled or not with given properties`);return!1}async isConditionMatch(e,t,n,r,i={}){let a=n.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((n.properties||[]).length>0){for(let e of n.properties){let n=e.type,a=!1;if(a=n===`cohort`?lt(e,r,this.cohorts,this.debugMode):n===`flag`?await this.evaluateFlagDependency(e,t,r,i):st(e,r,o),!a)return!1}if(a==null)return!0}return!(a!=null&&await Z(e.key,t)>a/100)}async getMatchingVariant(e,t){let n=await Z(e.key,t,`variant`),r=this.variantLookupTable(e).find(e=>n>=e.valueMin&&n<e.valueMax);if(r)return r.key}variantLookupTable(e){let t=[],n=0,r=0;return((e.filters||{}).multivariate?.variants||[]).forEach(e=>{r=n+e.rollout_percentage/100,t.push({valueMin:n,valueMax:r,key:e.key}),n=r}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(e){return this.onError?.(/* @__PURE__ */ Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return this.loadingPromise||=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0}),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&=(clearTimeout(this.poller),void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(/* @__PURE__ */ Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache(`Loaded flags from cache (skipped fetch)`)||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Flags not modified (304), using cached data`)),this.flagsEtag=t.headers?.get(`ETag`)??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new J(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn(`[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts`),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new J(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new J(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!(`flags`in n))return void this.onError?.(/* @__PURE__ */ Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get(`ETag`)??void 0;let r={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(r),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(r)}catch(e){this.onError?.(/* @__PURE__ */ Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(e){e instanceof J&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e=`GET`,t){let n={...this.customHeaders,"Content-Type":`application/json`,Authorization:`Bearer ${this.personalApiKey}`};return t&&(n[`If-None-Match`]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions(`GET`,this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout==`number`){let e=new AbortController;n=E(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(/* @__PURE__ */ Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(e){this.onError?.(/* @__PURE__ */ Error(`Error during cache shutdown: ${e}`))}}};async function Z(e,t,n=``){let r=await it(`${e}.${t}${n}`);return parseInt(r.slice(0,15),16)/0x1000000000000000}function st(e,t,n){let r=e.key,i=e.value,a=e.operator||`exact`;if(r in t){if(a===`is_not_set`)throw new Y(`Operator is_not_set is not supported`)}else throw new Y(`Property ${r} not found in propertyValues`);let o=t[r];if(o==null&&!at.includes(a))return n&&n(`Property ${r} cannot have a value of null/undefined with the ${a} operator`),!1;function s(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function c(e,t,n){if(n===`gt`)return e>t;if(n===`gte`)return e>=t;if(n===`lt`)return e<t;if(n===`lte`)return e<=t;throw Error(`Invalid operator: ${n}`)}switch(a){case`exact`:return s(i,o);case`is_not`:return!s(i,o);case`is_set`:return r in t;case`icontains`:return String(o).toLowerCase().includes(String(i).toLowerCase());case`not_icontains`:return!String(o).toLowerCase().includes(String(i).toLowerCase());case`regex`:return dt(String(i))&&String(o).match(String(i))!==null;case`not_regex`:return dt(String(i))&&String(o).match(String(i))===null;case`gt`:case`gte`:case`lt`:case`lte`:{let e=typeof i==`number`?i:null;if(typeof i==`string`)try{e=parseFloat(i)}catch{}return e==null||o==null?c(String(o),String(i),a):typeof o==`string`?c(o,String(i),a):c(o,e,a)}case`is_date_after`:case`is_date_before`:{if(typeof i==`boolean`)throw new Y(`Date operations cannot be performed on boolean values`);let e=pt(String(i));if(e??=ft(i),e==null)throw new Y(`Invalid date: ${i}`);let t=ft(o);return[`is_date_before`].includes(a)?t<e:t>e}default:throw new Y(`Unknown operator: ${a}`)}}function ct(e,t){if(!(e in t))throw new X(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function lt(e,t,n,r=!1){let i=String(e.value);ct(i,n);let a=n[i];return ut(a,t,n,r)}function ut(e,t,n,r=!1){if(!e)return!0;let i=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if(`values`in a[0]){for(let e of a)try{let a=ut(e,t,n,r);if(i===`AND`){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof X)throw t;if(t instanceof Y)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Y(`Can't match cohort without a given cohort property value`);return i===`AND`}for(let e of a)try{let a;if(e.type===`cohort`)a=lt(e,t,n,r);else if(e.type===`flag`){r&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${e.key||`unknown`}'`);continue}else a=st(e,t);let o=e.negation||!1;if(i===`AND`){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof X)throw t;if(t instanceof Y)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Y(`can't match cohort without a given cohort property value`);return i===`AND`}function dt(e){try{return new RegExp(e),!0}catch{return!1}}function ft(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 Y(`${e} is in an invalid date format`)}throw new Y(`The date provided ${e} must be a string, number, or date object`)}function pt(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),n=new Date((/* @__PURE__ */ new Date()).toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let r=t.groups.interval;if(r==`h`)n.setUTCHours(n.getUTCHours()-e);else if(r==`d`)n.setUTCDate(n.getUTCDate()-e);else if(r==`w`)n.setUTCDate(n.getUTCDate()-7*e);else if(r==`m`)n.setUTCMonth(n.getUTCMonth()-e);else{if(r!=`y`)return null;n.setUTCFullYear(n.getUTCFullYear()-e)}return n}}var mt=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t===null?void 0:t}constructor(){this._memoryStorage={}}};const ht=3e4;var gt=class extends Oe{constructor(e,t={}){if(super(e,t),this._memoryStorage=new mt,this.options=t,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof t.featureFlagsPollingInterval==`number`?Math.max(t.featureFlagsPollingInterval,100):ht,t.personalApiKey){if(t.personalApiKey.includes(`phc_`))throw Error(`Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.`);!1!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new ot({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit(`error`,e)},onLoad:e=>{this._events.emit(`localEvaluationFlagsLoaded`,e)},customHeaders:this.getCustomHeaders(),cacheProvider:t.flagDefinitionCacheProvider}))}this.errorTracking=new q(this,t,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||5e4}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getLibraryVersion(){return`5.17.2`}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){typeof e==`string`&&this._logger.warn(`Called capture() with a string as the first argument when an object was expected.`),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStateless(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}async captureImmediate(e){return typeof e==`string`&&this._logger.warn(`Called captureImmediate() with a string as the first argument when an object was expected.`),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStatelessImmediate(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}identify({distinctId:e,properties:t,disableGeoip:n}){let r=t?.$set_once;delete t?.$set_once;let i=t?.$set||t;super.identifyStateless(e,{$set:i,$set_once:r},{disableGeoip:n})}async identifyImmediate({distinctId:e,properties:t,disableGeoip:n}){let r=t?.$set_once;delete t?.$set_once;let i=t?.$set||t;await super.identifyStatelessImmediate(e,{$set:i,$set_once:r},{disableGeoip:n})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=ht){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller!==void 0&&new Promise(t=>{let n=setTimeout(()=>{r(),t(!1)},e),r=this._events.on(`localEvaluationFlagsLoaded`,e=>{clearTimeout(n),r(),t(e>0)})})}async getFeatureFlag(e,t,n){let{groups:r,disableGeoip:i}=n||{},{onlyEvaluateLocally:a,sendFeatureFlagEvents:o,personProperties:s,groupProperties:c}=n||{},l=this.addLocalPersonAndGroupProperties(t,r,s,c);s=l.allPersonProperties,c=l.allGroupProperties,a??=!1,o??=this.options.sendFeatureFlagEvent??!0;let u=await this.featureFlagsPoller?.getFeatureFlag(e,t,r,s,c),d=u!==void 0,f,m,h;if(!d&&!a){let n=await super.getFeatureFlagDetailStateless(e,t,r,s,c,i);if(n===void 0)return;h=n.response,u=p(h),f=n?.requestId,m=n?.evaluatedAt}let g=`${e}_${u}`;return!o||t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].includes(g)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(g):this.distinctIdHasSentFlagCalls[t]=[g],this.capture({distinctId:t,event:`$feature_flag_called`,properties:{$feature_flag:e,$feature_flag_response:u,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:d,[`$feature/${e}`]:u,$feature_flag_request_id:f,$feature_flag_evaluated_at:m},groups:r,disableGeoip:i})),u}async getFeatureFlagPayload(e,t,n,r){let{groups:i,disableGeoip:a}=r||{},{onlyEvaluateLocally:o,personProperties:s,groupProperties:c}=r||{},l=this.addLocalPersonAndGroupProperties(t,i,s,c);s=l.allPersonProperties,c=l.allGroupProperties;let u;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let r=this.featureFlagsPoller?.featureFlagsByKey[e];if(r)try{let e=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(r,t,i,s,c,n);e&&(n=e.value,u=e.payload)}catch(e){if(e instanceof X||e instanceof Y)this._logger?.info(`${e.name} when computing flag locally: ${r.key}: ${e.message}`);else throw e}}return o??=!1,u===void 0&&!o&&(u=await super.getFeatureFlagPayloadStateless(e,t,i,s,c,a)),u}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw Error(`Personal API key is required for remote config payload decryption`);let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){let r=await this.getFeatureFlag(e,t,n);if(r!==void 0)return!!r||!1}async getAllFlags(e,t){return(await this.getAllFlagsAndPayloads(e,t)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{groups:n,disableGeoip:r,flagKeys:i}=t||{},{onlyEvaluateLocally:a,personProperties:o,groupProperties:s}=t||{},c=this.addLocalPersonAndGroupProperties(e,n,o,s);o=c.allPersonProperties,s=c.allGroupProperties,a??=!1;let l=await this.featureFlagsPoller?.getAllFlagsAndPayloads(e,n,o,s,i),u={},d={},f=!0;if(l&&(u=l.response,d=l.payloads,f=l.fallbackToFlags),f&&!a){let t=await super.getFeatureFlagsAndPayloadsStateless(e,n,o,s,r,i);u={...u,...t.flags||{}},d={...d,...t.payloads||{}}}return{featureFlags:u,featureFlagPayloads:d}}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:r,disableGeoip:i}){super.groupIdentifyStateless(e,t,n,{disableGeoip:i},r)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}async _shutdown(e){return this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),super._shutdown(e)}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,Authorization:`Bearer ${this.options.personalApiKey}`}},r=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout==`number`){let e=new AbortController;r=E(()=>{e.abort()},this.options.requestTimeout),n.signal=e.signal}try{return await this.fetch(t,n)}catch(e){this._events.emit(`error`,e);return}finally{r&&clearTimeout(r)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},r={};for(let[i,a]of Object.entries(e))if(he(a)&&t&&i in t){let e={};for(let[t,n]of Object.entries(a))e[String(t)]=String(n);r[String(i)]=e}else n[String(i)]=String(a);return{personProperties:n,groupProperties:r}}async getFeatureFlagsForEvent(e,t,n,r){let i=r?.personProperties||{},a=r?.groupProperties||{},o=r?.flagKeys;if(r?.onlyEvaluateLocally??!1){if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}return{}}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,a,n)).flags}addLocalPersonAndGroupProperties(e,t,n,r){let i={distinct_id:e,...n||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...r?.[e]||{}};return{allPersonProperties:i,allGroupProperties:a}}captureException(e,t,n){let r=/* @__PURE__ */ Error(`PostHog syntheticException`);this.addPendingPromise(q.buildEventMessage(e,{syntheticException:r},t,n).then(e=>this.capture(e)))}async captureExceptionImmediate(e,t,n){let r=/* @__PURE__ */ Error(`PostHog syntheticException`);this.addPendingPromise(q.buildEventMessage(e,{syntheticException:r},t,n).then(e=>this.captureImmediate(e)))}async prepareEventMessage(e){let{distinctId:t,event:n,properties:r,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c}=e,l=this.context?.get(),u=t||l?.distinctId,d={...l?.properties||{},...r||{}};u||(u=_(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:u,event:n,properties:d,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c});if(!f)return Promise.reject(null);let p=await Promise.resolve().then(async()=>{if(a){let e=typeof a==`object`?a:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,i,s,e)}return f.event,{}}).then(e=>{let t={};if(e)for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let n=Object.keys(e||{}).filter(t=>e?.[t]!==!1).sort();return n.length>0&&(t.$active_feature_flags=n),t}).catch(()=>({})).then(e=>({...e,...f.properties||{},$groups:f.groups||i}));return f.event===`$pageview`&&this.options.__preview_capture_bot_pageviews&&typeof p.$raw_user_agent==`string`&&ae(p.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event=`$bot_pageview`,p.$browser_type=`bot`),{distinctId:f.distinctId,event:f.event,properties:p,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],r=e;for(let t of n){if(r=t(r),!r)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!r.properties||Object.keys(r.properties).length===0){let e=`Event '${r.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return r}},_t=class{constructor(){this.storage=new a}get(){return this.storage.getStore()}run(e,t,n){if(n?.fresh===!0)return this.storage.run(e,t);{let n=this.get()||{},r={distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}};return this.storage.run(r,t)}}};const vt=`posthog-node`;function yt(e,{organization:t,projectId:n,prefix:r,severityAllowList:i=[`error`],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(i===`*`||i.includes(o.level)))return o;o.tags||={};let s=o.tags[bt.POSTHOG_ID_TAG];if(s===void 0)return o;let c=e.options.host??`https://us.i.posthog.com`,l=new URL(`/project/${e.apiKey}/person/${s}`,c).toString();o.tags[`PostHog Person URL`]=l;let u=o.exception?.values||[],d=u.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:`raw`,frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:`node:javascript`}))}:void 0})),f={$exception_message:u[0]?.value||o.message,$exception_type:u[0]?.type,$exception_level:o.level,$exception_list:d,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:u[0]?.value||o.message,$sentry_exception_type:u[0]?.type,$sentry_tags:o.tags};return t&&n&&(f.$sentry_url=(r||`https://sentry.io/organizations/`)+t+`/issues/?project=`+n+`&query=`+o.event_id),a&&e.capture({event:`$exception`,distinctId:s,properties:f}),o}}var bt=class{static#e=this.POSTHOG_ID_TAG=`posthog_distinct_id`;constructor(e,t,n,r,i){this.name=vt,this.name=vt,this.setupOnce=function(a,o){let s=o()?.getClient()?.getDsn()?.projectId;a(yt(e,{organization:t,projectId:s,prefix:n,severityAllowList:r,sendExceptionsToPostHog:i??!0}))}}};q.errorPropertiesBuilder=new Ae([new Ue,new Re,new He,new Be,new We],Le(`node:javascript`,Ne),[o(),Ge]);var xt=class extends gt{getLibraryId(){return`posthog-node`}initializeContext(){return new _t}},St=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})};const Ct=1e4;let Q=null,$=Promise.resolve();function wt(){return Q||=new xt(`phc_eNuN6Ojnk9O7uWfC17z12AK85fNR0BY6IiGVy0Gfwzw`,{host:`https://ph.mintlify.com`}),Q}function Tt(e){$=Promise.allSettled([$,e]).then(()=>void 0)}function Et(){return St(this,void 0,void 0,function*(){try{yield Promise.race([$,new Promise(e=>{setTimeout(e,Ct).unref()})])}catch{}if(Q){try{yield Promise.race([Q.shutdown(),new Promise(e=>{setTimeout(e,Ct).unref()})])}catch{}Q=null}})}export{wt as n,Et as r,Tt as t};