@toloka-platform/sdk 0.2.0-preview.1 → 0.2.0-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/dist/cli/toloka.js +3 -3
  2. package/dist/cli/toloka.js.jsc +0 -0
  3. package/dist/cli/toloka.js.jsc.sha256 +1 -1
  4. package/dist/cli/toloka.js.sha256 +1 -1
  5. package/docs/limitations.md +1 -1
  6. package/openapi/gen/models/generationNodeSettingsAudienceAndPricingOneOfOneoneGenerationModelId.ts +1 -1
  7. package/openapi/gen/models/generationNodeSettingsQualityAssuranceOneOfFourLlmQaModelId.ts +1 -1
  8. package/openapi/gen/models/generationNodeSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  9. package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfOnefoursevenSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  10. package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneoneGenerationModelId.ts +1 -1
  11. package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfThreeoneSettingsQualityAssuranceOneOfFourLlmQaModelId.ts +1 -1
  12. package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfThreeoneSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  13. package/openapi/gen/models/quorumNodeSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  14. package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfOnefoursevenSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  15. package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneoneGenerationModelId.ts +1 -1
  16. package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfThreeoneSettingsQualityAssuranceOneOfFourLlmQaModelId.ts +1 -1
  17. package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfThreeoneSettingsQualityAssuranceOneOfLlmQaModelId.ts +1 -1
  18. package/package.json +1 -1
  19. package/skills/catalog.json +4 -4
  20. package/skills/toloka-build/references/node-semantics.md +2 -1
  21. package/skills/toloka-report-issue/references/report-template.md +1 -1
  22. package/src/pipeline-graph-v1.contract.json +16 -6
@@ -111,7 +111,7 @@ ${e.code}
111
111
  `),g=s.category===Fe.default.DiagnosticCategory.Error?"error":"warning";p(s.file&&s.start!=null,"Diagnostic location is missing");let{line:l,character:I}=s.file.getLineAndCharacterOfPosition(r),{line:d,character:C}=s.file.getLineAndCharacterOfPosition(s.start),A=d-l,c=d===l?C-I:C,u=s.file.text.split(/\r?\n/gu)[d]??"",Z=" ".repeat(C)+"^".repeat(s.length&&s.length>0?s.length:1);return{severity:g,text:[`${A}:${c+1} - [${Fe.default.DiagnosticCategory[s.category]}] TS${s.code}`,a,"",u,Z].join(`
112
112
  `)}})};return{data:i(at.data),constants:i(at.constants),preprocess:i(at.preprocess),postprocess:i(at.postprocess),code:i(at.code)}},ol=(e,t)=>{let i=[0];for(let g=0;g<e.length;g+=1)if(e[g]===`
113
113
  `)i.push(g+1);let n=(g)=>{let l=0;while(l+1<i.length&&i[l+1]<=g)l+=1;return{line:l,character:g-i[l]}},r=e.split(/\r?\n/gu),o=e5.map(([g,l])=>({key:g,start:e.indexOf(`/* ${l}_START */`)+`/* ${l}_START */`.length+1,end:e.indexOf(`/* ${l}_END */`)-1})),s=(g)=>{let l=o.find((C)=>g>=C.start&&g<=C.end);if(l)return l;let d=o.filter((C)=>C.start<=g).at(-1)??o[0];return p(d,"Task UI diagnostic block is missing"),d},a=t5();for(let g of t){let l=g.labels[0],I=l?.start??e.length,d=s(I),C=g.severity==="Error"?"error":"warning",{line:A,character:c}=n(d.start),{line:u,character:Z}=n(I),W=u-A,m=u===A?Z-c:Z,b=r[u]??"",h=l?l.end-l.start:0,f=" ".repeat(Z)+"^".repeat(h>0?h:1);a[d.key].push({severity:C,text:[`${W}:${m+1} - [${g.severity}]`,g.message,"",b,f].join(`
114
- `)})}return a},km=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=Gm(i),r=yt.createDefaultMapFromNodeModules({target:Fe.default.ScriptTarget.Latest},Fe.default,qv);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(Ui,n);let o=yt.createSystem(r),{languageService:s}=yt.createVirtualTypeScriptEnvironment(o,[Ui],Fe.default,{target:Fe.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:Fe.default.ModuleKind.CommonJS,moduleResolution:Fe.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:Fe.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],g=[];try{a=s.getSyntacticDiagnostics(Ui),g=[...s.getSemanticDiagnostics(Ui),...s.getSuggestionDiagnostics(Ui),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let l=Hm(n,a),I=Hm(n,[...a,...g]),d=wm(i),C=ol(d,wo.parseSync("runtime.jsx",d).errors);return Fm(I,l,C)},performSyntaxCheck:(i)=>{let n=Gm(i),r=ol(n,wo.parseSync(Ui,n).errors),o=wm(i),s=ol(o,wo.parseSync("runtime.jsx",o).errors);return Fm(r,r,s)}}),sl=()=>km({reactDeclaration:Mn.react.source,elementsDeclaration:Mn.elements.source});var gl=require("crypto"),Ti=require("fs/promises"),Nm=require("path");var Ym="TOLOKA_CHECK_EVIDENCE_DIR",ll="TOLOKA_CHECK_PIPELINE_FINGERPRINT",Il="TOLOKA_CHECK_NODE_ID",dl="TOLOKA_CHECK_TYPED_ONLY",n5=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),r5=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),al=(e)=>{if(Array.isArray(e))return e.map(al);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,al(i)]))},cl=(e)=>gl.createHash("sha256").update(JSON.stringify(al(e))).digest("hex"),o5=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,Pm=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Xm=(e,t)=>t===void 0?Pm(`[toloka:${e}:`):Pm(o5(e,t));var s5=(e)=>e==="code"||e==="ui"||e==="pipeline",a5=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",g5=(e,t)=>{p(n5(e),`Invalid test evidence ${t}`);let i=e;p(i.version===1,`Unsupported test evidence version in ${t}`),p(typeof i.pipelineFingerprint==="string",`Missing pipeline fingerprint in ${t}`),p(s5(i.kind),`Invalid test evidence kind in ${t}`),p(a5(i.status),`Invalid test evidence status in ${t}`),p(typeof i.testName==="string",`Missing test name in ${t}`),p(i.nodeId===void 0||typeof i.nodeId==="string",`Invalid node id in ${t}`),p(i.diagnostic===void 0||typeof i.diagnostic==="string",`Invalid diagnostic in ${t}`),p(i.partial===void 0||typeof i.partial==="boolean",`Invalid partial coverage in ${t}`),p(i.untestedHardwareFields===void 0||r5(i.untestedHardwareFields),`Invalid hardware fields in ${t}`);let n=i.untestedHardwareFields;return{version:1,pipelineFingerprint:i.pipelineFingerprint,kind:i.kind,status:i.status,testName:i.testName,...i.nodeId===void 0?{}:{nodeId:i.nodeId},...i.diagnostic===void 0?{}:{diagnostic:i.diagnostic},...i.partial===void 0?{}:{partial:i.partial},...n===void 0?{}:{untestedHardwareFields:n}}};var Sm=async(e)=>{let i=(await Ti.readdir(e,{withFileTypes:!0})).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name).toSorted();return Promise.all(i.map(async(n)=>{let r=Nm.join(e,n),o;try{o=JSON.parse(await Ti.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return g5(o,r)}))};var qn=require("fs"),ni=require("path"),xm=ni.join("bin","toloka.js"),Em=(e)=>{try{return qn.realpathSync(e)}catch{return e}},$n=(e)=>{let t=ni.join(e,xm);if(qn.existsSync(t))return t;let i=ni.dirname(e);return i===e?void 0:$n(i)},Jm=(e=process.argv[1])=>(e===void 0?void 0:$n(ni.dirname(Em(e))))??$n(process.cwd()),Um=(e=process.argv[1])=>{let t=e===void 0?void 0:Em(e);if(t!==void 0&&qn.existsSync(t)&&$n(ni.dirname(t))!==void 0)return t;let i=$n(process.cwd());return p(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${xm} in a directory above its runtime entry, but none exists above ${e??"the unset process.argv[1]"} or above ${process.cwd()}. Reinstall @toloka-platform/sdk.`),i};var nr=require("fs/promises"),me=require("path"),pp=require("url");var gp=We(el(),1),lp=We(op(),1);var sp={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var Ip=new gp.default({strict:!1});lp.default(Ip);var ap=Ip.compile(sp),U5=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function fl(e){if(ap(e))return;let t=ap.errors;p(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=U5(r),s=`${o.path}
114
+ `)})}return a},km=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=Gm(i),r=yt.createDefaultMapFromNodeModules({target:Fe.default.ScriptTarget.Latest},Fe.default,qv);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(Ui,n);let o=yt.createSystem(r),{languageService:s}=yt.createVirtualTypeScriptEnvironment(o,[Ui],Fe.default,{target:Fe.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:Fe.default.ModuleKind.CommonJS,moduleResolution:Fe.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:Fe.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],g=[];try{a=s.getSyntacticDiagnostics(Ui),g=[...s.getSemanticDiagnostics(Ui),...s.getSuggestionDiagnostics(Ui),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let l=Hm(n,a),I=Hm(n,[...a,...g]),d=wm(i),C=ol(d,wo.parseSync("runtime.jsx",d).errors);return Fm(I,l,C)},performSyntaxCheck:(i)=>{let n=Gm(i),r=ol(n,wo.parseSync(Ui,n).errors),o=wm(i),s=ol(o,wo.parseSync("runtime.jsx",o).errors);return Fm(r,r,s)}}),sl=()=>km({reactDeclaration:Mn.react.source,elementsDeclaration:Mn.elements.source});var gl=require("crypto"),Ti=require("fs/promises"),Nm=require("path");var Ym="TOLOKA_CHECK_EVIDENCE_DIR",ll="TOLOKA_CHECK_PIPELINE_FINGERPRINT",Il="TOLOKA_CHECK_NODE_ID",dl="TOLOKA_CHECK_TYPED_ONLY",n5=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),r5=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),al=(e)=>{if(Array.isArray(e))return e.map(al);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,al(i)]))},cl=(e)=>gl.createHash("sha256").update(JSON.stringify(al(e))).digest("hex"),o5=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,Pm=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Xm=(e,t)=>t===void 0?Pm(`[toloka:${e}:`):Pm(o5(e,t));var s5=(e)=>e==="code"||e==="ui"||e==="pipeline",a5=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",g5=(e,t)=>{p(n5(e),`Invalid test evidence ${t}`);let i=e;p(i.version===1,`Unsupported test evidence version in ${t}`),p(typeof i.pipelineFingerprint==="string",`Missing pipeline fingerprint in ${t}`),p(s5(i.kind),`Invalid test evidence kind in ${t}`),p(a5(i.status),`Invalid test evidence status in ${t}`),p(typeof i.testName==="string",`Missing test name in ${t}`),p(i.nodeId===void 0||typeof i.nodeId==="string",`Invalid node id in ${t}`),p(i.diagnostic===void 0||typeof i.diagnostic==="string",`Invalid diagnostic in ${t}`),p(i.partial===void 0||typeof i.partial==="boolean",`Invalid partial coverage in ${t}`),p(i.untestedHardwareFields===void 0||r5(i.untestedHardwareFields),`Invalid hardware fields in ${t}`);let n=i.untestedHardwareFields;return{version:1,pipelineFingerprint:i.pipelineFingerprint,kind:i.kind,status:i.status,testName:i.testName,...i.nodeId===void 0?{}:{nodeId:i.nodeId},...i.diagnostic===void 0?{}:{diagnostic:i.diagnostic},...i.partial===void 0?{}:{partial:i.partial},...n===void 0?{}:{untestedHardwareFields:n}}};var Sm=async(e)=>{let i=(await Ti.readdir(e,{withFileTypes:!0})).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name).toSorted();return Promise.all(i.map(async(n)=>{let r=Nm.join(e,n),o;try{o=JSON.parse(await Ti.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return g5(o,r)}))};var qn=require("fs"),ni=require("path"),xm=ni.join("bin","toloka.js"),Em=(e)=>{try{return qn.realpathSync(e)}catch{return e}},$n=(e)=>{let t=ni.join(e,xm);if(qn.existsSync(t))return t;let i=ni.dirname(e);return i===e?void 0:$n(i)},Jm=(e=process.argv[1])=>(e===void 0?void 0:$n(ni.dirname(Em(e))))??$n(process.cwd()),Um=(e=process.argv[1])=>{let t=e===void 0?void 0:Em(e);if(t!==void 0&&qn.existsSync(t)&&$n(ni.dirname(t))!==void 0)return t;let i=$n(process.cwd());return p(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${xm} in a directory above its runtime entry, but none exists above ${e??"the unset process.argv[1]"} or above ${process.cwd()}. Reinstall @toloka-platform/sdk.`),i};var nr=require("fs/promises"),me=require("path"),pp=require("url");var gp=We(el(),1),lp=We(op(),1);var sp={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","gemini-3.7-flash","claude-sonnet-5","claude-opus-5","claude-fable-5","gpt-5.6-terra","gpt-5.6-luna","gpt-5.6-sol"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var Ip=new gp.default({strict:!1});lp.default(Ip);var ap=Ip.compile(sp),U5=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function fl(e){if(ap(e))return;let t=ap.errors;p(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=U5(r),s=`${o.path}
115
115
  ${o.reason}`;if(i.has(s))continue;i.add(s),n.push(o)}throw Vi.fromIssues(n)}var T5=Symbol("fieldDefinition"),O5=Symbol.for("@toloka-platform/sdk/pipeline-definition"),cp=Symbol("portDefinition"),z5=Symbol("nodeFieldReferences");function Cp(e,t){return{node:e,handle:t,direction:"input",[cp]:"input"}}function up(e,t){return{node:e,handle:t,direction:"output",[cp]:"output"}}function mp(e){return typeof e==="object"&&e!==null&&T5 in e}function yl(e,t){if(mp(e)){t.push(e);return}if(Array.isArray(e)){for(let i of e)yl(i,t);return}if(typeof e==="object"&&e!==null)for(let i of Object.values(e))yl(i,t)}function j5(e){let t=[];return yl(e,t),t}function dp(e){return mp(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function D5(e,t={}){p(typeof e==="object"&&e!==null&&!Array.isArray(e),"root() defines the single pipeline boundary; call root({ started, completed }) without a name");let i=t.id??"root",{started:n,completed:r,...o}=e;return{id:i,type:"root",settings:{...o,startedFieldProxies:{output:n.map(dp)},completedFieldProxies:{input:r.map(dp)}},started:up(i,"started"),completed:Cp(i,"completed"),[z5]:j5(e)}}var oE=Object.assign(D5,{started:up("root","started"),completed:Cp("root","completed")});function Q5(e){return typeof e==="object"&&e!==null&&O5 in e}function vo(e){p(Q5(e),"Invalid pipeline definition: expected a value returned by definePipeline"),p(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;p(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),p(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}fl(e.graph)}function ir(e,t){let i={version:e.graph.version,fields:e.graph.fields.map((n)=>({...n})),nodes:e.graph.nodes.map((n)=>n.type==="root"?{...n,settings:{...n.settings,datasetId:t.datasetId}}:n),connections:e.graph.connections.map((n)=>({from:{...n.from},to:{...n.to},settings:{...n.settings}}))};return fl(i),i}var Ap=async(e)=>{let t;try{t=await nr.readdir(e,{withFileTypes:!0})}catch(n){if(n instanceof Error&&Reflect.get(n,"code")==="ENOENT")return[];throw n}let i=[];for(let n of t.toSorted((r,o)=>r.name.localeCompare(o.name))){let r=me.join(e,n.name);if(n.isDirectory())i.push(...await Ap(r));else if(n.isFile()&&n.name==="pipeline.ts")i.push(r)}return i},_5="toloka.json",K5=async(e)=>{try{return(await nr.stat(me.join(e,_5))).isFile()}catch{return!1}};async function Zp(e){let t=me.resolve(e);for(;;){if(await K5(t))return t;let i=me.dirname(t);if(i===t)return;t=i}}async function Di(e){let t=await Ap(me.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(n)=>{let r=await nr.stat(n),o=pp.pathToFileURL(n);o.searchParams.set("version",`${r.mtimeMs}-${r.size}`);let s=await import(o.href);p(typeof s==="object"&&s!==null,`Invalid ${n}: expected a module`);let a=Reflect.get(s,"default");vo(a);let g=me.relative(e,me.dirname(n)).split(me.sep).join("/");return{sourceDirectory:g,name:me.basename(g),definition:a}}))).toSorted((n,r)=>n.sourceDirectory.localeCompare(r.sourceDirectory))}}class Qi extends Error{phase;constructor(e,t,i){super(t,i);this.name="FreshCheckProcessError",this.phase=e}}var bp=5000,L5=65536,ri="TOLOKA_INTERNAL_CHECK_RESULT_FILE",M5=(e)=>e.message.length<=bp?e:{...e,message:`${e.message.slice(0,bp)}
116
116
  \u2026output truncated`},Vl=20,hp=async(e)=>{let t=[],i=0,n=!1;for await(let o of e){let s=Buffer.isBuffer(o)?o:Buffer.from(o),a=L5-i;if(a>0){let g=s.subarray(0,a);t.push(g),i+=g.length}if(s.length>a)n=!0}let r=Buffer.concat(t).toString("utf8");return n?`${r}
117
117
  \u2026output truncated`:r},Gl=async(e,t,i,n=process.env,r,o=process.execPath)=>{r?.throwIfAborted();let s=Rp.spawn(o,[t,...i],{cwd:e,env:n,stdio:["ignore","pipe","pipe"]}),a=()=>s.kill("SIGTERM");if(r?.addEventListener("abort",a,{once:!0}),r?.aborted===!0)a();try{let[g,l,I]=await Promise.all([wp.once(s,"close"),hp(s.stdout),hp(s.stderr)]),d=g[0];return typeof d==="number"?{exitCode:d,stdout:l,stderr:I}:{exitCode:2,stdout:l,stderr:[I,`Process terminated by ${String(g[1])}`].filter(Boolean).join(`
@@ -138,7 +138,7 @@ This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var M
138
138
  `)};let{value:I,source:d}=a;if(l.push(`Platform: ${I} (${d})`,`API key: ${e.showToken===!0?s.value:xp(s.value)} (${s.source})`,g),t.POTATO_API_KEY!==void 0&&n!==void 0)l.push("",`POTATO_API_KEY is set, so the key stored in ${n.path} is ignored.`);if(n?.legacy===!0)l.push("",`Credentials still live at the old path ${n.path}. Run toloka login to move them to ${Ee(t)}.`);let C=e.probe?.({baseUrl:I,apiKey:s.value})??bt({baseUrl:I,apiKey:s.value});try{let A=await C.projects.listPage({limit:1});return l.push("",`Reachable: ${A.pagination.total} project(s) visible.`),{authenticated:!0,output:l.join(`
139
139
  `)}}catch(A){let c=A instanceof Error?A.message:String(A);return l.push("",`Not reachable: ${c}`,"","Run toloka login to store a working key."),{authenticated:!1,output:l.join(`
140
140
  `)}}}var $Z=require("crypto"),mi=require("fs/promises"),us=require("path");var Ki=require("path");function eA(){let e=jk();return async(t)=>{for(let i of t)i.module=e(i.filename);return t}}function jk(e=process.argv[1]?Ki.dirname(process.argv[1]):process.cwd(),t=Ki.sep==="\\"){let i=t?qp(e):e;return(n)=>{if(!n)return;let r=t?qp(n):n,{dir:o,base:s,ext:a}=Ki.posix.parse(r);if(a===".js"||a===".mjs"||a===".cjs")s=s.slice(0,-1*a.length);let g=decodeURIComponent(s);if(!o)o=".";let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${g}`;if(o.startsWith(i)){let I=o.slice(i.length+1).replace(/\//g,".");return I?`${I}:${g}`:g}return g}}function qp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Nl=(e)=>{if("flags"in e){let t=tA(e.flags),i=iA(e.flags);return{...e,featureFlags:t,featureFlagPayloads:i}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([r,o])=>[r,Jo(o)])),n=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,Dk(r,o,i[r])]));return{...e,featureFlags:t,featureFlagPayloads:i,flags:n}}};function Dk(e,t,i){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:i?JSON.stringify(i):void 0,description:void 0}}}var tA=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,i])=>[t,gr(i)]).filter(([,t])=>t!==void 0)),iA=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((i)=>{let n=t[i];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map((i)=>{let n=t[i].metadata?.payload;return[i,n?Jo(n):void 0]}))},gr=(e)=>e===void 0?void 0:e.variant??e.enabled,Jo=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Qk=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],lr=(e,t=[])=>{let i={},n=(r)=>{if(e[r]!==void 0)i[r]=e[r]};return Qk.forEach(n),t.forEach(n),i};var He=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.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function Yl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Kk="NativeGzipValidationError",Lk=31,Mk=139,$k=8,qk=(e)=>e.length>=2&&e[0]===Lk&&e[1]===Mk;var Ir,eP=()=>{if(Ir)return Ir;Ir=[];for(let e=0;e<256;e++){let t=e;for(let i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;Ir[e]=t>>>0}return Ir},tP=(e)=>{let t=eP(),i=4294967295;for(let n=0;n<e.length;n++)i=t[(i^e[n])&255]^i>>>8;return(4294967295^i)>>>0},Uo=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=Kk,t},iP=async(e,t)=>{if(e.size<18)Uo("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!qk(i)||i[2]!==$k)Uo("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());if(n.getUint32(0,!0)!==tP(t))Uo("invalid-crc");let r=t.length>>>0;if(n.getUint32(4,!0)!==r)Uo("invalid-size")};async function gi(e,t=!0,i){try{let n=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),o=r.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async(l)=>{try{await o.abort(l)}catch{}throw l}),a=new Response(r.readable).blob(),[g]=await Promise.all([a,s]);return await iP(g,n),g}catch(n){if(i?.rethrow)throw n;if(t)console.error("Failed to gzip compress data",n);return null}}var nP=["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"],nA=function(e,t=[]){if(!e)return!1;let i=e.toLowerCase();return nP.concat(t).some((n)=>{let r=n.toLowerCase();return i.indexOf(r)!==-1})};function Li(e){let t=[];return JSON.stringify(e,function(i,n){if(typeof n=="bigint")return n.toString();if(typeof n=="function"||typeof n=="symbol")return;if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n})??"null"}var oP=Array.isArray,rA=Object.prototype,OE=rA.hasOwnProperty,To=rA.toString,It=oP||function(e){return To.call(e)==="[object Array]"};var dr=(e)=>e===Object(e)&&!It(e);var li=(e)=>e===void 0,Rt=(e)=>To.call(e)=="[object String]",oA=(e)=>Rt(e)&&e.trim().length===0,sA=(e)=>e===null;var cr=(e)=>To.call(e)=="[object Number]"&&e===e;var aA=(e)=>To.call(e)==="[object Boolean]";var gA=(e)=>e instanceof Error;function Oo(e){return e===null||typeof e!="object"}function Ii(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function lA(e){return Ii(e,"ErrorEvent")}function Mi(e){return typeof Event<"u"&&sP(e,Event)}function IA(e){return Ii(e,"Object")}function sP(e,t){try{return e instanceof t}catch{return!1}}function Cr(e,t,i,n,r){if(t>i)n.warn("min cannot be greater than max."),t=i;if(cr(e))if(e>i)return n.warn(" cannot be greater than max: "+i+". Using max value instead."),i;else{if(!(e<t))return e;return n.warn(" cannot be less than min: "+t+". Using min value instead."),t}return n.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),Cr(r||i,t,i,n)}var aP=86400000,gP=1,lP=10;function dA(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??gP,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??lP}}class Xl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Cr(e.bucketSize,0,100,e._logger),this._refillRate=Cr(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Cr(e.refillInterval,0,aP,e._logger)}_applyRefill(e,t){let i=t-e.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let r=n*this._refillRate;e.tokens=Math.min(e.tokens+r,this._bucketSize),e.lastAccess=e.lastAccess+n*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),i=String(e),n=this._buckets[i];if(n)this._applyRefill(n,t);else n={tokens:this._bucketSize,lastAccess:t},this._buckets[i]=n;if(n.tokens===0)return!0;if(n.tokens--,n.tokens===0)this._onBucketRateLimited?.(e);return n.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class di{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new di(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(n)||e<0||t<0||i<0||n<0||e>281474976710655||t>4095||i>1073741823||n>4294967295)throw RangeError("invalid field value");let r=new Uint8Array(16);return r[0]=e/1099511627776,r[1]=e/4294967296,r[2]=e/16777216,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new di(r)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let r=parseInt(t.substring(2*n,2*n+8),16);i[n+0]=r>>>24,i[n+1]=r>>>16,i[n+2]=r>>>8,i[n+3]=r}return new di(i)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".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+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".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((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new di(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let i=this.bytes[t]-e.bytes[t];if(i!==0)return Math.sign(i)}return 0}}class CA{constructor(e){this.timestamp=0,this.counter=0,this.random=e??IP()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let i=this.generateOrAbortCore(e,t);if(i===void 0)this.timestamp=0,i=this.generateOrAbortCore(e,t);return i}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return di.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,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,di.ofInner(e)}}var IP=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),cA,ve=()=>dP().toString(),dP=()=>(cA||(cA=new CA)).generate();class Sl{add(e){let t=ve(),i=++this.nextId;return this.promiseByIds[t]={id:i,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length}getPromises(e=[],t=this.nextId){let i=new Set(e);return Object.values(this.promiseByIds).filter((n)=>n.id<=t&&!i.has(n.promise)).map((n)=>n.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function cP(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var uA=(e,t,i)=>{function n(o,...s){t(()=>{let a=i[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{i.error(e,...o)},createLogger:(o)=>uA(`${e} ${o}`,t,i)}},CP=(e)=>e();function mA(e,t=CP){return uA(e,t,cP())}var qi="Mobile",jo="iOS",$i="Android",hA="Tablet",tJ=$i+" "+hA;var mP="Apple",iJ=mP+" Watch",WA="Safari",Do="BlackBerry",fA="Samsung",pP=fA+"Browser",AP=fA+" Internet",Qo="Chrome",ZP=Qo+" OS",bP=Qo+" "+jo,yA="Internet Explorer",hP=yA+" "+qi,El="Opera",nJ=El+" Mini",VA="Edge",WP="Microsoft "+VA,Jl="Firefox",fP=Jl+" "+jo,Ul="Nintendo",Tl="PlayStation",zo="Xbox",yP=$i+" "+qi,VP=qi+" "+WA,ur="Windows",BP=ur+" Phone";var BA="Generic",rJ=BA+" "+qi.toLowerCase(),oJ=BA+" "+hA.toLowerCase(),RP="Konqueror",GP="Oculus Browser",pA="Vivaldi",wP="Yandex",AA="Whale",FP="DuckDuckGo",HP="Pale Moon",ZA="Waterfox",bA="Brave",vP="Google Search App",L="(\\d+(\\.\\d+)?)",xl=new RegExp("Version/"+L);var sJ=new RegExp(zo,"i"),aJ=new RegExp(Tl+" \\w+","i"),gJ=new RegExp(Ul+" \\w+","i"),kP=new RegExp(Do+"|PlayBook|BB10","i"),PP={"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 lJ={[hP]:[new RegExp("rv:"+L)],[WP]:[new RegExp(VA+"?\\/"+L)],[Qo]:[new RegExp("("+Qo+"|CrMo)\\/"+L)],[bP]:[new RegExp("CriOS\\/"+L)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+L)],[WA]:[xl],[VP]:[xl],[El]:[new RegExp("("+El+"|OPR)\\/"+L)],[Jl]:[new RegExp(Jl+"\\/"+L)],[fP]:[new RegExp("FxiOS\\/"+L)],[RP]:[new RegExp("Konqueror[:/]?"+L,"i")],[Do]:[new RegExp(Do+" "+L),xl],[yP]:[new RegExp("android\\s"+L,"i")],[AP]:[new RegExp(pP+"\\/"+L)],[GP]:[new RegExp("OculusBrowser\\/"+L)],[pA]:[new RegExp(pA+"\\/"+L)],[wP]:[new RegExp("YaBrowser\\/"+L)],[AA]:[new RegExp(AA+"\\/"+L)],[bA]:[new RegExp(bA+"\\/"+L)],[FP]:[new RegExp("(DuckDuckGo|Ddg)\\/"+L)],[HP]:[new RegExp("PaleMoon\\/"+L)],[ZA]:[new RegExp(ZA+"\\/"+L)],[vP]:[new RegExp("GSA\\/"+L)],[yA]:[new RegExp("(rv:|MSIE )"+L)],Mozilla:[new RegExp("rv:"+L)]};var IJ=[[new RegExp(zo+"; "+zo+" (.*?)[);]","i"),(e)=>[zo,e&&e[1]||""]],[new RegExp(Ul,"i"),[Ul,""]],[new RegExp(Tl,"i"),[Tl,""]],[kP,[Do,""]],[new RegExp(ur,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[BP,""];if(new RegExp(qi).test(t)&&!/IEMobile\b/.test(t))return[ur+" "+qi,""];let i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){let n=i[1],r=PP[n]||"";if(/arm/i.test(t))r="RT";return[ur,r]}return[ur,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[jo,t.join(".")]}return[jo,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=li(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+$i+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$i+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[$i,t.join(".")]}return[$i,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let i=[e[1],e[2],e[3]||"0"];t[1]=i.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ZP,""]],[/Linux|debian/i,["Linux",""]]];var RA="utf8",NP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function YP(e){return typeof e=="string"&&NP.test(e)}function _o(e,t){return YP(e)?e:t()}function GA(e){return e?.replace(/\/+$/,"")}async function wA(e,t){let i=null;for(let n=0;n<t.retryCount+1;n++){if(n>0)await new Promise((r)=>setTimeout(r,t.retryDelay));try{return await e()}catch(r){if(i=r,!t.retryCheck(r))throw r}}throw i}function Ol(){return new Date().toISOString()}function de(e,t){let i=setTimeout(e,t);return i?.unref&&i?.unref(),i}var FA=(e)=>e instanceof Error;function zl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((i)=>({status:"fulfilled",value:i}),(i)=>({status:"rejected",reason:i}))))}var SP={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},fJ=SP.info;function jl(e){if(aA(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(It(e))return{arrayValue:{values:e.map((t)=>jl(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function mr(e){let t=[];for(let i in e){let n=e[i];if(!(sA(n)||li(n)))t.push({key:i,value:jl(n)})}return t}var pr=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Dl(e){return String(e)+"000000"}function Ql(e,t,i,n){let r="";if(n)r=Object.keys(n).sort().map((s)=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",");return`${e}\x00${t}\x00${i??""}\x00${r}`}function HA(e,t){for(let i=0;i<t.length;i++)if(e<=t[i])return i;return t.length}function _l(e,t,i){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":i}}function Kl(e,t,i,n){return{resourceMetrics:[{resource:{attributes:mr(t)},scopeMetrics:[{scope:{name:i,version:n},metrics:e}]}]}}function Ko(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var vA=1;class Lo{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:i?.unit,attributes:i?.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:i?.unit,attributes:i?.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:i?.unit,attributes:i?.attributes})}flush(){let e=this._flushPromise,i=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===i)this._flushPromise=null});return this._flushPromise=i,i}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let i,n;try{i=t.attributes?{...t.attributes}:void 0,n=Ql(t.type,t.name,t.unit,i)}catch(s){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,s);return}let r=this._series.get(n);if(!r){if(!this._admitNewSeries())return;r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now()},this._series.set(n,r)}let o=this._typeByName.get(t.name);if(o===void 0)this._typeByName.set(t.name,t.type);else if(o!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(r,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(pr.length+1).fill(0)};let i=e.hist;i.count+=1,i.sum+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),i.bucketCounts[HA(t,pr)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let i=It(t)?t:[t],n=e;for(let r of i)try{let o=r(n);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;n=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return n}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=de(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,i=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(i.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",i.error);return}}_buildPayload(e){return Kl(this._buildMetrics(e),_l(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Dl(Date.now()),i=new Map;for(let n of e.values()){let r=Ql(n.type,n.name,n.unit,void 0),o=i.get(r);if(!o){if(o={name:n.name,...n.unit&&{unit:n.unit}},n.type==="count")o.sum={aggregationTemporality:vA,isMonotonic:!0,dataPoints:[]};else if(n.type==="gauge")o.gauge={dataPoints:[]};else o.histogram={aggregationTemporality:vA,dataPoints:[]};i.set(r,o)}let s=mr(n.attributes??{}),a=Dl(n.windowStartMs);if(n.type==="count"){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,asDouble:n.total??0};o.sum.dataPoints.push(g)}else if(n.type==="gauge"){let g={attributes:s,timeUnixNano:t,asDouble:n.last??0};o.gauge.dataPoints.push(g)}else if(n.hist){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:pr};o.histogram.dataPoints.push(g)}}return Array.from(i.values())}_mergeWindowBack(e){for(let[t,i]of e){let n=this._series.get(t);if(!n){if(this._admitNewSeries())this._series.set(t,i);continue}switch(n.windowStartMs=Math.min(n.windowStartMs,i.windowStartMs),n.type){case"count":n.total=(n.total??0)+(i.total??0);break;case"gauge":break;case"histogram":if(i.hist)if(n.hist){n.hist.count+=i.hist.count,n.hist.sum+=i.hist.sum,n.hist.min=Math.min(n.hist.min,i.hist.min),n.hist.max=Math.max(n.hist.max,i.hist.max);for(let r=0;r<n.hist.bucketCounts.length;r++)n.hist.bucketCounts[r]+=i.hist.bucketCounts[r]}else n.hist=i.hist;break}}}}class Ll{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((i)=>i!==t)}}emit(e,t){for(let i of this.events[e]||[])i(t);for(let i of this.events["*"]||[])i(e,t)}}var Ge={};TW(Ge,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ss,DOMExceptionCoercer:()=>OA,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ar,ErrorCoercer:()=>ts,ErrorEventCoercer:()=>zA,ErrorPropertiesBuilder:()=>qo,EventCoercer:()=>DA,ExceptionStepsBuffer:()=>KA,ObjectCoercer:()=>rs,PrimitiveCoercer:()=>os,PromiseRejectionEventCoercer:()=>QA,ReduceableCache:()=>_A,StringCoercer:()=>is,chromeStackLineParser:()=>Ml,createDefaultStackParser:()=>ql,createStackParser:()=>TA,geckoStackLineParser:()=>$l,getUtf8ByteLength:()=>LA,nodeStackLineParser:()=>xA,opera10StackLineParser:()=>YA,opera11StackLineParser:()=>XA,resolveExceptionStepsConfig:()=>eI,reverseAndStripFrames:()=>UA,stripReservedExceptionStepFields:()=>oN,winjsStackLineParser:()=>NA});var Mo,kA,$o;function PA(e){let t=globalThis._posthogChunkIds;if(!t)return;let i=Object.keys(t);if($o&&i.length===kA)return $o;return kA=i.length,$o=i.reduce((n,r)=>{if(!Mo)Mo={};let o=Mo[r];if(o)n[o[0]]=o[1];else{let s=e(r);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,I=t[r];if(l&&I){n[l]=I,Mo[r]=[l,I];break}}}return n},{}),$o}var UP=4;class qo{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(o,s);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&It(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 i;if(e.cause!=null)i=this.parseStacktrace(e.cause,t);let n;if(e.stack!=""&&e.stack!=null)n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:i,stack:n}}applyChunkIds(e,t){return e.map((i)=>{if(i.filename&&t)i.chunk_id=t[i.filename];return i})}applyCoercers(e,t){for(let i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let i of this.modifiers)t=await i(t);return t}convertToExceptionList(e,t){let i={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)i.stacktrace={type:"raw",frames:e.stack};let n=[i];if(e.cause!=null)n.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return n}buildParsingContext(e){return{chunkIdMap:PA(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,i=0){let n=(o,s)=>{if(!(s<=UP))return;{let a=this.buildCoercingContext(e,t,s);return this.applyCoercers(o,a)}};return{...t,syntheticException:i==0?t.syntheticException:void 0,mechanism:e,apply:(o)=>n(o,i),next:(o)=>n(o,i+1)}}}var se="?";function dt(e,t,i,n,r){let o={platform:e,filename:t,function:i==="<anonymous>"?se:i,in_app:!0};if(!li(n))o.lineno=n;if(!li(r))o.colno=r;return o}var es=(e,t)=>{let i=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return i||n?[e.indexOf("@")!==-1?e.split("@")[0]:se,i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var TP=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,OP=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,zP=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ml=(e,t)=>{let i=TP.exec(e);if(i){let[,r,o,s]=i;return dt(t,r,se,+o,+s)}let n=OP.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=zP.exec(n[2]);if(a)n[2]=a[1],n[3]=a[2],n[4]=a[3]}let[o,s]=es(n[1]||se,n[2]);return dt(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var jP=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,DP=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,$l=(e,t)=>{let i=jP.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){let s=DP.exec(i[3]);if(s)i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]=""}let r=i[3],o=i[1]||se;return[o,r]=es(o,r),dt(t,r,o,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}};var QP=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,NA=(e,t)=>{let i=QP.exec(e);return i?dt(t,i[2],i[1]||se,+i[3],i[4]?+i[4]:void 0):void 0};var _P=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,YA=(e,t)=>{let i=_P.exec(e);return i?dt(t,i[2],i[3]||se,+i[1]):void 0},KP=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,XA=(e,t)=>{let i=KP.exec(e);return i?dt(t,i[5],i[3]||i[4]||se,+i[1],+i[2]):void 0};var LP=/^\s*[-]{4,}$/,MP=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$P=/^Promise\.(?:all|any)$/,qP=/^index \d+$/,eN="node:internal/promise",xA=(e,t)=>{let i=e.match(MP);if(i){let n,r,o,s,a;if(i[1]){o=i[1];let I=o.lastIndexOf(".");if(o[I-1]===".")I--;if(I>0){n=o.slice(0,I),r=o.slice(I+1);let d=n.indexOf(".Module");if(d>0)o=o.slice(d+1),n=n.slice(0,d)}s=void 0}if(r)s=n,a=r;if(r==="<anonymous>")a=void 0,o=void 0;if(o===void 0)a=a||se,o=s?`${s}.${a}`:a;let g=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";if(g?.match(/\/[A-Z]:/))g=g.slice(1);if(!g&&i[5]&&!l)g=i[5];if($P.test(o)&&qP.test(g||""))g=eN;return{filename:g?decodeURI(g):void 0,module:void 0,function:o,lineno:SA(i[3]),colno:SA(i[4]),in_app:tN(g||"",l),platform:t}}if(e.match(LP))return{filename:e,platform:t}};function tN(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 SA(e){return parseInt(e||"",10)||void 0}var EA=/\(error: (.*)\)/,JA=50;function UA(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,JA).map((i)=>({...i,filename:i.filename||iN(t).filename,function:i.function||se}))}function iN(e){return e[e.length-1]||{}}function ql(){return TA("web:javascript",Ml,$l)}function TA(e,...t){return(i,n=0)=>{let r=[],o=i.split(`
141
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let g=EA.test(a)?a.replace(EA,"$1"):a;if(!g.match(/\S*Error: /)){for(let l of t){let I=l(g,e);if(I){r.push(I);break}}if(r.length>=JA)break}}return UA(r)}}class OA{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=Rt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ii(e,"DOMException")}isDOMError(e){return Ii(e,"DOMError")}}class ts{match(e){return gA(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 i=e.message;if(i.error&&typeof i.error.message=="string")return String(i.error.message);return String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class zA{constructor(){}match(e){return lA(e)&&e.error!=null}coerce(e,t){let i=t.apply(e.error);if(!i)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return i}}var nN=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class is{match(e){return typeof e=="string"}coerce(e,t){let[i,n]=this.getInfos(e);return{type:i??"Error",value:n??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,n=e.match(nN);if(n)t=n[1],i=n[2];return[t,i]}}var jA=["fatal","error","warning","log","info","debug"];function ns(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let n=i.length;n>0;n--){let r=i.slice(0,n).join(", ");if(!(r.length>t)){if(n===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class rs{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let i=this.getErrorPropertyFromObject(e);if(i)return t.apply(i);return{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 Mi(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")n+=` with message: '${e.message}'`;return n}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),i=ns(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return Rt(e)&&!oA(e)&&jA.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(FA(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class DA{match(e){return Mi(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${ns(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class os{match(e){return Oo(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class QA{match(e){return Ii(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Mi(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);if(Oo(i))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class _A{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Ar={MESSAGE:"$message",TIMESTAMP:"$timestamp"},rN=new Set([Ar.MESSAGE,Ar.TIMESTAMP]),ss={enabled:!0,max_bytes:32768};function eI(e){if(!e)return{...ss};return{enabled:e.enabled??ss.enabled,max_bytes:sN(e.max_bytes,ss.max_bytes)}}function oN(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,r)=>{if(rN.has(r))return t.push(r),n;return n[r]=e[r],n},{}),droppedKeys:t}}class KA{constructor(e){this._entries=[],this._totalBytes=0,this._config=eI(e)}setConfig(e){this._config=eI(e),this._trimToMaxBytes()}add(e){let t=aN(e);if(!t)return;let i=LA(t.json);if(i>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function sN(e,t){if(!cr(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function aN(e){let t;try{t=Li(e)}catch{return}try{let i=JSON.parse(t);if(!dr(i))return;let n=i,r=n[Ar.MESSAGE],o=n[Ar.TIMESTAMP];if(!Rt(r)||r.trim().length===0)return;if(!Rt(o)&&!cr(o))return;return{step:n,json:t}}catch{return}}function LA(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let n=0;n<t.length;n++)if(t[n]==="%")i+=1,n+=2;else i+=1;return i}class jt 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()}}class ci extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var qA=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function MA(e){if(e instanceof jt){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 gN(e){return typeof e=="object"&&(e instanceof jt||eZ(e))}function eZ(e){return e instanceof ci}function lN(e){if(e instanceof jt)return e.status===502||e.status===504;if(!(e instanceof ci))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function en(e){return typeof e=="object"&&e instanceof jt&&e.status===413}function Zr(e){if(e instanceof jt)return e.status===408||e.status===429||e.status>=500;return eZ(e)}function $A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var tI="default";class as{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new qo([new ts,new rs,new is,new os],ql())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Sl,this._events=new Ll,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=mA("[PostHog]",this.logMsgIfDebug.bind(this)),r)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=i,this.host=GA(n||"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??1000),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??3000,retryCheck:Zr},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||r,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!Yl()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(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(He.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(He.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(He.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};if(qA(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=lr(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(e,t,i){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,i)}captureStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",r,n)})}async captureStatelessImmediate(e,t,i,n){let r=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",r,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",r,n)})}async aliasStatelessImmediate(e,t,i,n){let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",r,n)}groupIdentifyStateless(e,t,i,n,r,o){this.wrap(()=>{let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,r,o){let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});await this.sendImmediate("capture",s,n)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,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(e,t={},i={},n={},r={},o=!1){await this._initPromise;let s=o?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,g={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)g.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)g.evaluation_contexts=this.evaluationContexts;let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(g)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:lN},this.featureFlagsRequestTimeoutMs).then((I)=>I.json()).then((I)=>({success:!0,response:Nl(I)})).catch((I)=>(this._events.emit("error",I),{success:!1,error:this.categorizeRequestError(I)}))}categorizeRequestError(e){if(e instanceof jt)return{type:"api_error",statusCode:e.status};if(e instanceof ci){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,r,o);if(s===void 0)return{response:void 0,requestId:void 0};let a=gr(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,r,o,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,r,o,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},r,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},r,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,r,o);if(!s)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}}async getFeatureFlagDetailsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s={geoip_disable:r??this.disableGeoip};if(o)s.flag_keys_to_evaluate=o;let a=await this.getFlags(e,t,i,n,s);if(!a.success)return;let g=a.response;if(g.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");if(g.quotaLimited?.includes("feature_flags"))return 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:g?.requestId,quotaLimited:g.quotaLimited};return g}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)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((r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);this._logger.error(s),this._events.emit("error",Error(o));return}return r.json()}).catch((r)=>{this._logger.error("Surveys API could not be loaded",r),this._events.emit("error",r)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(He.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(He.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(He.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tI}persistedQueueKeyForRoute(e){return He.Queue}getActiveQueueRoutes(){return[tI]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let r=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),o=this.getPersistedProperty(r)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:n}),this.setPersistedProperty(r,o),this._events.emit(e,n),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(r){this._events.emit("error",r)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=$A(r.properties)?r.properties:void 0;if(i!==void 0&&o?.$lib===void 0)o={...o||{},$lib:i};if(n!==void 0&&o?.$lib_version===void 0)o={...o||{},$lib_version:n};if(o)r.properties=o;return r.uuid=_o(r.uuid,ve),r}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:Ol(),uuid:_o(t?.uuid,ve)};if(t?.disableGeoip??this.disableGeoip){if(!$A(i.properties))i.properties={};i.properties.$geoip_disable=!0}if(i.distinctId)i.distinct_id=i.distinctId,delete i.distinctId;return i}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await MA(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((r)=>!!r),n=0;while(!0){let r=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(r.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${r.length} pending promise(s) before flushing`);await Promise.all(r.map((o)=>o.catch(()=>{}))),n++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,n])}).then(()=>zl([t])).then(()=>{if(this.pendingFlushPromise===n)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=n,this.flushPromise=n,this.flushPromises.add(n),this.addPendingPromise(n),zl([n]).then(()=>{if(this.flushPromises.delete(n),this.pendingFlushPromise===n)this.pendingFlushPromise=null;if(this.flushPromise===n)this.flushPromise=null}),n}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,i=tI){let n={api_key:this.apiKey,batch:e,sent_at:Ol()};if(this.historicalMigration)n.historical_migration=!0;let r=Li(n),o=`${this.host}/batch/`,s=this.disableCompression?null:await gi(r,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await(await this.fetchWithRetry(o,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((n)=>this.getRouteQueue(n).length>0))return;let t=[],i;for(let n of e)try{await this._flushRoute(n,t)}catch(r){if(i===void 0)i=r}if(i!==void 0)throw i;this._events.emit("flush",t)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(i)||[];if(!n.length)return;let r=n.length,o=0;while(n.length>0&&o<r){let s=n.slice(0,this.maxBatchSize),a=s.map((I)=>I.message===void 0?I.message:this.normalizeMessage(I.message)),g=async()=>{let d=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,d),n=d,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:(I)=>{if(en(I))return!1;return Zr(I)}};try{await this.sendBatch(a,l,e)}catch(I){if(en(I)&&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}if(!(I instanceof ci))await g();throw this._events.emit("error",I),I}await g(),t.push(...a),o+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(en(o))return!1;return Zr(o)}}),{kind:"ok"}}catch(o){if(en(o))return{kind:"too-large"};if(o instanceof ci)return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(en(o))return!1;return Zr(o)}}),{kind:"ok"}}catch(o){if(en(o))return{kind:"too-large"};if(Zr(o))return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async fetchWithRetry(e,t,i,n){let r=t.body?t.body:"",o=-1;try{o=r instanceof Blob?r.size:Buffer.byteLength(r,RA)}catch{if(r instanceof Blob)o=r.size;else o=new TextEncoder().encode(r).length}return await wA(async()=>{let s=new AbortController,a=n??this.requestTimeout,g=de(()=>s.abort(),a),l=null;try{l=await this.fetch(e,{signal:s.signal,...t})}catch(d){throw new ci(d)}finally{clearTimeout(g)}if(t.mode!=="no-cors"&&(l.status<200||l.status>=400))throw new jt(l,o);return l},{...this._retryOptions,...i})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let i=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((s)=>this.getRouteQueue(s).length>0))break;let o=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(r){if(!gN(r))throw r;await MA(r)}},n;try{return await Promise.race([new Promise((r,o)=>{n=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(n)}}async shutdown(e=30000){if(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");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var nZ=require("fs"),rZ=require("readline"),gs=new Ge.ReduceableCache(25),oZ=new Ge.ReduceableCache(20),iI=7,uN=1000,mN=1e4;async function sZ(e){let t={};for(let r=e.length-1;r>=0;r--){let o=e[r],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||bN(s)||hN(o))continue;if(!t[s])t[s]=[];t[s].push(o.lineno)}let i=Object.keys(t);if(i.length==0)return e;let n=[];for(let r of i){if(oZ.get(r))continue;let o=t[r];if(!o)continue;o.sort((g,l)=>g-l);let s=fN(o);if(s.every((g)=>WN(r,g)))continue;let a=yN(gs,r,{});n.push(pN(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)AN(e,gs);return gs.reduce(),e}function pN(e,t,i){return new Promise((n)=>{let r=nZ.createReadStream(e),o=rZ.createInterface({input:r});function s(){r.destroy(),n()}let a=0,g=0,l=t[g];if(l===void 0)return void s();let I=l[0],d=l[1];function C(){oZ.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",C),o.on("error",C),o.on("close",s),o.on("line",(A)=>{if(a++,a<I)return;if(i[a]=VN(A,0),a>=d){if(g===t.length-1){o.close(),o.removeAllListeners();return}g++;let c=t[g];if(c===void 0){o.close(),o.removeAllListeners();return}I=c[0],d=c[1]}})})}function AN(e,t){for(let i of e)if(i.filename&&i.context_line===void 0&&typeof i.lineno=="number"){let n=t.get(i.filename);if(n===void 0)continue;ZN(i.lineno,i,n)}}function ZN(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=aZ(e);r<e;r++){let o=i[r];if(o===void 0)return void tZ(t);t.pre_context.push(o)}if(i[e]===void 0)return void tZ(t);t.context_line=i[e];let n=gZ(e);t.post_context=[];for(let r=e+1;r<=n;r++){let o=i[r];if(o===void 0)break;t.post_context.push(o)}}function tZ(e){delete e.pre_context,delete e.context_line,delete e.post_context}function bN(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function hN(e){if(e.lineno!==void 0&&e.lineno>mN)return!0;if(e.colno!==void 0&&e.colno>uN)return!0;return!1}function WN(e,t){let i=gs.get(e);if(i===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(i[n]===void 0)return!1;return!0}function fN(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=iZ(i),r=[];while(!0){if(t===e.length-1){r.push(n);break}let o=e[t+1];if(typeof o!="number")break;if(o<=n[1])n[1]=o+iI;else r.push(n),n=iZ(o);t++}return r}function iZ(e){return[aZ(e),gZ(e)]}function aZ(e){return Math.max(1,e-iI)}function gZ(e){return e+iI}function yN(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function VN(e,t){let i=e,n=i.length;if(n<=150)return i;if(t>n)t=n;let r=Math.max(t-60,0);if(r<5)r=0;let o=Math.min(r+140,n);if(o>n-5)o=n;if(o===n)r=Math.max(o-140,0);if(i=i.slice(r,o),r>0)i=`...${i}`;if(o<n)i+="...";return i}var tn=require("path");function lZ(e=process.cwd()){let t=tn.sep==="\\",i=(r)=>t?r.replace(/\\/g,"/"):r,n=i(e);return async(r)=>{for(let o of r)if(!(!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:"))){if(tn.isAbsolute(o.filename))o.filename=i(tn.relative(n,i(o.filename)))}return r}}var IZ="5.46.1";var Gt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Ci{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let i=this._flags[t];if(i)e[t]=i}return this._cloneWith(e)}only(e){let t={},i=[];for(let n of e){let r=this._flags[n];if(r)t[n]=r;else i.push(n)}if(i.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,n]of Object.entries(this._flags)){let r=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${i}`]=r,n.enabled)t.push(i)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Ci({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],i=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,n={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)n.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)n.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let r=[];if(this._errorsWhileComputing)r.push(Gt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(Gt.QUOTA_LIMITED);if(t===void 0)r.push(Gt.FLAG_MISSING);if(r.length>0)n.$feature_flag_error=r.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function dZ(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let i=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map((r)=>r.toString(16).padStart(2,"0")).join("")}var BN=60000,RN=1152921504606847000,GN=["is_not","is_set"];class nn extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,nn.prototype)}}function mZ(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class J extends Error{constructor(e){super(e);mZ(this,J)}}class ct extends Error{constructor(e){super(e);mZ(this,ct)}}class nI{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:r,customHeaders:o,...s}){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=n,this.projectApiKey=i,this.host=r,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=o,this.onLoad=s.onLoad,this.onMinimalFlagCalledEvents=s.onMinimalFlagCalledEvents,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},i={},n={},r={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:r}}async getFeatureFlag(e,t,i={},n={},r={}){await this.loadFeatureFlags();let o,s;if(!this.loadedSuccessfullyOnce)return o;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,r);try{o=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(g){if(g instanceof ct||g instanceof J)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${e}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${g}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},r=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async(a)=>{try{let{value:g,payload:l}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=g,l)n[a.key]=l}catch(g){if(g instanceof ct||g instanceof J)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${a.key}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${g}`));r=!0}})),{response:i,payloads:n,fallbackToFlags:r}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:r=!1}=i;if(!r)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:r,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new J("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let g=this.groupTypeMapping[String(a)];if(!g)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new J("Flag has unknown group type index");if(!(g in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(r?.$device_id===void 0||r?.$device_id===null||r?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=o[g];return await this.matchFeatureFlagProperties(e,n[g],l,t)}{let g=this.getBucketingValueForFlag(e,i,r);if(g===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new J(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,g,r,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=i?.$device_id;if(n==null||n==="")return;return n}return t}getFeatureFlagPayload(e,t){let i=null;if(t!==!1&&t!=null){if(typeof t=="boolean")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(i!=null){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:n}=i,r=e.key;if(!this.featureFlagsByKey)throw new J("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new J(`Flag dependency property for '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new J(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new J(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let l=this.featureFlagsByKey[a];if(l)if(l.active)try{let I=await this.computeFlagValueLocally(l,i);n[a]=I}catch(I){throw new J(`Error evaluating flag dependency '${a}' for flag '${r}': ${I}`)}else n[a]=!1;else throw new J(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new J(`Dependency '${a}' could not be evaluated`)}let s=n[r];return this.flagEvaluatesToExpectedValue(e.value,s)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,i,n){let r=e.filters||{},o=r.groups||[],s=r.aggregation_group_type_index,a=r.early_exit??!1,{groups:g,groupProperties:l}=n,I=!1,d;for(let C of o)try{let A=C.aggregation_group_type_index!==void 0?C.aggregation_group_type_index:s,c=i,u=t;if(A!==s){if(A!=null){let W=this.groupTypeMapping[String(A)];if(!W||!(W in g)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${A} not available`));continue}if(!(W in l)){I=!0;continue}c=l[W],u=g[W]}}let Z=await this.isConditionMatch(e,u,C,c,n);if(Z==="match"){let W=C.variant,m=r.multivariate?.variants||[];d=W&&m.some((b)=>b.key===W)?W:await this.getMatchingVariant(e,u)||!0;break}if(a&&Z==="out_of_rollout_bound")return!1}catch(A){if(A instanceof ct)throw A;if(A instanceof J)I=!0;else throw A}if(d!==void 0)return d;if(I)throw new J("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,n,r){let o=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let g=a.type,l=!1;if(g==="cohort"){let I=await AZ(a,n,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,n,r));l=a.operator==="not_in"?!I:I}else l=g==="flag"?await this.evaluateFlagDependency(a,n,r):pZ(a,n,s);if(!l)return"no_match"}if(o==null)return"match"}if(o!=null&&await cZ(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await cZ(e.key,t,"variant"),n=this.variantLookupTable(e).find((r)=>i>=r.valueMin&&i<r.valueMax);if(n)return n.key}variantLookupTable(e){let t=[],i=0,n=0;return((e.filters||{}).multivariate?.variants||[]).forEach((s)=>{n=i+s.rollout_percentage/100,t.push({valueMin:i,valueMax:n,key:s.key}),i=n}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,i)=>(t[i.key]=i,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((i)=>i.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.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(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(BN,this.pollingInterval*2**this.backOffCount)}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(){if(this.poller)clearTimeout(this.poller),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(i){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(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.clearBackoff();return;case 401:throw this.beginBackoff(),new nn(`Your project key or secret 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={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new nn(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new nn(`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 t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:i.minimal_flag_called_events===!0};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(r){this.onError?.(Error(`Failed to store in cache: ${r}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof nn)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)i["If-None-Match"]=t;return{method:e,headers:i}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.timeout),t.signal=n.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(i)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((i,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function cZ(e,t,i=""){let n=await dZ(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/RN}function pZ(e,t,i){let{key:n,value:r}=e,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new J(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!GN.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(l,I){if(Array.isArray(l))return l.map((d)=>String(d).toLowerCase()).includes(String(I).toLowerCase());return String(l).toLowerCase()===String(I).toLowerCase()}function g(l,I,d){if(d==="gt")return l>I;if(d==="gte")return l>=I;if(d==="lt")return l<I;if(d==="lte")return l<=I;throw Error(`Invalid operator: ${d}`)}switch(o){case"exact":return a(r,s);case"is_not":return!a(r,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(r).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(r).toLowerCase());case"regex":return CZ(String(r))&&String(s).match(String(r))!==null;case"not_regex":return CZ(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof r=="number"?r:parseFloat(String(r)),I;if(I=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(l)&&Number.isFinite(I))return g(I,l,o);return g(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new J("Date operations cannot be performed on boolean values");let l=kN(String(r));if(l==null)l=uZ(r);if(l==null)throw new J(`Invalid date: ${r}`);let I=uZ(s);if(["is_date_before"].includes(o))return I<l;return I>l}case"semver_eq":return Je(ae(String(s)),ae(String(r)))===0;case"semver_neq":return Je(ae(String(s)),ae(String(r)))!==0;case"semver_gt":return Je(ae(String(s)),ae(String(r)))>0;case"semver_gte":return Je(ae(String(s)),ae(String(r)))>=0;case"semver_lt":return Je(ae(String(s)),ae(String(r)))<0;case"semver_lte":return Je(ae(String(s)),ae(String(r)))<=0;case"semver_tilde":{let l=ae(String(s)),{lower:I,upper:d}=FN(String(r));return Je(l,I)>=0&&Je(l,d)<0}case"semver_caret":{let l=ae(String(s)),{lower:I,upper:d}=HN(String(r));return Je(l,I)>=0&&Je(l,d)<0}case"semver_wildcard":{let l=ae(String(s)),{lower:I,upper:d}=vN(String(r));return Je(l,I)>=0&&Je(l,d)<0}default:throw new J(`Unknown operator: ${o}`)}}function wN(e,t){if(!(e in t))throw new ct(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function AZ(e,t,i,n=!1,r){let o=String(e.value);wN(o,i);let s=i[o];return ZZ(s,t,i,n,r)}async function ZZ(e,t,i,n=!1,r){if(!e)return!0;let{type:o,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let g of s)try{let l=await ZZ(g,t,i,n,r);if(o==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof ct)throw l;if(l instanceof J){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new J("Can't match cohort without a given cohort property value");return o==="AND"}for(let g of s)try{let l;if(g.type==="cohort")l=await AZ(g,t,i,n,r);else if(g.type==="flag"){if(!r)throw new J(`Flag dependency '${g.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await r(g)}else l=pZ(g,t);let I=g.negation||!1;if(o==="AND"){if(!l&&!I)return!1;if(l&&I)return!1}else{if(l&&!I)return!0;if(!l&&I)return!0}}catch(l){if(l instanceof ct)throw l;if(l instanceof J){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new J("can't match cohort without a given cohort property value");return o==="AND"}function CZ(e){try{return new RegExp(e),!0}catch(t){return!1}}function bZ(e,t){if(!/^\d+$/.test(e))throw new J(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new J(`Invalid semver: ${t}`);return parseInt(e,10)}function ae(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new J(`Invalid semver: ${e}`);let n=i.split("."),r=(g)=>{if(g===void 0||g==="")return 0;return bZ(g,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function Je(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}function FN(e){let t=ae(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function HN(e){let t=ae(e),[i,n,r]=t,o=[i,n,r],s;return s=i>0?[i+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:o,upper:s}}function vN(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new J(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(g)=>{try{return bZ(g,e)}catch{throw new J(`Invalid wildcard semver: ${e}`)}},o=r(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let g=r(n[1]);s=[o,g,0],a=[o,g+1,0]}return{lower:s,upper:a}}function uZ(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 J(`${e} is in an invalid date format`)}throw new J(`The date provided ${e} must be a string, number, or date object`)}function kN(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,i=e.match(t),n=new Date(new Date().toISOString());if(!i)return null;{if(!i.groups)return null;let r=parseInt(i.groups.number);if(r>=1e4)return null;let o=i.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-r);else if(o=="d")n.setUTCDate(n.getUTCDate()-r);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*r);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-r);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-r)}return n}}function PN(e,t){let i=!1;return Object.assign((n)=>{let o=global.process.listeners("uncaughtException").filter((s)=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!i&&o)i=!0,t(n)},{_posthogErrorHandler:!0})}function hZ(e,t){globalThis.process?.on("uncaughtException",PN(e,t))}function WZ(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var NN=2000;class Ct{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Xl({...dA(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return dr(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,i,n,r){let o={...r},s=e.buildFromUnknown(t,i);return s.$exception_list=await e.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())hZ(this.onException.bind(this),this.onFatalError.bind(this)),WZ(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ct.isPreviouslyCapturedError(e)){let i=await Ct.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(r))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:r});return this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(NN),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class rI{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function YN(e){return e==="v0"||e==="v1"}function fZ(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return YN(e)?e:"v0"}var br="analytics",hr="ai";function yZ(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class rn extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super(rn.buildMessage(e,t,i,n)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=n}static buildMessage(e,t,i,n){let r=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;if(n instanceof Error)r+=` (${n.message})`;return r}}function oI(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function XN(e){return typeof e=="string"?e:void 0}var SN=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:oI},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:oI},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:oI},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:XN}],xN=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function EN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function JN(e){if(typeof e=="string"){let i=new Date(e);return Number.isNaN(i.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function VZ(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function UN(e){let i={...EN(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of SN)if(o in i){let g=a(i[o]);if(g!==void 0)n[s]=g;delete i[o]}let r={};for(let{property:o,field:s}of xN)if(o in i){let a=i[o];if(typeof a=="string")r[s]=a;delete i[o]}return delete i.$lib,delete i.$lib_version,VZ(i,"$set",e.$set),VZ(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:JN(e.timestamp),...r,options:n,properties:i}}function BZ(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(UN)};if(i)n.historical_migration=!0;return n}var TN="/i/v1/analytics/events",ON=30000,zN=new Set([408,500,502,503,504]);class sI{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??ON,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>de(n,i))),this.generateRequestId=t.generateRequestId??ve,this.compress=t.compress??gi}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=BZ(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${TN}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let g=1;g<=a;g++){let l=g===a,I=Li({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),d;try{d=await this.sendOnce(r,I,g,t)}catch(Z){if(l)return this.surfaceBatchFailure(t,o,s,Z);await this.sleep(this.backoffDelay(g));continue}let{status:C}=d;if(C<200||C>=300){if(!l&&zN.has(C)){let W=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(g,W));continue}let Z=await this.buildHttpError(d,C);return this.surfaceBatchFailure(t,o,s,Z)}let A;try{A=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${C} response body`))}let c=this.classify(s,A,o);if(c.length===0)return this.surfacePartialDrops(t,o);if(l)return void this.onError(new rn({requestId:t,drops:o,retryExhausted:c.map((Z)=>Z.uuid)}));s=c;let u=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(g,u))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let g=await this.compress(t,this.config.isDebug);if(g!==null)o=g,r["Content-Encoding"]="gzip"}let s=new AbortController,a=de(()=>s.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:r,body:o,signal:s.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)n["User-Agent"]=this.config.userAgent;return n}classify(e,t,i){let n=t.results??{},r=[];for(let o of e){let s=n[o.uuid];if(s){if(s.result==="drop")i.push({uuid:o.uuid,details:s.details??void 0});else if(s.result==="retry")r.push(o)}}return r}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return i;return Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let o=parseInt(i,10);return Number.isFinite(o)&&o>0?1000*o:void 0}let n=Date.parse(i);if(Number.isNaN(n))return;let r=n-this.now();return r>0?r:void 0}async parseResponse(e){let t=await e.text(),i=JSON.parse(t);if(typeof i!="object"||i===null||Array.isArray(i))throw Error("unexpected response shape");let n=i.results;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw Error("unexpected results shape");return{results:n??{}}}async buildHttpError(e,t){let i="";try{i=(await e.text()).slice(0,512)}catch{}let n=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${n}`)}surfaceBatchFailure(e,t,i,n){this.onError(new rn({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new rn({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var jN=100,RZ=30000,DN=50000,QN=50,_N=500,KN="https://us.i.posthog.com",GZ=new Set;function ls(e,t){if(GZ.has(e))return;GZ.add(e),console.warn(`[PostHog] ${t}`)}function LN(e){return typeof e=="string"?e.trim():""}function MN(e){return(typeof e=="string"?e.trim():"")||void 0}function $N(e){return(typeof e=="string"?e.trim():"")||KN}function qN(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function eY(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let i=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(i.length>0)t.$active_feature_flags=i;return t}class aI extends as{constructor(e,t={}){let i=LN(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:$N(t.host),personalApiKey:MN(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new rI,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=fZ(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,jN):RZ,typeof n.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(n.waitUntilDebounceMs,0);if(typeof n.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(n.waitUntilMaxWaitMs,0);if(!this.disabled&&n.personalApiKey){if(n.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.');if(n.enableLocalEvaluation!==!1)this.featureFlagsPoller=new nI({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:i,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(o)=>{this._events.emit("error",o)},onLoad:(o)=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:(o)=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new Ct(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||DN}enqueue(e,t,i){super.enqueue(e,t,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,s=new Promise((a)=>{o=a});try{e(s)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??_N,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??QN;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},r)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}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)}getQueueRouteKey(e){return this.captureMode==="v1"&&yZ(e)?hr:br}persistedQueueKeyForRoute(e){return e===hr?He.AiQueue:He.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[br,hr]:[br]}async sendBatch(e,t,i=br){if(this.captureMode!=="v1"||i===hr)return super.sendBatch(e,t,i);let n=e.filter((r)=>r!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new sI({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return IZ}get metrics(){if(!this._metrics)this._metrics=new Lo(this,Ko(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(i)}_sendPreparedEvent(e,t,i,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:r,event:o,properties:s,options:a})=>{let g={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,l,g):this.enqueue(e,l,g)}).catch((r)=>{if(r)console.error(r)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(Object.keys(t).length===0&&Object.keys(i).length===0)return;let n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(i).length>0)n.$set_once=i;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let i=qN(t);if(i.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=RZ){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let i=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",(r)=>{clearTimeout(i),n(),t(r>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,i={},n){if(this.disabled)return void this._logger.warn("The client is disabled");let r=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let y=this._flagOverrides[e];if(y===void 0)return;let B=this._payloadOverrides?.[e];return{key:e,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:B}}let{groups:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=i,I=this.addLocalPersonAndGroupProperties(t,o,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C,A=!1,c,u,Z,W,m,b,h;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let y=this.featureFlagsPoller?.featureFlagsByKey[e];if(y)try{let B=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(y,d,{matchValue:n});if(B){A=!0;let F=B.value;W=y.id,b="Evaluated locally",h=y.has_experiment,C={key:e,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:B.payload??void 0}}}catch(B){if(B instanceof ct||B instanceof J)this._logger?.info(`${B.name} when computing flag locally: ${e}: ${B.message}`);else throw B}}if(!A&&!a){let y=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,g,l,s,[e]);if(y===void 0)Z=Gt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,c=y.requestId,u=y.evaluatedAt;let B=[];if(y.errorsWhileComputingFlags)B.push(Gt.ERRORS_WHILE_COMPUTING);if(y.quotaLimited?.includes("feature_flags"))B.push(Gt.QUOTA_LIMITED);let F=y.flags[e];if(F===void 0)B.push(Gt.FLAG_MISSING);else{W=F.metadata?.id,m=F.metadata?.version,b=F.reason?.description??F.reason?.code,h=F.metadata?.has_experiment;let w;if(F.metadata?.payload!==void 0)try{w=JSON.parse(F.metadata.payload)}catch{w=F.metadata.payload}C={key:e,enabled:F.enabled,variant:F.variant,payload:w}}if(B.length>0)Z=B.join(",")}}if(r){let y=C===void 0?void 0:C.enabled===!1?!1:C.variant??!0,B={$feature_flag:e,$feature_flag_response:y,$feature_flag_id:W,$feature_flag_version:m,$feature_flag_reason:b,locally_evaluated:A,[`$feature/${e}`]:y,$feature_flag_request_id:c,$feature_flag_evaluated_at:A?Date.now():u};if(h!==void 0)B.$feature_flag_has_experiment=h;if(A&&this.featureFlagsPoller){let F=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(F!==void 0)B.$feature_flag_definitions_loaded_at=F}if(Z)B.$feature_flag_error=Z;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:y,groups:o,disableGeoip:s,properties:B})}if(C!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)C={...C,payload:this._payloadOverrides[e]};return C}async getFeatureFlag(e,t,i){ls("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return n.variant??!0}async getFeatureFlagPayload(e,t,i,n){if(ls("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},i);if(r===void 0)return;return r.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:n,options:r}=this._resolveDistinctId(t,i);if(!n)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,n,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");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 i=await t.json();if(typeof i=="string")try{return JSON.parse(i)}catch(n){}return i}async isFeatureEnabled(e,t,i){ls("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return!!(n.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(i,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},I=this.addLocalPersonAndGroupProperties(i,r,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,s),A={},c={},u=!0;if(C)A=C.response,c=C.payloads,u=C.fallbackToFlags;if(u&&!a){let Z=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,g,l,o,s);A={...A,...Z.flags||{}},c={...c,...Z.payloads||{}}}if(this._flagOverrides!==void 0)A={...A,...this._flagOverrides};if(this._payloadOverrides!==void 0)c={...c,...this._payloadOverrides};return{featureFlags:A,featureFlagPayloads:c}}async evaluateFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},I=this.addLocalPersonAndGroupProperties(i,r,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C={},A,c,u=!1,Z=!1,W=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,s),m=new Set;if(W)for(let[h,f]of Object.entries(W.response)){let y=this.featureFlagsPoller?.featureFlagsByKey[h];C[h]={key:h,enabled:f!==!1,variant:typeof f=="string"?f:void 0,payload:W.payloads[h],id:y?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:y?.has_experiment},m.add(h)}if((W?W.fallbackToFlags:!0)&&!a){let h=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,g,l,o,s);if(h){this._minimalFlagCalledEvents=h.minimalFlagCalledEvents===!0,A=h.requestId,c=h.evaluatedAt,u=Boolean(h.errorsWhileComputingFlags),Z=Array.isArray(h.quotaLimited)&&h.quotaLimited.includes("feature_flags");for(let[f,y]of Object.entries(h.flags)){if(m.has(f))continue;let B;if(y.metadata?.payload!==void 0)try{B=JSON.parse(y.metadata.payload)}catch{B=y.metadata.payload}C[f]={key:f,enabled:y.enabled,variant:y.variant,payload:B,id:y.metadata?.id,version:y.metadata?.version,reason:y.reason?.description??y.reason?.code,locallyEvaluated:!1,hasExperiment:y.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[h,f]of Object.entries(this._flagOverrides)){if(f===void 0){delete C[h];continue}let y=C[h];C[h]={key:h,enabled:f!==!1,variant:typeof f=="string"?f:void 0,payload:y?.payload,id:y?.id,version:y?.version,reason:y?.reason,locallyEvaluated:y?.locallyEvaluated??!1,hasExperiment:y?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[h,f]of Object.entries(this._payloadOverrides)){let y=C[h];if(y)C[h]={...y,payload:f}}return new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:C,requestId:A,evaluatedAt:c,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:u,quotaLimited:Z})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:n,groups:r,disableGeoip:o,properties:s}=e,a=r&&Object.keys(r).length>0?`_${JSON.stringify(Object.entries(r).sort(([l],[I])=>l<I?-1:l>I?1:0))}`:"",g=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(g))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(g);else this.distinctIdHasSentFlagCalls[t]=new Set([g]);this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:r,disableGeoip:o})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(i)=>Object.fromEntries(i.map((n)=>[n,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let i=t.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in t){let i=t.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(e,t,i){if(!this.context)return t();return this.context.run(e,t,i)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),i=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((n)=>de(n,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/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 r=new AbortController;n=de(()=>{r.abort()},this.options.requestTimeout),i.signal=r.signal}try{return await this.fetch(t,i)}catch(r){this._events.emit("error",r);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[r,o]of Object.entries(e))if(IA(o)&&t&&r in t){let s={};for(let[a,g]of Object.entries(o))s[String(a)]=String(g);n[String(r)]=s}else i[String(r)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(e,t,i,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let r=n?.personProperties||{},o=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let g={};for(let[l,I]of Object.entries(t||{}))g[l]=String(I);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[l,I]of Object.entries(t||{}))g[l]=String(I);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,r,o,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let r={...i||{}},o={};if(t)for(let s of Object.keys(t))o[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:r,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,n){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,i,n,r){if(!Ct.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(Ct.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,i).then((s)=>this._capturePreparedEvent({...s,uuid:n,flags:r},!1)))}}async captureExceptionImmediate(e,t,i,n){if(!Ct.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(Ct.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((o)=>this.captureImmediate({...o,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:r,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:I}=e,d=this.context?.get(),C=t.includeContextProperties??!0,A=i||d?.distinctId,c=C?{...this.props,...d?.properties||{},...r||{}}:{...r||{}};if(!A)A=ve(),c.$process_person_profile=!1;if(C&&d?.sessionId&&!c.$session_id)c.$session_id=d.sessionId;let u=this._shouldSendMinimalFlagCalledEvent(n,c)?lr(c):c,Z=this._runBeforeSend({distinctId:A,event:n,properties:u,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:I});if(!Z)return Promise.reject(null);let W=await Promise.resolve().then(async()=>{if(s){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return s._getEventProperties()}if(a){ls("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let m=typeof a=="object"?a:void 0,b=await this.getFeatureFlagsForEvent(Z.distinctId,o,l,m);return eY(b)}return{}}).catch(()=>({})).then((m)=>{let b=Z.groups||o;return{...m,...Z.properties||{},...b!==void 0&&Object.keys(b).length>0?{$groups:b}:{}}});if(Z.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof W.$raw_user_agent=="string"){if(nA(W.$raw_user_agent,this.options.custom_blocked_useragents||[]))Z.event="$bot_pageview",W.$browser_type="bot"}return{distinctId:Z.distinctId,event:Z.event,properties:W,options:{timestamp:Z.timestamp,disableGeoip:Z.disableGeoip,uuid:Z.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],n=e;for(let r of i){if(n=r(n),!n)return this._logger.info(`Event '${e.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 wZ=require("async_hooks");class gI{constructor(){this.storage=new wZ.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}function tY(e,{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:o=!0}={}){return(s)=>{if(!(r==="*"||r.includes(s.level)))return s;if(!s.tags)s.tags={};let g=s.tags[FZ.POSTHOG_ID_TAG];if(g===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",I=new URL(`/project/${e.apiKey}/person/${g}`,l).toString();s.tags["PostHog Person URL"]=I;let d=s.exception?.values||[],C=d.map((c)=>({...c,stacktrace:c.stacktrace?{...c.stacktrace,type:"raw",frames:(c.stacktrace.frames||[]).map((u)=>({...u,platform:"node:javascript"}))}:void 0})),A={$exception_message:d[0]?.value||s.message,$exception_type:d[0]?.type,$exception_level:s.level,$exception_list:C,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:d[0]?.value||s.message,$sentry_exception_type:d[0]?.type,$sentry_tags:s.tags};if(t&&i)A.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(o)e.capture({event:"$exception",distinctId:g,properties:A});return s}}class FZ{static#i=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,n,r){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(o,s){let a=s()?.getClient()?.getDsn()?.projectId;o(tY(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class lI extends aI{getLibraryId(){return"posthog-node"}initializeContext(){return new gI}createErrorPropertiesBuilder(){return new Ge.ErrorPropertiesBuilder([new Ge.EventCoercer,new Ge.ErrorCoercer,new Ge.ObjectCoercer,new Ge.StringCoercer,new Ge.PrimitiveCoercer],Ge.createStackParser("node:javascript",Ge.nodeStackLineParser),[eA(),sZ,lZ()])}}var Ue=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},on=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var ie=require("fs/promises"),ce=require("path");var Is={name:"@toloka-platform/sdk",version:"0.2.0-preview.1",private:!1,description:"Beta. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./testing":"./src/testing/index.ts","./checks":"./src/checks/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"latest"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts","sync-task-ui-declarations":"bun ./scripts/sync-task-ui-declarations.ts",test:"vitest run","test:browser":"vitest run --config vitest.browser.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.2",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","jsonpath-rfc9535":"1.3.0","oxc-parser":"0.138.0","posthog-node":"5.46.1","typescript-api":"npm:typescript@6.0.3"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",playwright:"1.56.1",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},peerDependencies:{playwright:">=1.56.1 <2",vitest:">=4.1.0 <5"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:"1.4.0"}};var HZ=require("fs/promises"),vZ=require("path"),ds=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),cs=(e)=>ds(e,"ENOENT"),sn=async(e)=>{try{return await HZ.lstat(e)}catch(t){if(cs(t))return;throw t}},Wr=async(e,t,i="write")=>{let n=e;for(let r of t.split("/")){n=vZ.join(n,r);let o=await sn(n);if(o===void 0)return;p(!o.isSymbolicLink(),`Refusing to ${i} through symbolic link ${n}.`)}};var YZ=require("crypto"),ee=require("fs/promises"),Ze=require("path");var nY=(e)=>{let t=typeof e.body==="string"?e.body:e.body===void 0?void 0:JSON.stringify(e.body);return t===void 0||t.length===0?void 0:t},fr=(e)=>{if(e instanceof te){let t=nY(e);return t===void 0?e.message:`${e.message}
141
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let g=EA.test(a)?a.replace(EA,"$1"):a;if(!g.match(/\S*Error: /)){for(let l of t){let I=l(g,e);if(I){r.push(I);break}}if(r.length>=JA)break}}return UA(r)}}class OA{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=Rt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ii(e,"DOMException")}isDOMError(e){return Ii(e,"DOMError")}}class ts{match(e){return gA(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 i=e.message;if(i.error&&typeof i.error.message=="string")return String(i.error.message);return String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class zA{constructor(){}match(e){return lA(e)&&e.error!=null}coerce(e,t){let i=t.apply(e.error);if(!i)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return i}}var nN=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class is{match(e){return typeof e=="string"}coerce(e,t){let[i,n]=this.getInfos(e);return{type:i??"Error",value:n??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,n=e.match(nN);if(n)t=n[1],i=n[2];return[t,i]}}var jA=["fatal","error","warning","log","info","debug"];function ns(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let n=i.length;n>0;n--){let r=i.slice(0,n).join(", ");if(!(r.length>t)){if(n===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class rs{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let i=this.getErrorPropertyFromObject(e);if(i)return t.apply(i);return{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 Mi(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")n+=` with message: '${e.message}'`;return n}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),i=ns(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return Rt(e)&&!oA(e)&&jA.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(FA(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class DA{match(e){return Mi(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${ns(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class os{match(e){return Oo(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class QA{match(e){return Ii(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Mi(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);if(Oo(i))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class _A{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Ar={MESSAGE:"$message",TIMESTAMP:"$timestamp"},rN=new Set([Ar.MESSAGE,Ar.TIMESTAMP]),ss={enabled:!0,max_bytes:32768};function eI(e){if(!e)return{...ss};return{enabled:e.enabled??ss.enabled,max_bytes:sN(e.max_bytes,ss.max_bytes)}}function oN(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,r)=>{if(rN.has(r))return t.push(r),n;return n[r]=e[r],n},{}),droppedKeys:t}}class KA{constructor(e){this._entries=[],this._totalBytes=0,this._config=eI(e)}setConfig(e){this._config=eI(e),this._trimToMaxBytes()}add(e){let t=aN(e);if(!t)return;let i=LA(t.json);if(i>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function sN(e,t){if(!cr(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function aN(e){let t;try{t=Li(e)}catch{return}try{let i=JSON.parse(t);if(!dr(i))return;let n=i,r=n[Ar.MESSAGE],o=n[Ar.TIMESTAMP];if(!Rt(r)||r.trim().length===0)return;if(!Rt(o)&&!cr(o))return;return{step:n,json:t}}catch{return}}function LA(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let n=0;n<t.length;n++)if(t[n]==="%")i+=1,n+=2;else i+=1;return i}class jt 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()}}class ci extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var qA=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function MA(e){if(e instanceof jt){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 gN(e){return typeof e=="object"&&(e instanceof jt||eZ(e))}function eZ(e){return e instanceof ci}function lN(e){if(e instanceof jt)return e.status===502||e.status===504;if(!(e instanceof ci))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function en(e){return typeof e=="object"&&e instanceof jt&&e.status===413}function Zr(e){if(e instanceof jt)return e.status===408||e.status===429||e.status>=500;return eZ(e)}function $A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var tI="default";class as{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new qo([new ts,new rs,new is,new os],ql())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Sl,this._events=new Ll,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=mA("[PostHog]",this.logMsgIfDebug.bind(this)),r)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=i,this.host=GA(n||"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??1000),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??3000,retryCheck:Zr},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||r,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!Yl()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(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(He.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(He.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(He.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};if(qA(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=lr(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(e,t,i){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,i)}captureStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",r,n)})}async captureStatelessImmediate(e,t,i,n){let r=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",r,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",r,n)})}async aliasStatelessImmediate(e,t,i,n){let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",r,n)}groupIdentifyStateless(e,t,i,n,r,o){this.wrap(()=>{let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,r,o){let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});await this.sendImmediate("capture",s,n)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,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(e,t={},i={},n={},r={},o=!1){await this._initPromise;let s=o?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,g={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)g.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)g.evaluation_contexts=this.evaluationContexts;let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(g)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:lN},this.featureFlagsRequestTimeoutMs).then((I)=>I.json()).then((I)=>({success:!0,response:Nl(I)})).catch((I)=>(this._events.emit("error",I),{success:!1,error:this.categorizeRequestError(I)}))}categorizeRequestError(e){if(e instanceof jt)return{type:"api_error",statusCode:e.status};if(e instanceof ci){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,r,o);if(s===void 0)return{response:void 0,requestId:void 0};let a=gr(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,r,o,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,r,o,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},r,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},r,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,r,o);if(!s)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}}async getFeatureFlagDetailsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s={geoip_disable:r??this.disableGeoip};if(o)s.flag_keys_to_evaluate=o;let a=await this.getFlags(e,t,i,n,s);if(!a.success)return;let g=a.response;if(g.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");if(g.quotaLimited?.includes("feature_flags"))return 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:g?.requestId,quotaLimited:g.quotaLimited};return g}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)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((r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);this._logger.error(s),this._events.emit("error",Error(o));return}return r.json()}).catch((r)=>{this._logger.error("Surveys API could not be loaded",r),this._events.emit("error",r)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(He.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(He.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(He.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tI}persistedQueueKeyForRoute(e){return He.Queue}getActiveQueueRoutes(){return[tI]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let r=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),o=this.getPersistedProperty(r)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:n}),this.setPersistedProperty(r,o),this._events.emit(e,n),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(r){this._events.emit("error",r)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=$A(r.properties)?r.properties:void 0;if(i!==void 0&&o?.$lib===void 0)o={...o||{},$lib:i};if(n!==void 0&&o?.$lib_version===void 0)o={...o||{},$lib_version:n};if(o)r.properties=o;return r.uuid=_o(r.uuid,ve),r}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:Ol(),uuid:_o(t?.uuid,ve)};if(t?.disableGeoip??this.disableGeoip){if(!$A(i.properties))i.properties={};i.properties.$geoip_disable=!0}if(i.distinctId)i.distinct_id=i.distinctId,delete i.distinctId;return i}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await MA(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((r)=>!!r),n=0;while(!0){let r=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(r.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${r.length} pending promise(s) before flushing`);await Promise.all(r.map((o)=>o.catch(()=>{}))),n++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,n])}).then(()=>zl([t])).then(()=>{if(this.pendingFlushPromise===n)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=n,this.flushPromise=n,this.flushPromises.add(n),this.addPendingPromise(n),zl([n]).then(()=>{if(this.flushPromises.delete(n),this.pendingFlushPromise===n)this.pendingFlushPromise=null;if(this.flushPromise===n)this.flushPromise=null}),n}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,i=tI){let n={api_key:this.apiKey,batch:e,sent_at:Ol()};if(this.historicalMigration)n.historical_migration=!0;let r=Li(n),o=`${this.host}/batch/`,s=this.disableCompression?null:await gi(r,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await(await this.fetchWithRetry(o,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((n)=>this.getRouteQueue(n).length>0))return;let t=[],i;for(let n of e)try{await this._flushRoute(n,t)}catch(r){if(i===void 0)i=r}if(i!==void 0)throw i;this._events.emit("flush",t)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(i)||[];if(!n.length)return;let r=n.length,o=0;while(n.length>0&&o<r){let s=n.slice(0,this.maxBatchSize),a=s.map((I)=>I.message===void 0?I.message:this.normalizeMessage(I.message)),g=async()=>{let d=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,d),n=d,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:(I)=>{if(en(I))return!1;return Zr(I)}};try{await this.sendBatch(a,l,e)}catch(I){if(en(I)&&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}if(!(I instanceof ci))await g();throw this._events.emit("error",I),I}await g(),t.push(...a),o+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(en(o))return!1;return Zr(o)}}),{kind:"ok"}}catch(o){if(en(o))return{kind:"too-large"};if(o instanceof ci)return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(en(o))return!1;return Zr(o)}}),{kind:"ok"}}catch(o){if(en(o))return{kind:"too-large"};if(Zr(o))return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async fetchWithRetry(e,t,i,n){let r=t.body?t.body:"",o=-1;try{o=r instanceof Blob?r.size:Buffer.byteLength(r,RA)}catch{if(r instanceof Blob)o=r.size;else o=new TextEncoder().encode(r).length}return await wA(async()=>{let s=new AbortController,a=n??this.requestTimeout,g=de(()=>s.abort(),a),l=null;try{l=await this.fetch(e,{signal:s.signal,...t})}catch(d){throw new ci(d)}finally{clearTimeout(g)}if(t.mode!=="no-cors"&&(l.status<200||l.status>=400))throw new jt(l,o);return l},{...this._retryOptions,...i})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let i=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((s)=>this.getRouteQueue(s).length>0))break;let o=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(r){if(!gN(r))throw r;await MA(r)}},n;try{return await Promise.race([new Promise((r,o)=>{n=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(n)}}async shutdown(e=30000){if(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");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var nZ=require("fs"),rZ=require("readline"),gs=new Ge.ReduceableCache(25),oZ=new Ge.ReduceableCache(20),iI=7,uN=1000,mN=1e4;async function sZ(e){let t={};for(let r=e.length-1;r>=0;r--){let o=e[r],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||bN(s)||hN(o))continue;if(!t[s])t[s]=[];t[s].push(o.lineno)}let i=Object.keys(t);if(i.length==0)return e;let n=[];for(let r of i){if(oZ.get(r))continue;let o=t[r];if(!o)continue;o.sort((g,l)=>g-l);let s=fN(o);if(s.every((g)=>WN(r,g)))continue;let a=yN(gs,r,{});n.push(pN(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)AN(e,gs);return gs.reduce(),e}function pN(e,t,i){return new Promise((n)=>{let r=nZ.createReadStream(e),o=rZ.createInterface({input:r});function s(){r.destroy(),n()}let a=0,g=0,l=t[g];if(l===void 0)return void s();let I=l[0],d=l[1];function C(){oZ.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",C),o.on("error",C),o.on("close",s),o.on("line",(A)=>{if(a++,a<I)return;if(i[a]=VN(A,0),a>=d){if(g===t.length-1){o.close(),o.removeAllListeners();return}g++;let c=t[g];if(c===void 0){o.close(),o.removeAllListeners();return}I=c[0],d=c[1]}})})}function AN(e,t){for(let i of e)if(i.filename&&i.context_line===void 0&&typeof i.lineno=="number"){let n=t.get(i.filename);if(n===void 0)continue;ZN(i.lineno,i,n)}}function ZN(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=aZ(e);r<e;r++){let o=i[r];if(o===void 0)return void tZ(t);t.pre_context.push(o)}if(i[e]===void 0)return void tZ(t);t.context_line=i[e];let n=gZ(e);t.post_context=[];for(let r=e+1;r<=n;r++){let o=i[r];if(o===void 0)break;t.post_context.push(o)}}function tZ(e){delete e.pre_context,delete e.context_line,delete e.post_context}function bN(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function hN(e){if(e.lineno!==void 0&&e.lineno>mN)return!0;if(e.colno!==void 0&&e.colno>uN)return!0;return!1}function WN(e,t){let i=gs.get(e);if(i===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(i[n]===void 0)return!1;return!0}function fN(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=iZ(i),r=[];while(!0){if(t===e.length-1){r.push(n);break}let o=e[t+1];if(typeof o!="number")break;if(o<=n[1])n[1]=o+iI;else r.push(n),n=iZ(o);t++}return r}function iZ(e){return[aZ(e),gZ(e)]}function aZ(e){return Math.max(1,e-iI)}function gZ(e){return e+iI}function yN(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function VN(e,t){let i=e,n=i.length;if(n<=150)return i;if(t>n)t=n;let r=Math.max(t-60,0);if(r<5)r=0;let o=Math.min(r+140,n);if(o>n-5)o=n;if(o===n)r=Math.max(o-140,0);if(i=i.slice(r,o),r>0)i=`...${i}`;if(o<n)i+="...";return i}var tn=require("path");function lZ(e=process.cwd()){let t=tn.sep==="\\",i=(r)=>t?r.replace(/\\/g,"/"):r,n=i(e);return async(r)=>{for(let o of r)if(!(!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:"))){if(tn.isAbsolute(o.filename))o.filename=i(tn.relative(n,i(o.filename)))}return r}}var IZ="5.46.1";var Gt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Ci{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let i=this._flags[t];if(i)e[t]=i}return this._cloneWith(e)}only(e){let t={},i=[];for(let n of e){let r=this._flags[n];if(r)t[n]=r;else i.push(n)}if(i.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,n]of Object.entries(this._flags)){let r=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${i}`]=r,n.enabled)t.push(i)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Ci({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],i=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,n={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)n.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)n.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let r=[];if(this._errorsWhileComputing)r.push(Gt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(Gt.QUOTA_LIMITED);if(t===void 0)r.push(Gt.FLAG_MISSING);if(r.length>0)n.$feature_flag_error=r.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function dZ(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let i=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map((r)=>r.toString(16).padStart(2,"0")).join("")}var BN=60000,RN=1152921504606847000,GN=["is_not","is_set"];class nn extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,nn.prototype)}}function mZ(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class J extends Error{constructor(e){super(e);mZ(this,J)}}class ct extends Error{constructor(e){super(e);mZ(this,ct)}}class nI{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:r,customHeaders:o,...s}){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=n,this.projectApiKey=i,this.host=r,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=o,this.onLoad=s.onLoad,this.onMinimalFlagCalledEvents=s.onMinimalFlagCalledEvents,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},i={},n={},r={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:r}}async getFeatureFlag(e,t,i={},n={},r={}){await this.loadFeatureFlags();let o,s;if(!this.loadedSuccessfullyOnce)return o;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,r);try{o=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(g){if(g instanceof ct||g instanceof J)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${e}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${g}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},r=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async(a)=>{try{let{value:g,payload:l}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=g,l)n[a.key]=l}catch(g){if(g instanceof ct||g instanceof J)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${a.key}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${g}`));r=!0}})),{response:i,payloads:n,fallbackToFlags:r}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:r=!1}=i;if(!r)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:r,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new J("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let g=this.groupTypeMapping[String(a)];if(!g)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new J("Flag has unknown group type index");if(!(g in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(r?.$device_id===void 0||r?.$device_id===null||r?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=o[g];return await this.matchFeatureFlagProperties(e,n[g],l,t)}{let g=this.getBucketingValueForFlag(e,i,r);if(g===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new J(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,g,r,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=i?.$device_id;if(n==null||n==="")return;return n}return t}getFeatureFlagPayload(e,t){let i=null;if(t!==!1&&t!=null){if(typeof t=="boolean")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(i!=null){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:n}=i,r=e.key;if(!this.featureFlagsByKey)throw new J("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new J(`Flag dependency property for '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new J(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new J(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let l=this.featureFlagsByKey[a];if(l)if(l.active)try{let I=await this.computeFlagValueLocally(l,i);n[a]=I}catch(I){throw new J(`Error evaluating flag dependency '${a}' for flag '${r}': ${I}`)}else n[a]=!1;else throw new J(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new J(`Dependency '${a}' could not be evaluated`)}let s=n[r];return this.flagEvaluatesToExpectedValue(e.value,s)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,i,n){let r=e.filters||{},o=r.groups||[],s=r.aggregation_group_type_index,a=r.early_exit??!1,{groups:g,groupProperties:l}=n,I=!1,d;for(let C of o)try{let A=C.aggregation_group_type_index!==void 0?C.aggregation_group_type_index:s,c=i,u=t;if(A!==s){if(A!=null){let W=this.groupTypeMapping[String(A)];if(!W||!(W in g)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${A} not available`));continue}if(!(W in l)){I=!0;continue}c=l[W],u=g[W]}}let Z=await this.isConditionMatch(e,u,C,c,n);if(Z==="match"){let W=C.variant,m=r.multivariate?.variants||[];d=W&&m.some((b)=>b.key===W)?W:await this.getMatchingVariant(e,u)||!0;break}if(a&&Z==="out_of_rollout_bound")return!1}catch(A){if(A instanceof ct)throw A;if(A instanceof J)I=!0;else throw A}if(d!==void 0)return d;if(I)throw new J("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,n,r){let o=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let g=a.type,l=!1;if(g==="cohort"){let I=await AZ(a,n,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,n,r));l=a.operator==="not_in"?!I:I}else l=g==="flag"?await this.evaluateFlagDependency(a,n,r):pZ(a,n,s);if(!l)return"no_match"}if(o==null)return"match"}if(o!=null&&await cZ(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await cZ(e.key,t,"variant"),n=this.variantLookupTable(e).find((r)=>i>=r.valueMin&&i<r.valueMax);if(n)return n.key}variantLookupTable(e){let t=[],i=0,n=0;return((e.filters||{}).multivariate?.variants||[]).forEach((s)=>{n=i+s.rollout_percentage/100,t.push({valueMin:i,valueMax:n,key:s.key}),i=n}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,i)=>(t[i.key]=i,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((i)=>i.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.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(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(BN,this.pollingInterval*2**this.backOffCount)}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(){if(this.poller)clearTimeout(this.poller),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(i){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(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.clearBackoff();return;case 401:throw this.beginBackoff(),new nn(`Your project key or secret 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={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new nn(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new nn(`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 t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:i.minimal_flag_called_events===!0};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(r){this.onError?.(Error(`Failed to store in cache: ${r}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof nn)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)i["If-None-Match"]=t;return{method:e,headers:i}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.timeout),t.signal=n.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(i)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((i,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function cZ(e,t,i=""){let n=await dZ(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/RN}function pZ(e,t,i){let{key:n,value:r}=e,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new J(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!GN.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(l,I){if(Array.isArray(l))return l.map((d)=>String(d).toLowerCase()).includes(String(I).toLowerCase());return String(l).toLowerCase()===String(I).toLowerCase()}function g(l,I,d){if(d==="gt")return l>I;if(d==="gte")return l>=I;if(d==="lt")return l<I;if(d==="lte")return l<=I;throw Error(`Invalid operator: ${d}`)}switch(o){case"exact":return a(r,s);case"is_not":return!a(r,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(r).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(r).toLowerCase());case"regex":return CZ(String(r))&&String(s).match(String(r))!==null;case"not_regex":return CZ(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof r=="number"?r:parseFloat(String(r)),I;if(I=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(l)&&Number.isFinite(I))return g(I,l,o);return g(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new J("Date operations cannot be performed on boolean values");let l=kN(String(r));if(l==null)l=uZ(r);if(l==null)throw new J(`Invalid date: ${r}`);let I=uZ(s);if(["is_date_before"].includes(o))return I<l;return I>l}case"semver_eq":return Je(ae(String(s)),ae(String(r)))===0;case"semver_neq":return Je(ae(String(s)),ae(String(r)))!==0;case"semver_gt":return Je(ae(String(s)),ae(String(r)))>0;case"semver_gte":return Je(ae(String(s)),ae(String(r)))>=0;case"semver_lt":return Je(ae(String(s)),ae(String(r)))<0;case"semver_lte":return Je(ae(String(s)),ae(String(r)))<=0;case"semver_tilde":{let l=ae(String(s)),{lower:I,upper:d}=FN(String(r));return Je(l,I)>=0&&Je(l,d)<0}case"semver_caret":{let l=ae(String(s)),{lower:I,upper:d}=HN(String(r));return Je(l,I)>=0&&Je(l,d)<0}case"semver_wildcard":{let l=ae(String(s)),{lower:I,upper:d}=vN(String(r));return Je(l,I)>=0&&Je(l,d)<0}default:throw new J(`Unknown operator: ${o}`)}}function wN(e,t){if(!(e in t))throw new ct(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function AZ(e,t,i,n=!1,r){let o=String(e.value);wN(o,i);let s=i[o];return ZZ(s,t,i,n,r)}async function ZZ(e,t,i,n=!1,r){if(!e)return!0;let{type:o,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let g of s)try{let l=await ZZ(g,t,i,n,r);if(o==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof ct)throw l;if(l instanceof J){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new J("Can't match cohort without a given cohort property value");return o==="AND"}for(let g of s)try{let l;if(g.type==="cohort")l=await AZ(g,t,i,n,r);else if(g.type==="flag"){if(!r)throw new J(`Flag dependency '${g.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await r(g)}else l=pZ(g,t);let I=g.negation||!1;if(o==="AND"){if(!l&&!I)return!1;if(l&&I)return!1}else{if(l&&!I)return!0;if(!l&&I)return!0}}catch(l){if(l instanceof ct)throw l;if(l instanceof J){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new J("can't match cohort without a given cohort property value");return o==="AND"}function CZ(e){try{return new RegExp(e),!0}catch(t){return!1}}function bZ(e,t){if(!/^\d+$/.test(e))throw new J(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new J(`Invalid semver: ${t}`);return parseInt(e,10)}function ae(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new J(`Invalid semver: ${e}`);let n=i.split("."),r=(g)=>{if(g===void 0||g==="")return 0;return bZ(g,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function Je(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}function FN(e){let t=ae(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function HN(e){let t=ae(e),[i,n,r]=t,o=[i,n,r],s;return s=i>0?[i+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:o,upper:s}}function vN(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new J(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(g)=>{try{return bZ(g,e)}catch{throw new J(`Invalid wildcard semver: ${e}`)}},o=r(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let g=r(n[1]);s=[o,g,0],a=[o,g+1,0]}return{lower:s,upper:a}}function uZ(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 J(`${e} is in an invalid date format`)}throw new J(`The date provided ${e} must be a string, number, or date object`)}function kN(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,i=e.match(t),n=new Date(new Date().toISOString());if(!i)return null;{if(!i.groups)return null;let r=parseInt(i.groups.number);if(r>=1e4)return null;let o=i.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-r);else if(o=="d")n.setUTCDate(n.getUTCDate()-r);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*r);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-r);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-r)}return n}}function PN(e,t){let i=!1;return Object.assign((n)=>{let o=global.process.listeners("uncaughtException").filter((s)=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!i&&o)i=!0,t(n)},{_posthogErrorHandler:!0})}function hZ(e,t){globalThis.process?.on("uncaughtException",PN(e,t))}function WZ(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var NN=2000;class Ct{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Xl({...dA(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return dr(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,i,n,r){let o={...r},s=e.buildFromUnknown(t,i);return s.$exception_list=await e.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())hZ(this.onException.bind(this),this.onFatalError.bind(this)),WZ(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ct.isPreviouslyCapturedError(e)){let i=await Ct.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(r))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:r});return this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(NN),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class rI{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function YN(e){return e==="v0"||e==="v1"}function fZ(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return YN(e)?e:"v0"}var br="analytics",hr="ai";function yZ(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class rn extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super(rn.buildMessage(e,t,i,n)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=n}static buildMessage(e,t,i,n){let r=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;if(n instanceof Error)r+=` (${n.message})`;return r}}function oI(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function XN(e){return typeof e=="string"?e:void 0}var SN=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:oI},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:oI},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:oI},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:XN}],xN=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function EN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function JN(e){if(typeof e=="string"){let i=new Date(e);return Number.isNaN(i.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function VZ(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function UN(e){let i={...EN(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of SN)if(o in i){let g=a(i[o]);if(g!==void 0)n[s]=g;delete i[o]}let r={};for(let{property:o,field:s}of xN)if(o in i){let a=i[o];if(typeof a=="string")r[s]=a;delete i[o]}return delete i.$lib,delete i.$lib_version,VZ(i,"$set",e.$set),VZ(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:JN(e.timestamp),...r,options:n,properties:i}}function BZ(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(UN)};if(i)n.historical_migration=!0;return n}var TN="/i/v1/analytics/events",ON=30000,zN=new Set([408,500,502,503,504]);class sI{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??ON,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>de(n,i))),this.generateRequestId=t.generateRequestId??ve,this.compress=t.compress??gi}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=BZ(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${TN}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let g=1;g<=a;g++){let l=g===a,I=Li({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),d;try{d=await this.sendOnce(r,I,g,t)}catch(Z){if(l)return this.surfaceBatchFailure(t,o,s,Z);await this.sleep(this.backoffDelay(g));continue}let{status:C}=d;if(C<200||C>=300){if(!l&&zN.has(C)){let W=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(g,W));continue}let Z=await this.buildHttpError(d,C);return this.surfaceBatchFailure(t,o,s,Z)}let A;try{A=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${C} response body`))}let c=this.classify(s,A,o);if(c.length===0)return this.surfacePartialDrops(t,o);if(l)return void this.onError(new rn({requestId:t,drops:o,retryExhausted:c.map((Z)=>Z.uuid)}));s=c;let u=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(g,u))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let g=await this.compress(t,this.config.isDebug);if(g!==null)o=g,r["Content-Encoding"]="gzip"}let s=new AbortController,a=de(()=>s.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:r,body:o,signal:s.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)n["User-Agent"]=this.config.userAgent;return n}classify(e,t,i){let n=t.results??{},r=[];for(let o of e){let s=n[o.uuid];if(s){if(s.result==="drop")i.push({uuid:o.uuid,details:s.details??void 0});else if(s.result==="retry")r.push(o)}}return r}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return i;return Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let o=parseInt(i,10);return Number.isFinite(o)&&o>0?1000*o:void 0}let n=Date.parse(i);if(Number.isNaN(n))return;let r=n-this.now();return r>0?r:void 0}async parseResponse(e){let t=await e.text(),i=JSON.parse(t);if(typeof i!="object"||i===null||Array.isArray(i))throw Error("unexpected response shape");let n=i.results;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw Error("unexpected results shape");return{results:n??{}}}async buildHttpError(e,t){let i="";try{i=(await e.text()).slice(0,512)}catch{}let n=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${n}`)}surfaceBatchFailure(e,t,i,n){this.onError(new rn({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new rn({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var jN=100,RZ=30000,DN=50000,QN=50,_N=500,KN="https://us.i.posthog.com",GZ=new Set;function ls(e,t){if(GZ.has(e))return;GZ.add(e),console.warn(`[PostHog] ${t}`)}function LN(e){return typeof e=="string"?e.trim():""}function MN(e){return(typeof e=="string"?e.trim():"")||void 0}function $N(e){return(typeof e=="string"?e.trim():"")||KN}function qN(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function eY(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let i=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(i.length>0)t.$active_feature_flags=i;return t}class aI extends as{constructor(e,t={}){let i=LN(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:$N(t.host),personalApiKey:MN(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new rI,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=fZ(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,jN):RZ,typeof n.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(n.waitUntilDebounceMs,0);if(typeof n.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(n.waitUntilMaxWaitMs,0);if(!this.disabled&&n.personalApiKey){if(n.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.');if(n.enableLocalEvaluation!==!1)this.featureFlagsPoller=new nI({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:i,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(o)=>{this._events.emit("error",o)},onLoad:(o)=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:(o)=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new Ct(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||DN}enqueue(e,t,i){super.enqueue(e,t,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,s=new Promise((a)=>{o=a});try{e(s)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??_N,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??QN;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},r)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}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)}getQueueRouteKey(e){return this.captureMode==="v1"&&yZ(e)?hr:br}persistedQueueKeyForRoute(e){return e===hr?He.AiQueue:He.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[br,hr]:[br]}async sendBatch(e,t,i=br){if(this.captureMode!=="v1"||i===hr)return super.sendBatch(e,t,i);let n=e.filter((r)=>r!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new sI({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return IZ}get metrics(){if(!this._metrics)this._metrics=new Lo(this,Ko(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(i)}_sendPreparedEvent(e,t,i,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:r,event:o,properties:s,options:a})=>{let g={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,l,g):this.enqueue(e,l,g)}).catch((r)=>{if(r)console.error(r)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(Object.keys(t).length===0&&Object.keys(i).length===0)return;let n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(i).length>0)n.$set_once=i;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let i=qN(t);if(i.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=RZ){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let i=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",(r)=>{clearTimeout(i),n(),t(r>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,i={},n){if(this.disabled)return void this._logger.warn("The client is disabled");let r=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let y=this._flagOverrides[e];if(y===void 0)return;let B=this._payloadOverrides?.[e];return{key:e,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:B}}let{groups:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=i,I=this.addLocalPersonAndGroupProperties(t,o,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C,A=!1,c,u,Z,W,m,b,h;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let y=this.featureFlagsPoller?.featureFlagsByKey[e];if(y)try{let B=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(y,d,{matchValue:n});if(B){A=!0;let F=B.value;W=y.id,b="Evaluated locally",h=y.has_experiment,C={key:e,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:B.payload??void 0}}}catch(B){if(B instanceof ct||B instanceof J)this._logger?.info(`${B.name} when computing flag locally: ${e}: ${B.message}`);else throw B}}if(!A&&!a){let y=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,g,l,s,[e]);if(y===void 0)Z=Gt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=y.minimalFlagCalledEvents===!0,c=y.requestId,u=y.evaluatedAt;let B=[];if(y.errorsWhileComputingFlags)B.push(Gt.ERRORS_WHILE_COMPUTING);if(y.quotaLimited?.includes("feature_flags"))B.push(Gt.QUOTA_LIMITED);let F=y.flags[e];if(F===void 0)B.push(Gt.FLAG_MISSING);else{W=F.metadata?.id,m=F.metadata?.version,b=F.reason?.description??F.reason?.code,h=F.metadata?.has_experiment;let w;if(F.metadata?.payload!==void 0)try{w=JSON.parse(F.metadata.payload)}catch{w=F.metadata.payload}C={key:e,enabled:F.enabled,variant:F.variant,payload:w}}if(B.length>0)Z=B.join(",")}}if(r){let y=C===void 0?void 0:C.enabled===!1?!1:C.variant??!0,B={$feature_flag:e,$feature_flag_response:y,$feature_flag_id:W,$feature_flag_version:m,$feature_flag_reason:b,locally_evaluated:A,[`$feature/${e}`]:y,$feature_flag_request_id:c,$feature_flag_evaluated_at:A?Date.now():u};if(h!==void 0)B.$feature_flag_has_experiment=h;if(A&&this.featureFlagsPoller){let F=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(F!==void 0)B.$feature_flag_definitions_loaded_at=F}if(Z)B.$feature_flag_error=Z;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:y,groups:o,disableGeoip:s,properties:B})}if(C!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)C={...C,payload:this._payloadOverrides[e]};return C}async getFeatureFlag(e,t,i){ls("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return n.variant??!0}async getFeatureFlagPayload(e,t,i,n){if(ls("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},i);if(r===void 0)return;return r.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:n,options:r}=this._resolveDistinctId(t,i);if(!n)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,n,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");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 i=await t.json();if(typeof i=="string")try{return JSON.parse(i)}catch(n){}return i}async isFeatureEnabled(e,t,i){ls("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return!!(n.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(i,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},I=this.addLocalPersonAndGroupProperties(i,r,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,s),A={},c={},u=!0;if(C)A=C.response,c=C.payloads,u=C.fallbackToFlags;if(u&&!a){let Z=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,g,l,o,s);A={...A,...Z.flags||{}},c={...c,...Z.payloads||{}}}if(this._flagOverrides!==void 0)A={...A,...this._flagOverrides};if(this._payloadOverrides!==void 0)c={...c,...this._payloadOverrides};return{featureFlags:A,featureFlagPayloads:c}}async evaluateFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},I=this.addLocalPersonAndGroupProperties(i,r,g,l);g=I.allPersonProperties,l=I.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C={},A,c,u=!1,Z=!1,W=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,s),m=new Set;if(W)for(let[h,f]of Object.entries(W.response)){let y=this.featureFlagsPoller?.featureFlagsByKey[h];C[h]={key:h,enabled:f!==!1,variant:typeof f=="string"?f:void 0,payload:W.payloads[h],id:y?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:y?.has_experiment},m.add(h)}if((W?W.fallbackToFlags:!0)&&!a){let h=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,g,l,o,s);if(h){this._minimalFlagCalledEvents=h.minimalFlagCalledEvents===!0,A=h.requestId,c=h.evaluatedAt,u=Boolean(h.errorsWhileComputingFlags),Z=Array.isArray(h.quotaLimited)&&h.quotaLimited.includes("feature_flags");for(let[f,y]of Object.entries(h.flags)){if(m.has(f))continue;let B;if(y.metadata?.payload!==void 0)try{B=JSON.parse(y.metadata.payload)}catch{B=y.metadata.payload}C[f]={key:f,enabled:y.enabled,variant:y.variant,payload:B,id:y.metadata?.id,version:y.metadata?.version,reason:y.reason?.description??y.reason?.code,locallyEvaluated:!1,hasExperiment:y.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[h,f]of Object.entries(this._flagOverrides)){if(f===void 0){delete C[h];continue}let y=C[h];C[h]={key:h,enabled:f!==!1,variant:typeof f=="string"?f:void 0,payload:y?.payload,id:y?.id,version:y?.version,reason:y?.reason,locallyEvaluated:y?.locallyEvaluated??!1,hasExperiment:y?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[h,f]of Object.entries(this._payloadOverrides)){let y=C[h];if(y)C[h]={...y,payload:f}}return new Ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:C,requestId:A,evaluatedAt:c,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:u,quotaLimited:Z})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:n,groups:r,disableGeoip:o,properties:s}=e,a=r&&Object.keys(r).length>0?`_${JSON.stringify(Object.entries(r).sort(([l],[I])=>l<I?-1:l>I?1:0))}`:"",g=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(g))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(g);else this.distinctIdHasSentFlagCalls[t]=new Set([g]);this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:r,disableGeoip:o})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(i)=>Object.fromEntries(i.map((n)=>[n,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let i=t.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in t){let i=t.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(e,t,i){if(!this.context)return t();return this.context.run(e,t,i)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),i=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((n)=>de(n,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/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 r=new AbortController;n=de(()=>{r.abort()},this.options.requestTimeout),i.signal=r.signal}try{return await this.fetch(t,i)}catch(r){this._events.emit("error",r);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[r,o]of Object.entries(e))if(IA(o)&&t&&r in t){let s={};for(let[a,g]of Object.entries(o))s[String(a)]=String(g);n[String(r)]=s}else i[String(r)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(e,t,i,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let r=n?.personProperties||{},o=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let g={};for(let[l,I]of Object.entries(t||{}))g[l]=String(I);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[l,I]of Object.entries(t||{}))g[l]=String(I);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,r,o,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let r={...i||{}},o={};if(t)for(let s of Object.keys(t))o[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:r,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,n){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,i,n,r){if(!Ct.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(Ct.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,i).then((s)=>this._capturePreparedEvent({...s,uuid:n,flags:r},!1)))}}async captureExceptionImmediate(e,t,i,n){if(!Ct.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(Ct.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((o)=>this.captureImmediate({...o,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:r,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:I}=e,d=this.context?.get(),C=t.includeContextProperties??!0,A=i||d?.distinctId,c=C?{...this.props,...d?.properties||{},...r||{}}:{...r||{}};if(!A)A=ve(),c.$process_person_profile=!1;if(C&&d?.sessionId&&!c.$session_id)c.$session_id=d.sessionId;let u=this._shouldSendMinimalFlagCalledEvent(n,c)?lr(c):c,Z=this._runBeforeSend({distinctId:A,event:n,properties:u,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:I});if(!Z)return Promise.reject(null);let W=await Promise.resolve().then(async()=>{if(s){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return s._getEventProperties()}if(a){ls("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let m=typeof a=="object"?a:void 0,b=await this.getFeatureFlagsForEvent(Z.distinctId,o,l,m);return eY(b)}return{}}).catch(()=>({})).then((m)=>{let b=Z.groups||o;return{...m,...Z.properties||{},...b!==void 0&&Object.keys(b).length>0?{$groups:b}:{}}});if(Z.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof W.$raw_user_agent=="string"){if(nA(W.$raw_user_agent,this.options.custom_blocked_useragents||[]))Z.event="$bot_pageview",W.$browser_type="bot"}return{distinctId:Z.distinctId,event:Z.event,properties:W,options:{timestamp:Z.timestamp,disableGeoip:Z.disableGeoip,uuid:Z.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],n=e;for(let r of i){if(n=r(n),!n)return this._logger.info(`Event '${e.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 wZ=require("async_hooks");class gI{constructor(){this.storage=new wZ.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}function tY(e,{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:o=!0}={}){return(s)=>{if(!(r==="*"||r.includes(s.level)))return s;if(!s.tags)s.tags={};let g=s.tags[FZ.POSTHOG_ID_TAG];if(g===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",I=new URL(`/project/${e.apiKey}/person/${g}`,l).toString();s.tags["PostHog Person URL"]=I;let d=s.exception?.values||[],C=d.map((c)=>({...c,stacktrace:c.stacktrace?{...c.stacktrace,type:"raw",frames:(c.stacktrace.frames||[]).map((u)=>({...u,platform:"node:javascript"}))}:void 0})),A={$exception_message:d[0]?.value||s.message,$exception_type:d[0]?.type,$exception_level:s.level,$exception_list:C,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:d[0]?.value||s.message,$sentry_exception_type:d[0]?.type,$sentry_tags:s.tags};if(t&&i)A.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(o)e.capture({event:"$exception",distinctId:g,properties:A});return s}}class FZ{static#i=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,n,r){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(o,s){let a=s()?.getClient()?.getDsn()?.projectId;o(tY(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class lI extends aI{getLibraryId(){return"posthog-node"}initializeContext(){return new gI}createErrorPropertiesBuilder(){return new Ge.ErrorPropertiesBuilder([new Ge.EventCoercer,new Ge.ErrorCoercer,new Ge.ObjectCoercer,new Ge.StringCoercer,new Ge.PrimitiveCoercer],Ge.createStackParser("node:javascript",Ge.nodeStackLineParser),[eA(),sZ,lZ()])}}var Ue=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},on=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var ie=require("fs/promises"),ce=require("path");var Is={name:"@toloka-platform/sdk",version:"0.2.0-preview.2",private:!1,description:"Beta. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./testing":"./src/testing/index.ts","./checks":"./src/checks/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"latest"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts","sync-task-ui-declarations":"bun ./scripts/sync-task-ui-declarations.ts",test:"vitest run","test:browser":"vitest run --config vitest.browser.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.2",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","jsonpath-rfc9535":"1.3.0","oxc-parser":"0.138.0","posthog-node":"5.46.1","typescript-api":"npm:typescript@6.0.3"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",playwright:"1.56.1",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},peerDependencies:{playwright:">=1.56.1 <2",vitest:">=4.1.0 <5"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:"1.4.0"}};var HZ=require("fs/promises"),vZ=require("path"),ds=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),cs=(e)=>ds(e,"ENOENT"),sn=async(e)=>{try{return await HZ.lstat(e)}catch(t){if(cs(t))return;throw t}},Wr=async(e,t,i="write")=>{let n=e;for(let r of t.split("/")){n=vZ.join(n,r);let o=await sn(n);if(o===void 0)return;p(!o.isSymbolicLink(),`Refusing to ${i} through symbolic link ${n}.`)}};var YZ=require("crypto"),ee=require("fs/promises"),Ze=require("path");var nY=(e)=>{let t=typeof e.body==="string"?e.body:e.body===void 0?void 0:JSON.stringify(e.body);return t===void 0||t.length===0?void 0:t},fr=(e)=>{if(e instanceof te){let t=nY(e);return t===void 0?e.message:`${e.message}
142
142
  ${t}`}return e instanceof Error?e.message:String(e)};var Cs="catalog.json",gn=".agents/skills",an="SKILL.md",dI="skills",kZ=500,PZ=1048576,XZ=64,rY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,oY=/^[a-f0-9]{64}$/u,SZ=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),NZ=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),II=(e)=>typeof e==="string"&&e.trim().length>0,sY=(e)=>typeof e==="string"&&e.length<=XZ&&rY.test(e),aY=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),gY=(e,t)=>{p(SZ(e),t("every skill must be an object."));let{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}=e;return p(sY(i),t(`skill id ${JSON.stringify(i)} must be at most ${XZ} lowercase letters, digits, and single hyphens.`)),p(II(n),t(`skill ${i} needs a name.`)),p(II(r),t(`skill ${i} needs a description.`)),p(NZ(o),t(`skill ${i} tags must be strings.`)),p(II(s),t(`skill ${i} needs a version.`)),p(typeof a==="string"&&oY.test(a),t(`skill ${i} digest must be the sha256 hex digest of its files.`)),p(NZ(g)&&g.includes(an),t(`skill ${i} files must include ${an}.`)),p(g.every(aY),t(`skill ${i} files must be relative paths inside its directory.`)),p(new Set(g).size===g.length,t(`skill ${i} lists a file more than once.`)),{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}},lY=(e,t)=>{try{return JSON.parse(e)}catch(i){throw Error(`Invalid skill catalog ${t}: ${fr(i)}`)}},IY=async(e)=>{try{return(await ee.stat(e)).isFile()}catch(t){if(ds(t,"ENOENT","ENOTDIR"))return!1;throw t}},cI=async(e)=>{let t=Ze.join(e,dI);if(await IY(Ze.join(t,Cs)))return t;let i=Ze.dirname(e);return i===e?void 0:cI(i)};async function dY(e=process.argv[1]){let t=e===void 0?void 0:await ee.realpath(e),i=t===void 0?void 0:await cI(Ze.dirname(t));if(i!==void 0)return i;let n=await cI(process.cwd()),r=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return p(n!==void 0,`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${dI}/${Cs} in a directory above its runtime entry, but ${r}, and no ${dI}/${Cs} exists above ${process.cwd()} either. Reinstall @toloka-platform/sdk.`),n}var CI=async()=>cY(await dY());async function cY(e){let t=Ze.join(e,Cs),i=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:n}=await ee.stat(t);p(n<=PZ,i(`the manifest is ${n} bytes; the limit is ${PZ} bytes.`));let r=lY(await ee.readFile(t,"utf8"),t);p(SZ(r)&&Array.isArray(r.skills),i("expected an object with a skills array.")),p(r.skills.length<=kZ,i(`${r.skills.length} skills exceed the limit of ${kZ}.`));let o=r.skills.map((a)=>gY(a,i)),s=new Set;for(let a of o)p(!s.has(a.id),i(`skill id ${a.id} appears more than once.`)),s.add(a.id);return{root:e,manifestPath:t,skills:o}}async function xZ(e,t){let i=YZ.createHash("sha256");for(let n of t.toSorted())i.update(n),i.update("\x00"),i.update(await ee.readFile(Ze.join(e,n))),i.update("\x00");return i.digest("hex")}var CY=(e,t)=>{let i=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);if(i.length===0)return[];return e.map((n,r)=>{let o=[n.id,n.name,n.description,...n.tags].join(`
143
143
  `).toLowerCase();return{skill:n,index:r,score:i.filter((s)=>o.includes(s)).length}}).filter(({score:n})=>n>0).toSorted((n,r)=>r.score-n.score||n.index-r.index).map(({skill:n})=>n)};async function uY(e,t){let i=Ze.join(e,gn,t.id);if(await sn(i)===void 0)return"not-installed";try{return await xZ(i,t.files)===t.digest?"current":"stale"}catch(n){if(ds(n,"ENOENT","ENOTDIR"))return"stale";throw n}}var EZ=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(i)=>({...i,status:await uY(e,i)}))),mY=async(e,t,i,n)=>{await e(i,n);try{await e(t,i)}catch(r){try{await e(n,i)}catch(o){throw Error(`Failed to replace ${i}; the previous version is preserved at ${n}. ${fr(o)}`,{cause:r})}throw r}await ee.rm(n,{recursive:!0,force:!0})};async function pY({catalog:e,sourceRoot:t,skillId:i,force:n=!1,rename:r=ee.rename}){let o=e.skills.find((d)=>d.id===i);p(o,`Skill ${JSON.stringify(i)} is not in the catalog. Run \`toloka skill list\` to see the available skills.`);let s=`${gn}/${o.id}`;await Wr(t,s);let a=Ze.join(t,s),g=await sn(a);p(g===void 0||n,`${s} already exists. Re-run with --force to replace it with the catalog version of ${o.id}.`);let l=Ze.dirname(a);await ee.mkdir(l,{recursive:!0});let I=await ee.mkdtemp(Ze.join(l,`.${o.id}.tmp-`));try{for(let d of o.files){let C=Ze.join(I,d);await ee.mkdir(Ze.dirname(C),{recursive:!0}),await ee.copyFile(Ze.join(e.root,o.id,d),C)}if(p(await xZ(I,o.files)===o.digest,`Skill ${o.id} failed its digest check: the packaged files do not match the catalog digest ${o.digest}. Nothing was installed.`),g===void 0)await r(I,a);else await mY(r,I,a,`${I}.backup`)}catch(d){throw await ee.rm(I,{recursive:!0,force:!0}),d}return{skill:o,directory:a,replaced:g!==void 0}}var JZ=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let i=Math.max(...e.map((r)=>r.id.length)),n=Math.max(...e.map((r)=>r.status.length));return e.flatMap((r)=>[`${r.id.padEnd(i)} ${r.status.padEnd(n)} ${r.name}`,` ${r.description}`]).join(`
144
144
  `)};async function UZ({sourceRoot:e,json:t,io:i}){let n=await CI();i.stdout(JZ(await EZ({sourceRoot:e,skills:n.skills}),t))}async function TZ({sourceRoot:e,query:t,json:i,io:n}){let r=await CI(),o=await EZ({sourceRoot:e,skills:CY(r.skills,t)});if(i||o.length>0){n.stdout(JZ(o,i));return}n.stdout(`No skills match ${JSON.stringify(t)}. Run \`toloka skill list\` to see the catalog.`)}async function OZ({sourceRoot:e,skillId:t,force:i,io:n}){let r=await CI(),o=await pY({catalog:r,sourceRoot:e,skillId:t,force:i}),s=`${gn}/${o.skill.id}`,a=o.skill.files.length;n.stdout(`${o.replaced?"Replaced":"Installed"} ${o.skill.id} in ${s} (${a} ${a===1?"file":"files"}). Start with ${s}/${an}.`)}var be=Is.version,$e="@toloka-platform/sdk",AI="toloka-bootstrap",jZ=`.claude/skills/${AI}/SKILL.md`,DZ=`.cursor/rules/${AI}.mdc`,ui="AGENTS.md",AY=[jZ,DZ,ui],ln={begin:"<toloka>",end:"</toloka>"},uI={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},mI=/<!-- toloka:sdk-version ([^\s>]+) -->/u,QZ=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),In=async(e)=>{try{return await ie.readFile(e,"utf8")}catch(t){if(cs(t))return;throw t}},pI=async(e)=>{try{return(await ie.lstat(e)).isDirectory()}catch(t){if(cs(t))return!1;throw t}},ZI=(e)=>mI.test(e),_Z=`Generated by \`${$e}\` version \`${be}\`.
@@ -258,7 +258,7 @@ ${u}`,...Z===void 0?{}:{warning:Z}}}async function Sb(e,t){let i=await NI(e,t,!1
258
258
  `)}}var tW=(e)=>{if(typeof e!=="object"||e===null)return!1;if(!("label"in e)||typeof e.label!=="string")return!1;if(!("expectedTotal"in e)||typeof e.expectedTotal!=="string")return!1;if(!("maxTotal"in e)||typeof e.maxTotal!=="string")return!1;if("subLines"in e&&e.subLines!==void 0&&!Array.isArray(e.subLines))return!1;return!0},PX=(e)=>{let t=[0,0,0];for(let i of e)for(let n=0;n<3;n+=1){let r=i[n];t[n]=Math.max(t[n]??0,r?.length??0)}return e.map((i)=>i.map((n,r)=>r===0?n.padEnd(t[0]??0):n.padStart(t[r]??0)).join(" "))},iW=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let r of e.subLines??[])if(tW(r))n.push(...iW(r,t+1));return n},NX=(e)=>{let t=[],i=[];for(let n of e){if(n.kind==="priced"){t.push([n.nodeNameDisplay,n.expectedTotal,n.maxTotal]);for(let r of n.displayBreakdown)if(tW(r))t.push(...iW(r,1));continue}i.push(n.kind==="validation-errors"?` ${n.nodeNameDisplay} skipped (validation errors)`:` ${n.nodeNameDisplay} not billed`)}return{billed:t,unpriced:i}},YX=(e)=>{let t=e.expected===e.worstCase?[["Run cost",e.expected,""]]:[["Expected run cost",e.expected,""],["Maximum run cost","",e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,"N/A"]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},XX=(e,t)=>{let{billed:i,unpriced:n}=NX(e.nodes),r=YX(e.total),o=PX([["Item","Expected","Maximum"],...i,...r]),s=o.slice(0,1+i.length),a=o.slice(1+i.length),g=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...s];if(i.length===0)g.push(" (no billed nodes)");if(g.push("",...a),n.length>0)g.push("","Not billed",...n);if(e.isInternalPricing===!0)g.push("","Internal-team pricing.");return g.push("",e.disclaimer),g.join(`
259
259
  `)};async function nW(e,t){let i=await Yr({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:i.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:XX(n,i.name)}}var rW=require("crypto"),gd=require("fs"),Ys=require("fs/promises"),et=require("path"),SX=262144,xX=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),EX=async(e,t)=>{let i=et.relative(t,e);if(i===""||i===".."||i.startsWith(`..${et.sep}`)||et.isAbsolute(i))return;let n=i.split(et.sep);for(let r=1;r<n.length;r+=1){let o=et.join(t,...n.slice(0,r)),s=await Ys.lstat(o);p(!s.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${o}; select a path that does not traverse symbolic links.`)}},JX=async(e,t,i)=>{let n=et.resolve(i,e);await EX(n,t);let r;try{r=await Ys.open(n,gd.constants.O_RDONLY|gd.constants.O_NOFOLLOW)}catch(o){throw p(!(o instanceof Error&&("code"in o)&&o.code==="ELOOP"),`Report file ${n} is a symbolic link; select the file it points to directly.`),o}try{let o=await r.stat();return p(o.isFile(),`Report file ${n} is not a regular file.`),p(o.size>0,`Report file ${n} is empty.`),p(o.size<=SX,`Report file ${n} is ${o.size} bytes; the limit is 256 KiB.`),{handle:r,absolutePath:n,size:o.size}}catch(o){throw await r.close(),o}},UX=async(e,t,i)=>{let n=await JX(e,t,i);try{let r=await n.handle.readFile();p(r.byteLength===n.size,`${n.absolutePath} changed while it was being read.`);try{return xX.decode(r)}catch{throw Error(`Report file ${n.absolutePath} is not valid UTF-8.`)}}finally{await n.handle.close()}},TX=async(e,t)=>{if(t)return!0;if(e.prompt===void 0)return!1;let i=(await e.prompt("Send this report to Toloka? [y/N] ")).trim().toLowerCase();return i==="y"||i==="yes"};async function oW(e){let{analytics:t,io:i}=e;p(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.");let n=await UX(e.path,e.sourceRoot,e.cwd);if(i.stdout("Issue report preview:"),i.stdout(""),i.stdout(n.replace(/(?![\t\n])(?!\r\n)(?:\p{Cc}|\p{Bidi_Control})/gu,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)),i.stdout(""),i.stdout(`Authored by: ${e.authoredBy}`),i.stdout(`Platform: ${e.platform}`),i.stdout(""),!await TX(i,e.confirm))return i.stderr("Refusing to submit without confirmation in a non-interactive environment. Pass --confirm after reviewing the preview above."),1;let r=rW.randomUUID();return await t.submitIssueReport({reportId:r,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),i.stdout(`Submitted issue report: ${r}`),0}var aW=require("path"),Xr=require("fs/promises"),ld=require("crypto");var OX=262144,Sr=(e)=>{let t=e.reduce((i,n)=>n.map((r,o)=>Math.max(i[o]??0,r.length)),[]);return e.map((i)=>i.map((n,r)=>n.padEnd(t[r]??n.length)).join(" ").trimEnd()).join(`
260
260
  `)},pt=(e,t,i,n)=>{e.stdout(t?JSON.stringify(i,null,2):n)},zX=(e)=>Sr([["ID",e.id],["Project",e.projectId],["Method",e.configuration.method==="sft"?"Supervised fine-tuning (SFT)":"Prompt gisting"],["Output Model",e.modelId??"-"],["Archived at",e.archivedAt??"-"],["Created at",e.createdAt],["Updated at",e.updatedAt]]),Xs=(e)=>Sr([["ID",e.id],["Training",e.trainingId],["Status",e.status],["Blocked reason",e.blockedReason??"-"],["Message",e.message??"-"],["Error code",e.error?.code??"-"],["Billing status",e.billingStatus],["Charged amount",e.chargedAmount===null?"-":`$${e.chargedAmount} ${e.quote.currency}`],["Progress",e.progress?`${e.progress.phase}${e.progress.step===null?"":` ${e.progress.step}${e.progress.total===null?"":`/${e.progress.total}`}`}`:"-"],["Model Version name",e.outputModelVersionName],["Model Version revision",e.outputModelVersionRevision===null?"-":String(e.outputModelVersionRevision)],["Future Model Version",e.outputModelVersionId],["Maximum charge",`$${e.quote.maximumCharge} ${e.quote.currency}`],["Created at",e.createdAt]]),jX=(e)=>(p(typeof e==="object"&&e!==null&&!Array.isArray(e),"The estimate file must contain a JSON object."),p("status"in e&&e.status==="ready","The estimate file is not a ready Training Cost Estimate."),p("trainingId"in e&&typeof e.trainingId==="string","The estimate file has no Training ID."),p("inputSetId"in e&&typeof e.inputSetId==="string","The estimate file has no Input Set ID."),p("fingerprint"in e&&typeof e.fingerprint==="string"&&/^[0-9a-f]{64}$/.test(e.fingerprint),"The estimate file has no valid fingerprint."),{status:"ready",trainingId:e.trainingId,inputSetId:e.inputSetId,fingerprint:e.fingerprint}),DX=(e)=>{if(e.status==="blocked")return["Training cannot run with these inputs:",...e.issues.map((t)=>`- ${t.message}`)].join(`
261
- `);return Sr([["Training",e.trainingId],["Training rows",String(e.inputs.training.report?.validCount??0)],["Training tokens",String(e.inputs.training.report?.tokens.total??0)],["Maximum GPU seconds",String(e.budget.maximumGpuSeconds)],["Maximum charge",`$${e.maximumCharge} ${e.currency}`],["Fingerprint",e.fingerprint]])},xr=async(e,t,i)=>{if(i.startsWith("trg.")){let r=await e.trainings.get({trainingId:i});return p(r.projectId===t,`Training ${i} was not found in project ${t}.`),r}let n=[];for await(let r of e.trainings.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return p(n.length===1,`Training ${i} was not found or is ambiguous.`),n[0]},QX=(e)=>{if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return e.trim()!==""&&Number.isFinite(t)?t:e},sW=async(e,t,i)=>{if(p(t,"A Dataset is required when specifying a filter."),i===void 0)return{datasetId:t};let n=i.indexOf("=");p(n>0&&n<i.length-1,"Dataset filters must use FIELD=VALUE syntax.");let r=i.slice(0,n),o=i.slice(n+1),s=[];for await(let g of e.datasets.listAllFields({datasetId:t}))if(g.name===r)s.push(g);let[a]=s;return p(a&&s.length===1,`Dataset field ${r} was not found or is ambiguous.`),{datasetId:t,itemFilter:{fieldValues:[{fieldId:a.id,jsonPath:"$",operator:"text_eq",value:QX(o),latestOnly:!0,sources:[]}],fieldSources:[],missingRevisionFields:[]}}},_X=(e,t)=>{if(p(!(e.baseModelId&&e.modelVersionId),"Choose exactly one of --base-model and --model-version."),e.baseModelId)return{type:"base_model",baseModelId:e.baseModelId};if(e.modelVersionId)return{type:"model_version",modelVersionId:e.modelVersionId};return p(t,"Choose exactly one of --base-model and --model-version."),t},KX=async(e,t,i,n)=>{let r=await Xr.stat(i);p(r.isFile(),"--prompt-file must point to a file."),p(r.size>0,"The gisting prompt file is empty."),p(r.size<=OX,"The gisting prompt file exceeds the 256 KiB limit.");let o=await Xr.readFile(i),s;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw Error("The gisting prompt file must contain valid UTF-8 text.")}p(s.trim().length>0,"The gisting prompt file is empty.");let a=await e.files.startUpload({projectId:t,filename:aW.basename(i),declaredSizeBytes:o.byteLength});try{let g=await n(a.uploadUrl,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/plain; charset=utf-8"},body:o});return p(g.ok,`Failed to upload gisting prompt: HTTP ${g.status}.`),(await e.files.finalizeUpload({projectId:t,fileId:a.file.id})).id}catch(g){throw await e.files.delete({projectId:t,fileId:a.file.id}).catch(()=>{return}),g}},LX=async({client:e,current:t,options:i})=>{let n=i.datasetId??t?.training.datasetId;p(n,"--dataset is required.");let r=i.datasetId===void 0&&i.trainingFilter===void 0&&t?t.training:await sW(e,n,i.trainingFilter),o=i.validationDatasetId===void 0&&i.validationFilter===void 0?t?.validation:await sW(e,i.validationDatasetId??t?.validation?.datasetId??"",i.validationFilter);return{training:r,validation:o}},MX=({source:e,selections:t,current:i,options:n})=>(p(n.promptFilePath===void 0,"Gisting options cannot be used with SFT."),{...i,method:"sft",source:e,...t,...n.regime===void 0?{}:{regime:n.regime},...n.epochs===void 0?{}:{epochs:n.epochs},...n.evalSteps===void 0?{}:{evalSteps:n.evalSteps}}),$X=async({client:e,projectId:t,source:i,selections:n,current:r,options:o})=>{p(o.evalSteps===void 0,"SFT options cannot be used with gisting.");let s=o.promptFilePath?await KX(e,t,o.promptFilePath,o.fetch??globalThis.fetch):r?.promptFileId;return p(s,"--prompt-file is required for gisting."),{...r,method:"gisting",source:i,...n,promptFileId:s,...o.regime===void 0?{}:{regime:o.regime},...o.epochs===void 0?{}:{epochs:o.epochs}}},gW=async({client:e,projectId:t,current:i,options:n})=>{let r=_X(n,i?.source),o=await LX({client:e,current:i,options:n});return(n.method??i?.method??"sft")==="sft"?MX({source:r,selections:o,current:i?.method==="sft"?i:void 0,options:n}):$X({client:e,projectId:t,source:r,selections:o,current:i?.method==="gisting"?i:void 0,options:n})},lW=async(e,t,i)=>{let n=await e.trainings.listPage({projectId:t.projectId,limit:100,offset:0});pt(i,t.json,n.trainings,n.trainings.length===0?"No Trainings found.":Sr([["ID","NAME","METHOD","OUTPUT MODEL"],...n.trainings.map((r)=>[r.id,r.name,r.configuration.method==="sft"?"SFT":"GISTING",r.modelId??"-"])]))},IW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId);pt(i,t.json,n,zX(n))},dW=async(e,t,i)=>{p(t.datasetId,"--dataset is required."),p(!t.validationFilter||t.validationDatasetId,"--validation-filter requires --validation-dataset.");let n=await gW({client:e,projectId:t.projectId,options:t}),r=await e.trainings.create({projectId:t.projectId,name:t.name,configuration:n});pt(i,t.json,r,`Created training ${r.id}`)},cW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.replaceConfiguration({trainingId:n.id,configuration:await gW({client:e,projectId:t.projectId,current:n.configuration,options:t})});pt(i,t.json,r,`Updated training ${r.id}`)},CW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.prepareCostEstimateInputs({trainingId:n.id,idempotencyKey:t.idempotencyKey??ld.randomUUID()}),o=[r.exports.training,r.exports.validation].filter((a)=>a!==null);await Promise.all(o.map((a)=>e.waitFor({type:"datasetExport",exportId:a})));let s=await e.trainings.estimateCost({trainingId:n.id,inputSetId:r.id});pt(i,t.json,s,DX(s))},uW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=jX(JSON.parse(await Xr.readFile(t.estimateFile,"utf8")));p(r.trainingId===n.id,"The estimate file belongs to another Training.");let o=await e.trainings.createRun({trainingId:n.id,inputSetId:r.inputSetId,estimateFingerprint:r.fingerprint,versionName:t.versionName,idempotencyKey:t.idempotencyKey??ld.randomUUID()});pt(i,t.json,o,Xs(o))},mW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.listRunsPage({trainingId:n.id,limit:100,offset:0});pt(i,t.json,r.trainingRuns,r.trainingRuns.length===0?"No Training Runs found.":Sr([["ID","STATUS","VERSION","MAXIMUM CHARGE","OUTPUT MODEL VERSION"],...r.trainingRuns.map((o)=>[o.id,o.status,o.outputModelVersionName,`$${o.quote.maximumCharge}`,o.outputModelVersionId])]))},pW=async(e,t,i)=>{let n=await e.trainings.getRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},AW=async(e,t,i)=>{let n=await e.trainings.resumeRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},ZW=async(e,t,i)=>{let n=await e.trainings.cancelRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},bW=async(e,t,i)=>{let n=null;for(;;){let r=await e.trainings.getRunLogs({trainingRunId:t.trainingRunId,cursor:n??void 0,limit:100});for(let o of r.entries)i.stdout(`${o.timestamp} ${o.level.toUpperCase()} ${o.message}`);if(!t.follow||r.complete){if(r.truncated)i.stdout("Training logs were truncated by the server.");return}n=r.nextCursor,await new Promise((o)=>{setTimeout(o,t.pollIntervalMs??1000)})}};var hW=require("fs"),WW=require("os"),he=require("path");var qX=`${he.sep}install${he.sep}global${he.sep}`,Id=(e)=>{try{return hW.realpathSync(e)}catch{return e}},eS=(e,t,i,n)=>{if(Id(e).includes(qX))return"global-registry";if(Id(n)===t)return"linked";if(he.dirname(he.resolve(e))===he.resolve(i))return"linked";return"project-local"},fW=(e=process.argv[1],t={})=>{p(e,"CLI entry path is unavailable");let i=t.globalBinDirectory??he.resolve(process.env.BUN_INSTALL??he.join(WW.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??he.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=he.resolve(he.dirname(Id(e)),".."),o=eS(e,r,i,n);return{version:be,commit:"9dc3b33707ce",channel:o,...o==="linked"?{path:r}:{}}};var tS=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. POTATO_API_KEY / POTATO_BASE_URL"," 3. the file written by toloka login",`The platform defaults to ${ai}.`].join(`
261
+ `);return Sr([["Training",e.trainingId],["Training rows",String(e.inputs.training.report?.validCount??0)],["Training tokens",String(e.inputs.training.report?.tokens.total??0)],["Maximum GPU seconds",String(e.budget.maximumGpuSeconds)],["Maximum charge",`$${e.maximumCharge} ${e.currency}`],["Fingerprint",e.fingerprint]])},xr=async(e,t,i)=>{if(i.startsWith("trg.")){let r=await e.trainings.get({trainingId:i});return p(r.projectId===t,`Training ${i} was not found in project ${t}.`),r}let n=[];for await(let r of e.trainings.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return p(n.length===1,`Training ${i} was not found or is ambiguous.`),n[0]},QX=(e)=>{if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return e.trim()!==""&&Number.isFinite(t)?t:e},sW=async(e,t,i)=>{if(p(t,"A Dataset is required when specifying a filter."),i===void 0)return{datasetId:t};let n=i.indexOf("=");p(n>0&&n<i.length-1,"Dataset filters must use FIELD=VALUE syntax.");let r=i.slice(0,n),o=i.slice(n+1),s=[];for await(let g of e.datasets.listAllFields({datasetId:t}))if(g.name===r)s.push(g);let[a]=s;return p(a&&s.length===1,`Dataset field ${r} was not found or is ambiguous.`),{datasetId:t,itemFilter:{fieldValues:[{fieldId:a.id,jsonPath:"$",operator:"text_eq",value:QX(o),latestOnly:!0,sources:[]}],fieldSources:[],missingRevisionFields:[]}}},_X=(e,t)=>{if(p(!(e.baseModelId&&e.modelVersionId),"Choose exactly one of --base-model and --model-version."),e.baseModelId)return{type:"base_model",baseModelId:e.baseModelId};if(e.modelVersionId)return{type:"model_version",modelVersionId:e.modelVersionId};return p(t,"Choose exactly one of --base-model and --model-version."),t},KX=async(e,t,i,n)=>{let r=await Xr.stat(i);p(r.isFile(),"--prompt-file must point to a file."),p(r.size>0,"The gisting prompt file is empty."),p(r.size<=OX,"The gisting prompt file exceeds the 256 KiB limit.");let o=await Xr.readFile(i),s;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw Error("The gisting prompt file must contain valid UTF-8 text.")}p(s.trim().length>0,"The gisting prompt file is empty.");let a=await e.files.startUpload({projectId:t,filename:aW.basename(i),declaredSizeBytes:o.byteLength});try{let g=await n(a.uploadUrl,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/plain; charset=utf-8"},body:o});return p(g.ok,`Failed to upload gisting prompt: HTTP ${g.status}.`),(await e.files.finalizeUpload({projectId:t,fileId:a.file.id})).id}catch(g){throw await e.files.delete({projectId:t,fileId:a.file.id}).catch(()=>{return}),g}},LX=async({client:e,current:t,options:i})=>{let n=i.datasetId??t?.training.datasetId;p(n,"--dataset is required.");let r=i.datasetId===void 0&&i.trainingFilter===void 0&&t?t.training:await sW(e,n,i.trainingFilter),o=i.validationDatasetId===void 0&&i.validationFilter===void 0?t?.validation:await sW(e,i.validationDatasetId??t?.validation?.datasetId??"",i.validationFilter);return{training:r,validation:o}},MX=({source:e,selections:t,current:i,options:n})=>(p(n.promptFilePath===void 0,"Gisting options cannot be used with SFT."),{...i,method:"sft",source:e,...t,...n.regime===void 0?{}:{regime:n.regime},...n.epochs===void 0?{}:{epochs:n.epochs},...n.evalSteps===void 0?{}:{evalSteps:n.evalSteps}}),$X=async({client:e,projectId:t,source:i,selections:n,current:r,options:o})=>{p(o.evalSteps===void 0,"SFT options cannot be used with gisting.");let s=o.promptFilePath?await KX(e,t,o.promptFilePath,o.fetch??globalThis.fetch):r?.promptFileId;return p(s,"--prompt-file is required for gisting."),{...r,method:"gisting",source:i,...n,promptFileId:s,...o.regime===void 0?{}:{regime:o.regime},...o.epochs===void 0?{}:{epochs:o.epochs}}},gW=async({client:e,projectId:t,current:i,options:n})=>{let r=_X(n,i?.source),o=await LX({client:e,current:i,options:n});return(n.method??i?.method??"sft")==="sft"?MX({source:r,selections:o,current:i?.method==="sft"?i:void 0,options:n}):$X({client:e,projectId:t,source:r,selections:o,current:i?.method==="gisting"?i:void 0,options:n})},lW=async(e,t,i)=>{let n=await e.trainings.listPage({projectId:t.projectId,limit:100,offset:0});pt(i,t.json,n.trainings,n.trainings.length===0?"No Trainings found.":Sr([["ID","NAME","METHOD","OUTPUT MODEL"],...n.trainings.map((r)=>[r.id,r.name,r.configuration.method==="sft"?"SFT":"GISTING",r.modelId??"-"])]))},IW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId);pt(i,t.json,n,zX(n))},dW=async(e,t,i)=>{p(t.datasetId,"--dataset is required."),p(!t.validationFilter||t.validationDatasetId,"--validation-filter requires --validation-dataset.");let n=await gW({client:e,projectId:t.projectId,options:t}),r=await e.trainings.create({projectId:t.projectId,name:t.name,configuration:n});pt(i,t.json,r,`Created training ${r.id}`)},cW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.replaceConfiguration({trainingId:n.id,configuration:await gW({client:e,projectId:t.projectId,current:n.configuration,options:t})});pt(i,t.json,r,`Updated training ${r.id}`)},CW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.prepareCostEstimateInputs({trainingId:n.id,idempotencyKey:t.idempotencyKey??ld.randomUUID()}),o=[r.exports.training,r.exports.validation].filter((a)=>a!==null);await Promise.all(o.map((a)=>e.waitFor({type:"datasetExport",exportId:a})));let s=await e.trainings.estimateCost({trainingId:n.id,inputSetId:r.id});pt(i,t.json,s,DX(s))},uW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=jX(JSON.parse(await Xr.readFile(t.estimateFile,"utf8")));p(r.trainingId===n.id,"The estimate file belongs to another Training.");let o=await e.trainings.createRun({trainingId:n.id,inputSetId:r.inputSetId,estimateFingerprint:r.fingerprint,versionName:t.versionName,idempotencyKey:t.idempotencyKey??ld.randomUUID()});pt(i,t.json,o,Xs(o))},mW=async(e,t,i)=>{let n=await xr(e,t.projectId,t.nameOrId),r=await e.trainings.listRunsPage({trainingId:n.id,limit:100,offset:0});pt(i,t.json,r.trainingRuns,r.trainingRuns.length===0?"No Training Runs found.":Sr([["ID","STATUS","VERSION","MAXIMUM CHARGE","OUTPUT MODEL VERSION"],...r.trainingRuns.map((o)=>[o.id,o.status,o.outputModelVersionName,`$${o.quote.maximumCharge}`,o.outputModelVersionId])]))},pW=async(e,t,i)=>{let n=await e.trainings.getRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},AW=async(e,t,i)=>{let n=await e.trainings.resumeRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},ZW=async(e,t,i)=>{let n=await e.trainings.cancelRun({trainingRunId:t.trainingRunId});pt(i,t.json,n,Xs(n))},bW=async(e,t,i)=>{let n=null;for(;;){let r=await e.trainings.getRunLogs({trainingRunId:t.trainingRunId,cursor:n??void 0,limit:100});for(let o of r.entries)i.stdout(`${o.timestamp} ${o.level.toUpperCase()} ${o.message}`);if(!t.follow||r.complete){if(r.truncated)i.stdout("Training logs were truncated by the server.");return}n=r.nextCursor,await new Promise((o)=>{setTimeout(o,t.pollIntervalMs??1000)})}};var hW=require("fs"),WW=require("os"),he=require("path");var qX=`${he.sep}install${he.sep}global${he.sep}`,Id=(e)=>{try{return hW.realpathSync(e)}catch{return e}},eS=(e,t,i,n)=>{if(Id(e).includes(qX))return"global-registry";if(Id(n)===t)return"linked";if(he.dirname(he.resolve(e))===he.resolve(i))return"linked";return"project-local"},fW=(e=process.argv[1],t={})=>{p(e,"CLI entry path is unavailable");let i=t.globalBinDirectory??he.resolve(process.env.BUN_INSTALL??he.join(WW.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??he.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=he.resolve(he.dirname(Id(e)),".."),o=eS(e,r,i,n);return{version:be,commit:"327f7f9b9c3f",channel:o,...o==="linked"?{path:r}:{}}};var tS=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. POTATO_API_KEY / POTATO_BASE_URL"," 3. the file written by toloka login",`The platform defaults to ${ai}.`].join(`
262
262
  `),iS=(e)=>{if(e!=="human"&&e!=="agent")throw new Pe('Expected "human" or "agent".');return e},At=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Pe("Expected a positive integer.");return t},yW=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<0)throw new Pe("Expected a non-negative integer.");return t},nS=(e)=>{if(e!=="sft"&&e!=="gisting")throw new Pe('Expected training method "sft" or "gisting".');return e},VW=(e)=>{if(e!=="low"&&e!=="medium"&&e!=="high")throw new Pe('Expected regime "low", "medium", or "high".');return e},BW=(e)=>({method:e.method,baseModelId:e.baseModel,modelVersionId:e.modelVersion,datasetId:e.dataset,validationDatasetId:e.validationDataset,trainingFilter:e.trainFilter,validationFilter:e.validationFilter,regime:e.regime,epochs:e.epochs,evalSteps:e.evalSteps,promptFilePath:e.promptFile}),dd=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},tt=async(e,t)=>{if(e.sourceRoot!==void 0)return Jr.resolve(e.sourceRoot);let i=process.cwd(),n=await Zp(i);if(n===void 0||n===i)return i;return t.stderr(`Using project root ${n} (found from ${i}).`),n},RW=(e)=>e.sourceRoot===void 0?process.cwd():Jr.resolve(e.sourceRoot),HW=async(e,t)=>{let{found:i,warning:n}=await sr(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(n!==void 0)t.io.stderr(n);return i?.credentials},Er=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},Y=async(e,t)=>{let i=await tt(e,t.io),n=await Re(i),r=await HW(e,t),o=Pl(e,n,t.environment,r),s=t.injectedClient??bt({apiKey:o.apiKey,baseUrl:o.baseUrl});return await Er(s,t.analytics),{sourceRoot:i,client:s,baseUrl:o.baseUrl,state:n,stored:r,...o.projectId===void 0?{}:{projectId:o.projectId}}},GW=(e,t,i,n)=>_i({flags:e,environment:t.environment,stored:i,...n===void 0?{}:{state:n}});function rS(e){let t=new yi("toloka"),i={value:0},n=e.runChecks??wl,r=async(m,b=n)=>{let h=new AbortController,f,y=(w)=>{f=w,h.abort()},B=()=>y(130),F=()=>y(143);process.on("SIGINT",B),process.on("SIGTERM",F);try{return{result:await b({...m,signal:h.signal}),...f===void 0?{}:{interruptedExitCode:f}}}finally{process.off("SIGINT",B),process.off("SIGTERM",F)}},o=!1;t.description("Beta. Build and operate Toloka pipeline projects from TypeScript source. The public API may change before general availability.").version(be,"-v, --version","output the current version").option("--source-root <directory>","project root; discovered from the working directory when omitted").option("--api-key <key>","API key for this command only").option("--base-url <url>","platform base URL for this command only").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
263
263
  ${tS}`).configureOutput({writeOut:(m)=>e.io.stdout(m.replace(/\n$/u,"")),writeErr:(m)=>e.io.stderr(m.replace(/\n$/u,""))}).exitOverride();let s=()=>t.opts();t.hook("postAction",async(m,b)=>{if(o)return;let h=[];for(let B=b;B!==null;B=B.parent)h.push(B.name());if(h.includes("init")||h.includes("help")||h.includes("report")||h.includes("url")||h.includes("version")||h.includes("config"))return;let f=await tt(s(),e.io),y=await MZ(f).catch(()=>{return});if(y===void 0)return;o=!0,e.io.stderr(y)}),t.command("version").option("--json","print version and build provenance as JSON",!1).description("print the current CLI version").action((m)=>e.io.stdout(m.json?JSON.stringify(fW()):be));let a=t.command("config").description("read and write machine CLI settings");a.command("get").argument("[name]","setting name; omit to print every setting").description("print a CLI setting, or every setting").action(async(m)=>{let b=await yr(e.environment);e.io.stdout(hI(b,m).output)}),a.command("set").argument("<name>","setting name").argument("<value>","setting value").description("write a CLI setting for this machine").action(async(m,b)=>{let h=await nb(e.environment,m,b);e.io.stdout(h.output)}),a.action(async()=>{let m=await yr(e.environment);e.io.stdout(hI(m,void 0).output)}),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let m=await Kp({...s().apiKey===void 0?{}:{apiKey:s().apiKey},...s().baseUrl===void 0?{}:{baseUrl:s().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(m.output);try{let b=await Xp(e.environment);if(b===void 0)return;let h=e.injectedClient??bt(b);await Er(h,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let m=await Lp(e.environment);e.io.stdout(m.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(m)=>{let b=s(),h=await sr(e.environment,b.apiKey??e.environment.POTATO_API_KEY),f=h.found?.credentials,y=await tt(b,e.io),B=await Re(y),F=GW(b,e,f,B),w=e.injectedClient,S=await $p({environment:e.environment,showToken:m.showToken,credentialLookup:h,...b.apiKey===void 0?{}:{flagApiKey:b.apiKey},...b.baseUrl===void 0?{}:{flagBaseUrl:b.baseUrl},...w===void 0?{}:{probe:()=>w},...F===void 0?{}:{project:F}});if(e.io.stdout(S.output),!S.authenticated){i.value=1;return}try{let U=Pl(b,B,e.environment,f),M=e.injectedClient??bt({apiKey:U.apiKey,baseUrl:U.baseUrl});await Er(M,e.analytics)}catch{}});let g=t.command("project").description("select and manage the current platform project");g.command("list").option("--limit <n>","maximum projects to list",At).description("list remote projects this key can see").action(async(m)=>{let b=s(),{client:h,stored:f,state:y}=await Y(b,e),B=GW(b,e,f,y);await Up({client:h,io:e.io,...B===void 0?{}:{context:B},...m.limit===void 0?{}:{limit:m.limit}})}),g.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(m,b)=>{let h=s(),f=await zt(e.environment),y=e.injectedClient??bt(f.credentials);await Op({environment:e.environment,flags:h,client:y,io:e.io,afterPreflight:async()=>Er(y,e.analytics),...m===void 0?{}:{alias:m},...b===void 0?{}:{projectId:b}})}),g.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(m)=>{await zp({environment:e.environment,flags:s(),alias:m,io:e.io})}),g.command("current").description("show the project this command would use").action(async()=>{let m=s(),b=await HW(m,e),h=await tt(m,e.io),f=await Re(h);if(Dp({flags:m,environment:e.environment,stored:b,...f===void 0?{}:{state:f},io:e.io}).project===void 0)i.value=1}),g.command("url").description("print the current project URL").action(async()=>{let{baseUrl:m,client:b,projectId:h}=await Y(s(),e);p(h,j);let f=await b.projects.get({projectId:h}),y=new URL(`/teams/${encodeURIComponent(f.teamId)}/projects/${encodeURIComponent(f.id)}`,m);e.io.stdout(y.href)}),g.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(m)=>{await jp({environment:e.environment,flags:s(),alias:m,io:e.io})}),g.command("untrack").argument("<type>","pipeline or dataset").argument("<name>","tracked resource name").option("--confirm","confirm untracking in a non-interactive environment",!1).description("remove a pipeline or dataset from local tracking without deleting it").action(async(m,b,h)=>{p(m==="pipeline"||m==="dataset","Resource type must be pipeline or dataset.");let f=await tt(s(),e.io);await Tp({sourceRoot:f,type:m,name:b,confirm:h.confirm,io:e.io})}),g.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(m,b)=>{let h=s(),f=await zt(e.environment),y=e.injectedClient??bt(f.credentials),B=await tt(h,e.io);await Qp({environment:e.environment,flags:h,client:y,io:e.io,sourceRoot:B,afterPreflight:async()=>Er(y,e.analytics),...m===void 0?{}:{alias:m},...b.name===void 0?{}:{name:b.name},...b.teamId===void 0?{}:{teamId:b.teamId}})}),t.command("init").description("initialize this project directory and install the agent bootstrap").action(async()=>{let m=s(),b=RW(m),h=await Re(b),f=_i({flags:m,environment:e.environment,...h===void 0?{}:{state:h}}),y=await LZ(b,f===void 0?{}:{projectId:f.id});if(e.io.stdout(y.output),y.warning!==void 0)e.io.stderr(y.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(m,b)=>{let{sourceRoot:h,client:f,projectId:y}=await Y(s(),e),B=m??y;p(B,j);let F=await Rb(f,{sourceRoot:h,projectId:B,...b?.force===!0?{force:!0}:{}});e.io.stdout(F.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:m,client:b,projectId:h}=await Y(s(),e),f=await Gb(b,{sourceRoot:m,...h===void 0?{}:{projectId:h}});e.io.stdout(f.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:m,client:b,projectId:h}=await Y(s(),e),f=await Hb(b,{sourceRoot:m,...h===void 0?{}:{projectId:h}});if(e.io.stdout(f.output),!f.valid)i.value=1}),t.command("check").argument("[pipeline]","pipeline source directory or name").option("--node <node>","check one code or human-work node by name or id").option("--json","print the structured check report",!1).option("--watch","rerun checks when project files change",!1).description("run the complete local source, type, and test gate").action(async(m,b)=>{let h=await tt(s(),e.io),f={environment:e.environment,sourceRoot:h,...m===void 0?{}:{pipeline:m},...b.node===void 0?{}:{node:b.node},...b.json?{json:!0}:{}},y=async(S)=>{let U=e.environment[ri];if(U===void 0)e.io.stdout(S);else await wW.writeFile(U,S,"utf8")},B=e.runChecks===void 0&&e.environment[ri]===void 0?Fl:n;if(b.watch){let S=new AbortController,U=()=>S.abort();process.on("SIGINT",U),process.on("SIGTERM",U);try{await Hp(f,async(M)=>{await y(M.output),i.value=M.exitCode},void 0,S.signal)}finally{process.off("SIGINT",U),process.off("SIGTERM",U)}return}let{result:F,interruptedExitCode:w}=await r(f,B);await y(F.output),i.value=w??F.exitCode}),t.command("apply").description("check source, then make the platform match it").action(async()=>{let m=await tt(s(),e.io),{result:b,interruptedExitCode:h}=await r({sourceRoot:m,environment:e.environment});if(e.io.stdout(b.output),h!==void 0){i.value=h;return}if(b.exitCode!==0){i.value=b.exitCode;return}p(b.source,"Passing checks must return project source");let{client:f,projectId:y}=await Y(s(),e),B=await Fb(f,{sourceRoot:m,source:b.source,...y===void 0?{}:{projectId:y}});e.io.stdout(B.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j);let y=b.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[b.fromEnv];p(y!==void 0,`Missing secret value. Set ${b.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let B=await Jb(h,{projectId:f,name:m,value:y});e.io.stdout(B.output)}catch{e.io.stderr(`Failed to set secret ${m}.`),i.value=1}});let I=t.command("base-model").description("inspect the global base model catalog");I.command("list").option("--json","print JSON",!1).description("list base models").action(async(m)=>{let{client:b}=await Y(s(),e);await Ob(b,{json:m.json},e.io)}),I.command("get").argument("<id>","base model ID").option("--json","print JSON",!1).description("show one base model").action(async(m,b)=>{let{client:h}=await Y(s(),e);await zb(h,{id:Fr(m),json:b.json},e.io)});let d=t.command("model").description("manage project Models and immutable versions");d.command("list").option("--json","print JSON",!1).description("list Models owned by the selected project").action(async(m)=>{let{client:b,projectId:h}=await Y(s(),e);p(h,j),await jb(b,{projectId:h,json:m.json},e.io)}),d.command("get").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("show one project Model").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await Db(h,{projectId:f,nameOrId:m,json:b.json},e.io)}),d.command("versions").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("list immutable versions of a model").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await Qb(h,{projectId:f,nameOrId:m,json:b.json},e.io)}),d.command("create").argument("<name>","new Model name").requiredOption("--base <id>","base model ID").option("--description <text>","Model description").option("--json","print JSON",!1).description("create project Model metadata without a Model Version").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await _b(h,{projectId:f,name:m,description:b.description,baseModelId:Fr(b.base),json:b.json},e.io)}),d.command("archive").option("--json","print JSON",!1).argument("<name-or-id>","project Model name or ID").description("archive a project Model").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await Kb(h,{projectId:f,nameOrId:m,json:b.json},e.io)}),d.command("version").description("manage one immutable Model Version").command("download").argument("<model-version>","Model Version ID or Model@name").requiredOption("--out <directory>","output directory").description("download and verify Model Version content").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);await Lb(h,{projectId:f,modelVersionId:m,out:b.out},e.io)});let A=t.command("training").description("manage project Training drafts");A.command("list").option("--json","print JSON",!1).description("list active Trainings owned by the selected project").action(async(m)=>{let{client:b,projectId:h}=await Y(s(),e);p(h,j),await lW(b,{projectId:h,json:m.json},e.io)}),A.command("get").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("show one Training draft").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await IW(h,{projectId:f,nameOrId:m,json:b.json},e.io)}),A.command("create").argument("<name>","new Training name").option("--method <method>","Training method",nS,"sft").option("--base-model <id>","catalog Base Model source",Fr).option("--model-version <id>","exact Model Version source").requiredOption("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","optional validation Dataset ID").option("--train-filter <field=value>","training Dataset field equality filter").option("--validation-filter <field=value>","validation Dataset field equality filter").option("--regime <regime>","Python training regime",VW).option("--epochs <count>","training epochs",yW).option("--eval-steps <count>","SFT eval steps",At).option("--prompt-file <path>","gisting prompt text file").option("--json","print JSON",!1).description("create a normalized Training draft").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await dW(h,{...BW(b),projectId:f,name:m,json:b.json},e.io)}),A.command("update").argument("<name-or-id>","Training name or ID").option("--base-model <id>","catalog Base Model source",Fr).option("--model-version <id>","exact Model Version source").option("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","replacement validation Dataset ID").option("--train-filter <field=value>","replacement training Dataset field equality filter").option("--validation-filter <field=value>","replacement validation Dataset field equality filter").option("--regime <regime>","Python training regime",VW).option("--epochs <count>","training epochs",yW).option("--eval-steps <count>","SFT eval steps",At).option("--prompt-file <path>","replacement gisting prompt text file").option("--json","print JSON",!1).description("replace the complete Training draft").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await cW(h,{...BW(b),projectId:f,nameOrId:m,json:b.json},e.io)}),A.command("cost").argument("<name-or-id>","Training name or ID").option("--idempotency-key <key>","reuse one Cost Estimate input preparation").option("--json","print JSON",!1).description("validate Training inputs and calculate the maximum charge").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await CW(h,{projectId:f,nameOrId:m,idempotencyKey:b.idempotencyKey,json:b.json},e.io)}),A.command("run").argument("<name-or-id>","Training name or ID").requiredOption("--estimate-file <path>","ready Training Cost Estimate JSON").requiredOption("--version-name <name>","unique Model Version name for this run").option("--idempotency-key <key>","reuse one Training Run creation").option("--json","print JSON",!1).description("create one queued Training Run from a ready Cost Estimate").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await uW(h,{projectId:f,nameOrId:m,...b},e.io)}),A.command("runs").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("list Training Run history").action(async(m,b)=>{let{client:h,projectId:f}=await Y(s(),e);p(f,j),await mW(h,{projectId:f,nameOrId:m,json:b.json},e.io)}),A.command("status").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("show one Training Run").action(async(m,b)=>{let{client:h}=await Y(s(),e);await pW(h,{trainingRunId:m,json:b.json},e.io)}),A.command("resume").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("resume a Training Run blocked on funds or payment").action(async(m,b)=>{let{client:h}=await Y(s(),e);await AW(h,{trainingRunId:m,json:b.json},e.io)}),A.command("cancel").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("cancel a Training Run before provider work completes").action(async(m,b)=>{let{client:h}=await Y(s(),e);await ZW(h,{trainingRunId:m,json:b.json},e.io)}),A.command("logs").argument("<training-run-id>","Training Run ID").option("--follow","wait for new log entries until complete",!1).description("read sanitized Training Run logs").action(async(m,b)=>{let{client:h}=await Y(s(),e);await bW(h,{trainingRunId:m,follow:b.follow},e.io)});let c=t.command("dataset").description("inspect and move dataset catalog and rows");c.command("list").description("list live datasets in the selected project").action(async()=>{let{client:m,projectId:b}=await Y(s(),e);p(b,j);let h=await xb(m,{projectId:b});e.io.stdout(h.output)}),c.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(m)=>{let{sourceRoot:b,client:h,projectId:f}=await Y(s(),e),y=await Sb(h,{sourceRoot:b,datasetName:m,...f===void 0?{}:{projectId:f}});e.io.stdout(y.output)}),c.command("load").argument("<name>","dataset name or id").requiredOption("--out <file>","JSONL file to write").option("--limit <n>","how many rows to keep after download",At).option("--timeout <ms>","how long to wait for the export",At).description("download live dataset rows into a JSONL file").action(async(m,b)=>{let{sourceRoot:h,client:f,projectId:y}=await Y(s(),e),B=await Eb(f,{sourceRoot:h,datasetName:m,outPath:Jr.resolve(b.out),...y===void 0?{}:{projectId:y},...b.limit===void 0?{}:{limit:b.limit},...b.timeout===void 0?{}:{timeoutMs:b.timeout}});e.io.stdout(B.output)}),c.command("upload").argument("<name>","dataset name or id").argument("<file>","JSON array, JSONL, or CSV file").description("append rows to a dataset").action(async(m,b)=>{let{sourceRoot:h,client:f,projectId:y}=await Y(s(),e),B=await Xb(f,{sourceRoot:h,datasetName:m,filePath:Jr.resolve(b),...y===void 0?{}:{projectId:y}});if(e.io.stdout(B.output),B.warning!==void 0)e.io.stderr(B.warning)});let u="pipeline name or id; required unless a TTY picker can choose among several",Z=t.command("pipeline").description("operate on a live pipeline in the selected project");Z.command("list").option("--limit <n>","maximum pipelines to list",At).description("list live pipelines in the selected project").action(async(m)=>{let{client:b,projectId:h,state:f}=await Y(s(),e);p(h,j);let y=await Qh({client:b,projectId:h,state:f,...m.limit===void 0?{}:{limit:m.limit}});e.io.stdout(y.output)}),Z.command("run").argument("[name]",u).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",At).description("start a run on a deployed pipeline").action(async(m,b)=>{let{client:h,state:f,projectId:y}=await Y(s(),e);p(y,j);let B=await Lh(h,{projectId:y,state:f,...m===void 0?{}:{pipeline:m},wait:b.wait,...b.timeout===void 0?{}:{timeoutMs:b.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(B.output),i.value=dd(B.outcome)}),Z.command("status").argument("[name]",u).description("report the latest run's state and item counts").action(async(m)=>{let{client:b,state:h,projectId:f}=await Y(s(),e);p(f,j);let y=await $h(b,{projectId:f,state:h,...m===void 0?{}:{pipeline:m},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(y.output),i.value=dd(y.outcome)}),Z.command("runs").argument("[name]",u).option("--limit <n>","how many runs to list",At).description("list recent runs").action(async(m,b)=>{let{client:h,state:f,projectId:y}=await Y(s(),e);p(y,j);let B=await Mh(h,{projectId:y,state:f,...m===void 0?{}:{pipeline:m},...b.limit===void 0?{}:{limit:b.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(B.output)}),Z.command("cost").argument("[name]",u).option("--item-limit <n>","cap how many items to price",At).description("forecast what a run of this pipeline would bill").action(async(m,b)=>{let{client:h,state:f,projectId:y}=await Y(s(),e);p(y,j);let B=await nW(h,{projectId:y,state:f,...m===void 0?{}:{pipeline:m},...b.itemLimit===void 0?{}:{itemLimit:b.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(B.output)}),Z.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(m)=>{let{client:b}=await Y(s(),e),h=await qh(b,{runId:m});e.io.stdout(h.output)}),Z.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",At).option("--failed","only report failed items",!1).description("report a run's items").action(async(m,b)=>{let{client:h}=await Y(s(),e),f=await eW(h,{runId:m,failedOnly:b.failed,...b.limit===void 0?{}:{limit:b.limit}});e.io.stdout(f.output),i.value=dd(f.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:m,client:b,projectId:h}=await Y(s(),e);p(h,j);let f=await wb(b,{sourceRoot:m,projectId:h});e.io.stdout(f.output)}),t.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",iS,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(m,b)=>{p(e.analytics,"Issue reporting requires CLI analytics.");let h=RW(s()),f=s().baseUrl??e.environment.POTATO_BASE_URL??Bt(e.environment)??ai;i.value=await oW({path:m,authoredBy:b.authoredBy,platform:new URL(f).origin,confirm:b.confirm,sourceRoot:h,cwd:process.cwd(),analytics:e.analytics,io:e.io})});let W=t.command("skill").description("discover bundled agent skills and install them into .agents/skills");return W.command("list").option("--json","print Skill Descriptors with their status as JSON",!1).description("list bundled skills as not-installed, current, or stale").action(async(m)=>{let b=await tt(s(),e.io);await UZ({sourceRoot:b,json:m.json,io:e.io})}),W.command("search").argument("<query>","text matched case-insensitively against id, name, description, and tags").option("--json","print matching Skill Descriptors with their status as JSON",!1).description("find bundled skills for a task").action(async(m,b)=>{let h=await tt(s(),e.io);await TZ({sourceRoot:h,query:m,json:b.json,io:e.io})}),W.command("install").argument("<skillId>","skill id from toloka skill list").option("-f, --force","replace an existing .agents/skills/<skillId> directory",!1).description("copy one bundled skill into .agents/skills/<skillId>").action(async(m,b)=>{let h=await tt(s(),e.io);await OZ({sourceRoot:h,skillId:m,force:b.force,io:e.io})}),{program:t,exitCode:i}}var oS=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},sS=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:i,resolve:n,reject:r}=Promise.withResolvers(),o="",s=()=>{process.stdin.off("data",I),process.stdin.off("end",g),process.stdin.off("error",l),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
264
264
  `)},g=()=>{a(),r(Error("Standard input closed before an API key was entered."))},l=(d)=>{a(),r(d)},I=(d)=>{for(let C of d){if(C==="\r"||C===`