@toloka-platform/sdk 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,7 +36,7 @@ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{l
36
36
  `),s=Math.min(o.length,n+Ew),a=[];for(let d=n;d<s;d++){let c=o[d];if(c.length>1024)continue;let I=up.test(c)?c.replace(up,"$1"):c;if(!I.match(/\S*Error: /)){for(let m of t){let p=m(I,e);if(p){r.push(p);let C=Nw(r);if(C){for(let h=a.length-1;h>=0;h--){let Z=a[h];if(Z.start+Z.length<=C.start)break;a.pop()}a.push(C)}break}}if(Yw(r,a)>=mp)break}}let l=[...a].sort((d,c)=>c.start-d.start),g=l[l.length-1];if(g){let d=pp(r,g);r.splice(g.start-d,d);for(let c of l)c.start-=d}for(let d of l)Tw(r,d);if(a.some((d)=>d.start===0&&r.length===d.length))Ow(r);return Uw(r)}}class xs{match(e){return Li(e)}coerce(e,t){let i=this.getStack(e),n=i===void 0?t.syntheticException?.stack:void 0,r=!!n;return{type:this.getType(e),value:this.getMessage(e,t),stack:i??n,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}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){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let i=e.stack;return typeof i=="string"&&i.length>0?i:void 0}catch{return}}}var _w=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Ss{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(_w);if(n)t=n[1],i=n[2];return[t,i]}}var hp=["fatal","error","warning","log","info","debug"];function Es(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 Ns{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:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(io(e))return e.constructor.name;let t="name"in e?e.name:void 0;return Vt(t)&&!dg(t)?t:"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=Es(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return Vt(e)&&!dg(e)&&hp.indexOf(e)>=0}getStack(e){try{if(Vt(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return Vt(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(Li(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class bp{match(e){return io(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Es(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Ts{match(e){return Ig(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Pg{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 Zp={MESSAGE:"$message",TIMESTAMP:"$timestamp"},L9=new Set([Zp.MESSAGE,Zp.TIMESTAMP]);var xg=(e)=>{if("flags"in e){let t=yp(e.flags),i=Wp(e.flags);return{...e,featureFlags:t,featureFlagPayloads:i}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([r,o])=>[r,ao(o)])),n=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,jw(r,o,i[r])]));return{...e,featureFlags:t,featureFlagPayloads:i,flags:n}}};function jw(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 yp=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,i])=>[t,so(i)]).filter(([,t])=>t!==void 0)),Wp=(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?ao(n):void 0]}))},so=(e)=>e===void 0?void 0:e.variant??e.enabled,ao=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Vp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],Dw=["$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","$referring_domain",...Vp,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],lo=(e,t=[])=>{let i={},n=(r)=>{if(e[r]!==void 0)i[r]=e[r]};return Dw.forEach(n),t.forEach(n),i};class Sg{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)}}function Eg(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Lw="NativeGzipValidationError",Qw=31,Kw=139,Mw=8,$w=(e)=>e.length>=2&&e[0]===Qw&&e[1]===Kw;var go,qw=()=>{if(go)return go;go=[];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;go[e]=t>>>0}return go},eF=(e)=>{let t=qw(),i=4294967295;for(let n=0;n<e.length;n++)i=t[(i^e[n])&255]^i>>>8;return(4294967295^i)>>>0},Ys=(e)=>{throw Yn(Lw,`Native gzip produced invalid output: ${e}`)},tF=async(e,t)=>{if(e.size<18)Ys("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!$w(i)||i[2]!==Mw)Ys("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());if(n.getUint32(0,!0)!==eF(t))Ys("invalid-crc");let r=t.length>>>0;if(n.getUint32(4,!0)!==r)Ys("invalid-size")};async function co(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(g)=>{try{await o.abort(g)}catch{}throw g}),a=new Response(r.readable).blob(),[l]=await Promise.all([a,s]);return await tF(l,n),l}catch(n){if(i?.rethrow)throw n;if(t)console.error("Failed to gzip compress data",n);return null}}class Rt extends Error{constructor(e,t,i,n){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=i,this.abortController=n,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return Rg(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=Yn("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((i,n)=>{this.responseBodyTimer=Se(()=>{this._bodyReadTimedOut=!0;let r=Yn("AbortError","Response body read timed out");n(r),this.cancelResponseBody(r)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(i){t=Promise.reject(i)}this.responseBodyTextPromise=Promise.race([t,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then((e)=>JSON.parse(e))}cancelResponseBody(e){if(clearTimeout(this.responseBodyTimer),!this.abortController.signal.aborted)this.abortController.abort(e);(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class ui extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var iF=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function Rp(e){if(e instanceof Rt){let t="";try{t=await e.text}catch{if(e.bodyReadTimedOut)t="<response body read timed out>"}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 nF(e){return typeof e=="object"&&(e instanceof Rt||Fp(e))}function Fp(e){return e instanceof ui}function rF(e){if(e instanceof Rt)return e.status===502||e.status===504;if(!(e instanceof ui))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Bp=10485760;function Gp(e){try{if(typeof e!="string")return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,ip);return new TextEncoder().encode(e).length}catch{return 0}}function Os(e){return typeof e=="object"&&e instanceof Rt&&e.status===413}function Xs(e){if(e instanceof Rt)return e.status===408||e.status===429||e.status>=500;return Fp(e)}function wp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ng="default";class Us{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ps([new xs,new Ns,new Ss,new Ts],Ap())}getEvaluationRuntime(){}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new pg,this._events=new Sg,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=Xm("[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=np(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:Xs},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=!Eg()||(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(it.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(it.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(it.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=this.mergeCommonEventProperties(t);if(iF(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=lo(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}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,{type:"required",consume:(n)=>n.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).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}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)l.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)l.evaluation_contexts=this.evaluationContexts;let g=this.getEvaluationRuntime();if(g)l.evaluation_runtime=g;let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,d,{type:"required",consume:(c)=>c.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:rF},this.featureFlagsRequestTimeoutMs).then((c)=>({success:!0,response:xg(c)})).catch((c)=>(this._events.emit("error",c),{success:!1,error:this.categorizeRequestError(c)}))}categorizeRequestError(e){if(e instanceof Rt)return{type:"api_error",statusCode:e.status};if(e instanceof ui){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=so(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 l=a.response;if(l.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(l.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:l?.requestId,quotaLimited:l.quotaLimited};return l}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,{type:"required",consume:(r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);return this._logger.error(s),this._events.emit("error",Error(o)),Promise.resolve(void 0)}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(it.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(it.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(it.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ng}persistedQueueKeyForRoute(e){return it.Queue}getActiveQueueRoutes(){return[Ng]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let r=this.prepareMessage(t,i);if(r=this.processBeforeEnqueue(r),r===null)return;r=this.normalizeMessage(r);let o=this.persistedQueueKeyForRoute(n??this.getQueueRouteKey(r)),s=this.getPersistedProperty(o)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:r}),this.setPersistedProperty(o,s),this._events.emit(e,r),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Se(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i,n){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 r=this.prepareMessage(t,i);if(r=this.processBeforeEnqueue(r),r===null)return;r=this.normalizeMessage(r);try{await this.sendBatch([r],void 0,n??this.getQueueRouteKey(r))}catch(o){this._events.emit("error",o)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=wp(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=vs(r.uuid,nt),r}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let i=t.toISOString(),n=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return n&&n.length>3?i.replace(/\.\d{3}Z$/,`.${n}Z`):i}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:Bg(),uuid:vs(t?.uuid,nt)};if(t?.disableGeoip??this.disableGeoip){if(!wp(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.flushAutomatic().catch(async(e)=>{await Rp(e)})}flushAutomatic(){return this.flush()}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(()=>wg([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),wg([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}compressPayload(e){return co(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,i=Ng){let n={api_key:this.apiKey,batch:e.map((l)=>{if(!l)return l;let g=this.normalizeTimestampForWire(l.timestamp);return g===l.timestamp?l:{...l,timestamp:g}}),sent_at:Bg()};if(this.historicalMigration)n.historical_migration=!0;let r=eo(n),o=`${this.host}${this.getBatchEndpointPath(i)}`,s=this.disableCompression?null:await this.compressPayload(r),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await this.fetchWithRetry(o,a,{type:"successful-write"},t)}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((d)=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let d=this.getPersistedProperty(i)||[],c=[...s],I=d.filter((m)=>{let p=m.message?.uuid,C=c.findIndex((h)=>h===m||typeof p=="string"&&p.length>0&&h.message?.uuid===p);if(C===-1)return!0;return c.splice(C,1),!1});this.setPersistedProperty(i,I),n=I,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},g={retryCheck:(d)=>{if(Os(d))return!1;return Xs(d)}};try{await this.sendBatch(a,g,e)}catch(d){if(Os(d)&&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(!(d instanceof ui))await l();throw this._events.emit("error",d),d}await l(),t.push(...a),o+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:i}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let n;try{n=JSON.stringify(i)}catch(g){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,g)),{kind:"too-large",measuredLocally:!0}}let r=Gp(n);if(r>Bp)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${r} bytes: the endpoint accepts at most ${Bp}`)),{kind:"too-large",measuredLocally:!0};let o=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,s=this.disableCompression?null:await this.compressPayload(n),a=s||n,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...s!==null&&{"Content-Encoding":"gzip"}},body:a};try{return await this.fetchWithRetry(o,l,{type:"successful-write"},{retryCheck:(g)=>{if(Os(g))return!1;if(g instanceof Rt&&g.retryAfterMs!==void 0)return!1;return Xs(g)}}),{kind:"ok"}}catch(g){if(Os(g))return{kind:"too-large"};if(Xs(g)){let d=g instanceof Rt?g.retryAfterMs:void 0;return{kind:"retry-later",error:g,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:g}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,i,n,r){let o=t.body?t.body:"",s=Gp(o),a={...this._retryOptions,...n},l=0;return await rp(async()=>{l++;let g=new AbortController,d=r??this.requestTimeout,c=Date.now()+d,I,m=new Promise((y,W)=>{I=Se(()=>{let u=Yn("AbortError",`Request timed out after ${d}ms`);W(u),g.abort(u)},d)}),p,C=!1,h,Z=()=>h??=(async()=>{try{await p?.body?.cancel()}catch{}})();try{let y;try{y=this.fetch(e,{signal:g.signal,...t})}catch(A){throw new ui(A)}y.then((A)=>{if(g.signal.aborted&&!C)Promise.resolve(A.body?.cancel()).catch(()=>{})}).catch(()=>{});try{p=await Promise.race([y,m]),C=!0}catch(A){throw new ui(A)}let W=t.mode==="no-cors",u=i.type==="successful-write"?300:400;if(!W&&(p.status<200||p.status>=u))throw new Rt(p,s,c,g);if(i.type==="successful-write"){try{await Promise.race([Z(),m])}catch{}return}try{return await Promise.race([i.consume(p),m])}catch(A){if(g.signal.aborted)throw new ui(A);throw A}}finally{if(clearTimeout(I),g.signal.aborted&&p)Z()}},{...a,retryCheck:(g)=>{let d=a.retryCheck(g);if(d&&l<=a.retryCount&&g instanceof Rt)g.cancelResponseBody();return d}})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;return Gg((async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let r=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===r){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!nF(n))throw n;await Rp(n)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}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 gF=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var k3=new RegExp(gF.source,"i"),Hp=/[a-z][a-z0-9+.-]{0,63}:\/\//i,x3=new RegExp(`^${Hp.source}`,"i"),S3=new RegExp(Hp.source,"gi");var vp=9223372036854776000,dF="9223372036854775808",cF=Object.prototype.propertyIsEnumerable;function IF(){return{ancestors:new WeakSet,remainingNodes:Wg}}function mi(e,t){try{return Pp(e,t,IF(),0)}catch{return[]}}function uF(e,t){let i=e.toString(),n=BigInt(dF);if(e>=n||e<-n)return t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i};return{intValue:i}}function Tg(e,t,i,n){if(i.remainingNodes<=0)return{stringValue:Hs};if(i.remainingNodes--,km(e))return{boolValue:e};if(typeof e=="bigint")return uF(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let r=BigInt(e).toString();if(e>=vp||e<-vp)return t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r};return{intValue:r}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Ii(e)};if(typeof e=="function")return{stringValue:tp};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(i.ancestors.has(e))return{stringValue:Vg};if(n>=yg)return{stringValue:Hs};if(e instanceof Date){let r=e.getTime(),o=Number.isFinite(r)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Ii(o):String(o)}}i.ancestors.add(e);try{try{let r=e.toJSON;if(typeof r=="function")return Tg(r.call(e),t,i,n+1)}catch{}if(dt(e))return{arrayValue:{values:mF(e,t,i,n+1)}};return{kvlistValue:{values:Pp(e,t,i,n+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Ii(String(e))}}function mF(e,t,i,n){let r=[],o=Math.min(e.length,Fs),s=0;for(;s<o&&i.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(to(a))continue;r.push(Tg(a,t,i,n))}catch{r.push({stringValue:Nn})}if(e.length>s)r.push({stringValue:Hs});return r}function Pp(e,t,i,n){let r=[];for(let o in e)if(cF.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(r.length>=Fs||i.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(cg(s)||ti(s))continue;r.push({key:Ii(o),value:Tg(s,t,i,n)})}catch{r.push({key:Ii(o),value:{stringValue:Nn}})}}return r}function Js(e,t,i){return{...Tn({},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}}var pF=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function _s(e,t){let i=Tn({},e),n={};for(let r of pF)if(Object.prototype.hasOwnProperty.call(i,r))n[r]=i[r],delete i[r];return[...mi(i,t),...mi(n,t)]}var CF={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}},M3=CF.info;class Io{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=Se(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){if(this._timer&&Date.now()+e<=this._firesAt)return;this.arm(e)}clear(){if(this._timer)clearTimeout(this._timer),this._timer=void 0}}var js=30000;function Ds(){return 0.75+Math.random()*0.25*2}var Xn=1;function zs(e,t,i,n){let r=Math.min(Math.max(0,t-1),6),o=e*2**r,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*i)}var bF="00000000000000000000000000000000",ZF=/^[0-9a-f]+$/;function kp(e,t,i){return typeof e=="string"&&e.length===t&&e!==i&&ZF.test(e)}function xp(e){return kp(e,32,bF)}function Sp(e){return kp(e,16,"0000000000000000")}var yF=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Yg(e){let t=VF(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:WF(t.flags)}}function WF(e){return 1&parseInt(e,16)?Ls:RF}function VF(e){if(typeof e!="string")return;let t=yF.exec(e.trim());if(!t)return;let[,i,n,r,o,s]=t;if(i==="ff")return;if(i==="00"&&s)return;if(!xp(n)||!Sp(r))return;return{version:i,traceId:n,spanId:r,flags:o}}var Ls="01",RF="00";var uo=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Qs(e){return String(e)+"000000"}function Og(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 Ep(e,t){for(let i=0;i<t.length;i++)if(e<=t[i])return i;return t.length}function Xg(e,t,i){return Js(e,t,i)}function Ug(e,t,i,n){return{resourceMetrics:[{resource:{attributes:_s(t)},scopeMetrics:[{scope:{name:i,version:n},metrics:e}]}]}}function Ks(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 Np=1;class Ms{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushTimer=new Io(()=>this.flush().catch((n)=>{this._logger.error("Metrics flush failed:",n)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new oo,this._consecutiveFlushFailures=0,this._flushJitter=Xn,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._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=Xn,this._flushTimer.clear(),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=Og(t.type,t.name,t.unit,i)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);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);let s=this._activeTraceContext();if(s)r.exemplar={...s,value:t.value,timeMs:Date.now()};this._armFlushTimer()}_activeTraceContext(){try{let e=Yg(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Ls)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_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(uo.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[Ep(t,uo)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let i=dt(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.pending)return;this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(zs(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,js),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),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;if(this._retryAfter.record(i),i.kind==="retry-later")this._consecutiveFlushFailures++,this._flushJitter=Ds();else this._consecutiveFlushFailures=0,this._flushJitter=Xn;if(this._flushTimer.pending)this._flushTimer.arm(this._nextFlushDelay());switch(i.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());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 Ug(this._buildMetrics(e),Xg(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Qs(Date.now()),i=new Map;for(let n of e.values()){let r=Og(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:Np,isMonotonic:!0,dataPoints:[]};else if(n.type==="gauge")o.gauge={dataPoints:[]};else o.histogram={aggregationTemporality:Np,dataPoints:[]};i.set(r,o)}let s=mi(n.attributes??{},this._logger),a=Qs(n.windowStartMs),l=BF(n.exemplar);if(n.type==="count"){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,asDouble:n.total??0,...l};o.sum.dataPoints.push(g)}else if(n.type==="gauge"){let g={attributes:s,timeUnixNano:t,asDouble:n.last??0,...l};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:uo,...l};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.exemplar=n.exemplar??i.exemplar,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}}}}function BF(e){if(!e)return{};return{exemplars:[{filteredAttributes:[],timeUnixNano:Qs(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}}var Op=require("fs"),Xp=require("readline"),$s=new Pg(25),Up=new Pg(20),Jg=7,xF=1000,SF=1e4;async function Jp(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"||YF(s)||OF(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(Up.get(r))continue;let o=t[r];if(!o)continue;o.sort((l,g)=>l-g);let s=UF(o);if(s.every((l)=>XF(r,l)))continue;let a=JF($s,r,{});n.push(EF(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)NF(e,$s);return $s.reduce(),e}function EF(e,t,i){return new Promise((n)=>{let r=Op.createReadStream(e),o=Xp.createInterface({input:r});function s(){r.destroy(),n()}let a=0,l=0,g=t[l];if(g===void 0)return void s();let d=g[0],c=g[1];function I(){Up.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",I),o.on("error",I),o.on("close",s),o.on("line",(m)=>{if(a++,a<d)return;if(i[a]=_F(m,0),a>=c){if(l===t.length-1){o.close(),o.removeAllListeners();return}l++;let p=t[l];if(p===void 0){o.close(),o.removeAllListeners();return}d=p[0],c=p[1]}})})}function NF(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;TF(i.lineno,i,n)}}function TF(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=_p(e);r<e;r++){let o=i[r];if(o===void 0)return void Tp(t);t.pre_context.push(o)}if(i[e]===void 0)return void Tp(t);t.context_line=i[e];let n=jp(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 Tp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function YF(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function OF(e){if(e.lineno!==void 0&&e.lineno>SF)return!0;if(e.colno!==void 0&&e.colno>xF)return!0;return!1}function XF(e,t){let i=$s.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 UF(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=Yp(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+Jg;else r.push(n),n=Yp(o);t++}return r}function Yp(e){return[_p(e),jp(e)]}function _p(e){return Math.max(1,e-Jg)}function jp(e){return e+Jg}function JF(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function _F(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 Un=require("path");function Dp(e=process.cwd()){let t=Un.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(Un.isAbsolute(o.filename))o.filename=i(Un.relative(n,i(o.filename)))}return r}}var zp="5.46.1";var ii={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Mi{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 Mi({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(ii.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(ii.QUOTA_LIMITED);if(t===void 0)r.push(ii.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 Lp(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 jF=60000,DF=1152921504606847000,zF=["is_not","is_set"];class Jn extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Jn.prototype)}}function $p(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class L extends Error{constructor(e){super(e);$p(this,L)}}class vt extends Error{constructor(e){super(e);$p(this,vt)}}class _g{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(l){if(l instanceof vt||l instanceof L)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${l}`))}}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:l,payload:g}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=l,g)n[a.key]=g}catch(l){if(l instanceof vt||l instanceof L)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${a.key}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${l}`));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 L("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let l=this.groupTypeMapping[String(a)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new L("Flag has unknown group type index");if(!(l 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 g=o[l];return await this.matchFeatureFlagProperties(e,n[l],g,t)}{let l=this.getBucketingValueForFlag(e,i,r);if(l===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 L(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,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 L("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new L(`Flag dependency property for '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new L(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new L(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let g=this.featureFlagsByKey[a];if(g)if(g.active)try{let d=await this.computeFlagValueLocally(g,i);n[a]=d}catch(d){throw new L(`Error evaluating flag dependency '${a}' for flag '${r}': ${d}`)}else n[a]=!1;else throw new L(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new L(`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:l,groupProperties:g}=n,d=!1,c;for(let I of o)try{let m=I.aggregation_group_type_index!==void 0?I.aggregation_group_type_index:s,p=i,C=t;if(m!==s){if(m!=null){let Z=this.groupTypeMapping[String(m)];if(!Z||!(Z in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${m} not available`));continue}if(!(Z in g)){d=!0;continue}p=g[Z],C=l[Z]}}let h=await this.isConditionMatch(e,C,I,p,n);if(h==="match"){let Z=I.variant,y=r.multivariate?.variants||[];c=Z&&y.some((W)=>W.key===Z)?Z:await this.getMatchingVariant(e,C)||!0;break}if(a&&h==="out_of_rollout_bound")return!1}catch(m){if(m instanceof vt)throw m;if(m instanceof L)d=!0;else throw m}if(c!==void 0)return c;if(d)throw new L("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 l=a.type,g=!1;if(l==="cohort"){let d=await eC(a,n,this.cohorts,this.debugMode,(c)=>this.evaluateFlagDependency(c,n,r));g=a.operator==="not_in"?!d:d}else g=l==="flag"?await this.evaluateFlagDependency(a,n,r):qp(a,n,s);if(!g)return"no_match"}if(o==null)return"match"}if(o!=null&&await Qp(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await Qp(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(jF,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 Jn(`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 Jn(`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 Jn(`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 Jn)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=Se(()=>{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 Qp(e,t,i=""){let n=await Lp(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/DF}function qp(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 L(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!zF.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(g,d){if(Array.isArray(g))return g.map((c)=>String(c).toLowerCase()).includes(String(d).toLowerCase());return String(g).toLowerCase()===String(d).toLowerCase()}function l(g,d,c){if(c==="gt")return g>d;if(c==="gte")return g>=d;if(c==="lt")return g<d;if(c==="lte")return g<=d;throw Error(`Invalid operator: ${c}`)}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 Kp(String(r))&&String(s).match(String(r))!==null;case"not_regex":return Kp(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let g=typeof r=="number"?r:parseFloat(String(r)),d;if(d=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(g)&&Number.isFinite(d))return l(d,g,o);return l(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new L("Date operations cannot be performed on boolean values");let g=$F(String(r));if(g==null)g=Mp(r);if(g==null)throw new L(`Invalid date: ${r}`);let d=Mp(s);if(["is_date_before"].includes(o))return d<g;return d>g}case"semver_eq":return ct(Fe(String(s)),Fe(String(r)))===0;case"semver_neq":return ct(Fe(String(s)),Fe(String(r)))!==0;case"semver_gt":return ct(Fe(String(s)),Fe(String(r)))>0;case"semver_gte":return ct(Fe(String(s)),Fe(String(r)))>=0;case"semver_lt":return ct(Fe(String(s)),Fe(String(r)))<0;case"semver_lte":return ct(Fe(String(s)),Fe(String(r)))<=0;case"semver_tilde":{let g=Fe(String(s)),{lower:d,upper:c}=QF(String(r));return ct(g,d)>=0&&ct(g,c)<0}case"semver_caret":{let g=Fe(String(s)),{lower:d,upper:c}=KF(String(r));return ct(g,d)>=0&&ct(g,c)<0}case"semver_wildcard":{let g=Fe(String(s)),{lower:d,upper:c}=MF(String(r));return ct(g,d)>=0&&ct(g,c)<0}default:throw new L(`Unknown operator: ${o}`)}}function LF(e,t){if(!(e in t))throw new vt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function eC(e,t,i,n=!1,r){let o=String(e.value);LF(o,i);let s=i[o];return tC(s,t,i,n,r)}async function tC(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 l of s)try{let g=await tC(l,t,i,n,r);if(o==="AND"){if(!g)return!1}else if(g)return!0}catch(g){if(g instanceof vt)throw g;if(g instanceof L){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new L("Can't match cohort without a given cohort property value");return o==="AND"}for(let l of s)try{let g;if(l.type==="cohort")g=await eC(l,t,i,n,r);else if(l.type==="flag"){if(!r)throw new L(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await r(l)}else g=qp(l,t);let d=l.negation||!1;if(o==="AND"){if(!g&&!d)return!1;if(g&&d)return!1}else{if(g&&!d)return!0;if(!g&&d)return!0}}catch(g){if(g instanceof vt)throw g;if(g instanceof L){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new L("can't match cohort without a given cohort property value");return o==="AND"}function Kp(e){try{return new RegExp(e),!0}catch(t){return!1}}function iC(e,t){if(!/^\d+$/.test(e))throw new L(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new L(`Invalid semver: ${t}`);return parseInt(e,10)}function Fe(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new L(`Invalid semver: ${e}`);let n=i.split("."),r=(l)=>{if(l===void 0||l==="")return 0;return iC(l,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function ct(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 QF(e){let t=Fe(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function KF(e){let t=Fe(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 MF(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new L(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(l)=>{try{return iC(l,e)}catch{throw new L(`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 l=r(n[1]);s=[o,l,0],a=[o,l+1,0]}return{lower:s,upper:a}}function Mp(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 L(`${e} is in an invalid date format`)}throw new L(`The date provided ${e} must be a string, number, or date object`)}function $F(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 qF(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 nC(e,t){globalThis.process?.on("uncaughtException",qF(e,t))}function rC(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var eH=2000;class Pt{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new mg({...Nm(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return ys(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())nC(this.onException.bind(this),this.onFatalError.bind(this)),rC(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Pt.isPreviouslyCapturedError(e)){let i=await Pt.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(eH),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class jg{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function tH(e){return e==="v0"||e==="v1"}function oC(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return tH(e)?e:"v0"}var mo="analytics",po="ai";function sC(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class _n extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super(_n.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 Dg(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 iH(e){return typeof e=="string"?e:void 0}var nH=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Dg},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Dg},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Dg},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:iH}],rH=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function oH(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sH(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 aC(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function aH(e){let i={...oH(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of nH)if(o in i){let l=a(i[o]);if(l!==void 0)n[s]=l;delete i[o]}let r={};for(let{property:o,field:s}of rH)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,aC(i,"$set",e.$set),aC(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:sH(e.timestamp),...r,options:n,properties:i}}function lC(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(aH)};if(i)n.historical_migration=!0;return n}var lH="/i/v1/analytics/events",gH=30000,dH=new Set([408,500,502,503,504]);class zg{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??gH,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>Se(n,i))),this.generateRequestId=t.generateRequestId??nt,this.compress=t.compress??co}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=lC(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${lH}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let l=1;l<=a;l++){let g=l===a,d=eo({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),c;try{c=await this.sendOnce(r,d,l,t)}catch(h){if(g)return this.surfaceBatchFailure(t,o,s,h);await this.sleep(this.backoffDelay(l));continue}let{status:I}=c;if(I<200||I>=300){if(!g&&dH.has(I)){let Z=this.parseRetryAfter(c);await this.cancelBody(c),await this.sleep(this.backoffDelay(l,Z));continue}let h=await this.buildHttpError(c,I);return this.surfaceBatchFailure(t,o,s,h)}let m;try{m=await this.parseResponse(c)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${I} response body`))}let p=this.classify(s,m,o);if(p.length===0)return this.surfacePartialDrops(t,o);if(g)return void this.onError(new _n({requestId:t,drops:o,retryExhausted:p.map((h)=>h.uuid)}));s=p;let C=this.parseRetryAfter(c);await this.sleep(this.backoffDelay(l,C))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let l=await this.compress(t,this.config.isDebug);if(l!==null)o=l,r["Content-Encoding"]="gzip"}let s=new AbortController,a=Se(()=>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 _n({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new _n({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var cH=100,gC=30000,IH=50000,uH=50,mH=500,pH="https://us.i.posthog.com",dC=new Set;function qs(e,t){if(dC.has(e))return;dC.add(e),console.warn(`[PostHog] ${t}`)}function CH(e){return typeof e=="string"?e.trim():""}function AH(e){return(typeof e=="string"?e.trim():"")||void 0}function fH(e){return(typeof e=="string"?e.trim():"")||pH}function hH(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function bH(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 Lg extends Us{constructor(e,t={}){let i=CH(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:fH(t.host),personalApiKey:AH(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new jg,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=oC(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,cH):gC,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 _g({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 Pt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||IH}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??mH,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??uH;this._waitUntilCycle.timer=Se(()=>{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"&&sC(e)?po:mo}persistedQueueKeyForRoute(e){return e===po?it.AiQueue:it.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[mo,po]:[mo]}async sendBatch(e,t,i=mo){if(this.captureMode!=="v1"||i===po)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 zg({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 zp}get metrics(){if(!this._metrics)this._metrics=new Ms(this,Ks(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 l={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},g={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,g,l):this.enqueue(e,g,l)}).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,g={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,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,g={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,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=hH(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=gC){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 b=this._flagOverrides[e];if(b===void 0)return;let R=this._payloadOverrides?.[e];return{key:e,enabled:b!==!1,variant:typeof b=="string"?b:void 0,payload:R}}let{groups:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=i,d=this.addLocalPersonAndGroupProperties(t,o,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let I,m=!1,p,C,h,Z,y,W,u;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[e];if(b)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,c,{matchValue:n});if(R){m=!0;let S=R.value;Z=b.id,W="Evaluated locally",u=b.has_experiment,I={key:e,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof vt||R instanceof L)this._logger?.info(`${R.name} when computing flag locally: ${e}: ${R.message}`);else throw R}}if(!m&&!a){let b=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,s,[e]);if(b===void 0)h=ii.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=b.minimalFlagCalledEvents===!0,p=b.requestId,C=b.evaluatedAt;let R=[];if(b.errorsWhileComputingFlags)R.push(ii.ERRORS_WHILE_COMPUTING);if(b.quotaLimited?.includes("feature_flags"))R.push(ii.QUOTA_LIMITED);let S=b.flags[e];if(S===void 0)R.push(ii.FLAG_MISSING);else{Z=S.metadata?.id,y=S.metadata?.version,W=S.reason?.description??S.reason?.code,u=S.metadata?.has_experiment;let E;if(S.metadata?.payload!==void 0)try{E=JSON.parse(S.metadata.payload)}catch{E=S.metadata.payload}I={key:e,enabled:S.enabled,variant:S.variant,payload:E}}if(R.length>0)h=R.join(",")}}if(r){let b=I===void 0?void 0:I.enabled===!1?!1:I.variant??!0,R={$feature_flag:e,$feature_flag_response:b,$feature_flag_id:Z,$feature_flag_version:y,$feature_flag_reason:W,locally_evaluated:m,[`$feature/${e}`]:b,$feature_flag_request_id:p,$feature_flag_evaluated_at:m?Date.now():C};if(u!==void 0)R.$feature_flag_has_experiment=u;if(m&&this.featureFlagsPoller){let S=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(S!==void 0)R.$feature_flag_definitions_loaded_at=S}if(h)R.$feature_flag_error=h;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:b,groups:o,disableGeoip:s,properties:R})}if(I!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)I={...I,payload:this._payloadOverrides[e]};return I}async getFeatureFlag(e,t,i){qs("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(qs("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){qs("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:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let I=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),m={},p={},C=!0;if(I)m=I.response,p=I.payloads,C=I.fallbackToFlags;if(C&&!a){let h=await super.getFeatureFlagsAndPayloadsStateless(c.distinctId,c.groups,l,g,o,s);m={...m,...h.flags||{}},p={...p,...h.payloads||{}}}if(this._flagOverrides!==void 0)m={...m,...this._flagOverrides};if(this._payloadOverrides!==void 0)p={...p,...this._payloadOverrides};return{featureFlags:m,featureFlagPayloads:p}}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 Mi({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Mi({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let I={},m,p,C=!1,h=!1,Z=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),y=new Set;if(Z)for(let[u,A]of Object.entries(Z.response)){let b=this.featureFlagsPoller?.featureFlagsByKey[u];I[u]={key:u,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:Z.payloads[u],id:b?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:b?.has_experiment},y.add(u)}if((Z?Z.fallbackToFlags:!0)&&!a){let u=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,o,s);if(u){this._minimalFlagCalledEvents=u.minimalFlagCalledEvents===!0,m=u.requestId,p=u.evaluatedAt,C=Boolean(u.errorsWhileComputingFlags),h=Array.isArray(u.quotaLimited)&&u.quotaLimited.includes("feature_flags");for(let[A,b]of Object.entries(u.flags)){if(y.has(A))continue;let R;if(b.metadata?.payload!==void 0)try{R=JSON.parse(b.metadata.payload)}catch{R=b.metadata.payload}I[A]={key:A,enabled:b.enabled,variant:b.variant,payload:R,id:b.metadata?.id,version:b.metadata?.version,reason:b.reason?.description??b.reason?.code,locallyEvaluated:!1,hasExperiment:b.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[u,A]of Object.entries(this._flagOverrides)){if(A===void 0){delete I[u];continue}let b=I[u];I[u]={key:u,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:b?.payload,id:b?.id,version:b?.version,reason:b?.reason,locallyEvaluated:b?.locallyEvaluated??!1,hasExperiment:b?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[u,A]of Object.entries(this._payloadOverrides)){let b=I[u];if(b)I[u]={...b,payload:A}}return new Mi({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:I,requestId:m,evaluatedAt:p,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:C,quotaLimited:h})}_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(([g],[d])=>g<d?-1:g>d?1:0))}`:"",l=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(l);else this.distinctIdHasSentFlagCalls[t]=new Set([l]);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)=>Se(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=Se(()=>{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(xm(o)&&t&&r in t){let s={};for(let[a,l]of Object.entries(o))s[String(a)]=String(l);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 l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,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(!Pt.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(Pt.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(!Pt.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(Pt.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:l,disableGeoip:g,uuid:d}=e,c=this.context?.get(),I=t.includeContextProperties??!0,m=i||c?.distinctId,p=I?{...this.props,...c?.properties||{},...r||{}}:{...r||{}};if(!m)m=nt(),p.$process_person_profile=!1;if(I&&c?.sessionId&&!p.$session_id)p.$session_id=c.sessionId;let C=this._shouldSendMinimalFlagCalledEvent(n,p)?lo(p):p,h=this._runBeforeSend({distinctId:m,event:n,properties:C,groups:o,flags:s,sendFeatureFlags:a,timestamp:l,disableGeoip:g,uuid:d});if(!h)return Promise.reject(null);let Z=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){qs("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 y=typeof a=="object"?a:void 0,W=await this.getFeatureFlagsForEvent(h.distinctId,o,g,y);return bH(W)}return{}}).catch(()=>({})).then((y)=>{let W=h.groups||o;return{...y,...h.properties||{},...W!==void 0&&Object.keys(W).length>0?{$groups:W}:{}}});if(h.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof Z.$raw_user_agent=="string"){if(Em(Z.$raw_user_agent,this.options.custom_blocked_useragents||[]))h.event="$bot_pageview",Z.$browser_type="bot"}return{distinctId:h.distinctId,event:h.event,properties:Z,options:{timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.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 cC=require("async_hooks");class Qg{constructor(){this.storage=new cC.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 ZH(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 l=s.tags[IC.POSTHOG_ID_TAG];if(l===void 0)return s;let g=e.options.host??"https://us.i.posthog.com",d=new URL(`/project/${e.apiKey}/person/${l}`,g).toString();s.tags["PostHog Person URL"]=d;let c=s.exception?.values||[],I=c.map((p)=>({...p,stacktrace:p.stacktrace?{...p.stacktrace,type:"raw",frames:(p.stacktrace.frames||[]).map((C)=>({...C,platform:"node:javascript"}))}:void 0})),m={$exception_message:c[0]?.value||s.message,$exception_type:c[0]?.type,$exception_level:s.level,$exception_list:I,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:c[0]?.value||s.message,$sentry_exception_type:c[0]?.type,$sentry_tags:s.tags};if(t&&i)m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(o)e.capture({event:"$exception",distinctId:l,properties:m});return s}}class IC{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(ZH(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class Kg extends Lg{getLibraryId(){return"posthog-node"}initializeContext(){return new Qg}createErrorPropertiesBuilder(){return new Ps([new bp,new xs,new Ns,new Ss,new Ts],fp("node:javascript",Ip),[Hm(),Jp,Dp()])}}class K extends Error{code;status;body;requestId;constructor(e,t,i,n,r){super(e);this.name="PotatoApiError",this.code=t,this.status=i,this.body=n,this.requestId=r}static fromResponse(e,t,i){let n=i===void 0?"":` (request id: ${i})`;return new K(`Potato API request failed with status ${e}${n}`,"http",e,t,i)}static waitTimeout(e){return new K(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class $i extends Error{code="invalid_pipeline_graph";issues;constructor(e,t){super(e);this.name="PipelineGraphValidationError",this.issues=t}static fromIssues(e){let t=e.map(({path:i,reason:n})=>`- ${i}: ${n}`).join(`
37
37
  `);return new $i(`Pipeline graph validation failed
38
38
  ${t}`,e)}}var Je=require("fs/promises"),CC=require("os"),qi=require("path");class k extends Error{hint;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause});this.name="TolokaCliError",this.hint=t.hint}}function f(e,t,i){if(!e)throw new k(t,i)}var uC=(e)=>("disabled"in e)?void 0:`Hint: ${e.description}`,Y={description:"This looks like a defect in the CLI or the platform. Write a report as the toloka-report-issue skill describes, then send it with toloka report <report.md>."},ni={description:"Retry the command; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>."},He={description:"Reinstall @toloka-platform/sdk to restore the bundled files."};class Co extends k{constructor(e,t){super(e,t);this.name="CredentialsError"}}var AC=(e)=>e.HOME??CC.homedir(),yH=(e)=>e.XDG_CONFIG_HOME??qi.join(AC(e),".config"),It=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??qi.join(yH(e),"toloka","credentials.json"),fC=(e=process.env)=>qi.join(AC(e),".toloka","credentials.json"),ta=(e=process.env)=>qi.dirname(It(e)),mC=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},kt=(e)=>{let t=mC(e.trim());try{let i=new URL(t);return i.hash="",i.search="",mC(i.toString())}catch{return t}},ea=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,WH=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let i=Reflect.get(e,"name");if(i!==void 0&&typeof i!=="string")return;return i===void 0?{id:t}:{id:t,name:i}},VH=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[i,n]of Object.entries(e)){if(i.length===0)return;let r=WH(n);if(r===void 0)return;Object.defineProperty(t,i,{value:r,writable:!0,enumerable:!0,configurable:!0})}return t},RH=(e,t)=>{let i=VH(e);if(i===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(i,t))return;return{current:t,projects:i}}if(t!==void 0)return;return Object.keys(i).length===0?{}:{projects:i}},BH=(e)=>{let t=ea(e,"baseUrl"),i=ea(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(i!==void 0&&(typeof i!=="string"||i.length===0))return;let n=i===void 0?{baseUrl:t}:{baseUrl:t,apiKey:i},r=ea(e,"current"),o=ea(e,"projects");if(r===void 0&&o===void 0)return n;let s=RH(o,r);if(s===void 0)return;return{...n,...s}};async function Ao(e){let t;try{t=await Je.readFile(e,"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return"missing";return"invalid"}try{let i=BH(JSON.parse(t));return i===void 0?"invalid":{credentials:i}}catch{return"invalid"}}async function Mg(e=process.env){let t=It(e),i=await Ao(t);if(i!=="missing"){if(i==="invalid")throw new Co(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:i.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let n=fC(e),r=await Ao(n);if(r==="missing")return;if(r==="invalid")throw new Co(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:r.credentials,path:n,legacy:!0}}async function jn(e,t){try{return{found:await Mg(e)}}catch(i){if(!(i instanceof Co)||t===void 0)throw i;return{found:void 0,warning:i.message}}}async function hC(e=process.env){return(await Mg(e))?.credentials}async function pi(e=process.env){let t=await Mg(e);if(t!==void 0)return t;throw new Co(`No stored credentials found at ${It(e)}. Run toloka login.`,{hint:{disabled:!0}})}var GH=(e)=>{let t=e.projects,i=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.current===void 0?{}:{current:e.current},...i?{projects:t}:{}}},pC=async(e)=>{try{let t=await Je.lstat(e);f(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`,{hint:{description:"Replace the symbolic link with a regular file or directory, then retry."}})}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function ri(e){let t=qi.dirname(e);await pC(t),await pC(e),await Je.mkdir(t,{recursive:!0,mode:448}),await Je.chmod(t,448)}async function fo(e,t=process.env){let i=It(t);return await ri(i),await Je.writeFile(i,`${JSON.stringify(GH(e),null,2)}
39
- `,{mode:384}),await Je.chmod(i,384),i}var wH=async(e)=>{try{return await Je.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},$g=(e=process.env)=>[It(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[fC(e)]:[]];async function bC(e=process.env){let t=[];for(let i of $g(e)){if(!await wH(i))continue;await Je.rm(i,{force:!0}),t.push(i)}return t}var FH=16,ZC=(e)=>e.length>FH?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var ut=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},Dn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var qg={name:"@toloka-platform/sdk",version:"0.22.0",private:!1,description:"Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","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","generate:check":"bun ./scripts/check-generated-client.ts","docs:generate":"bun ./scripts/generate-docs-reference.ts","docs:check":"bun ./scripts/generate-docs-reference.ts --check",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:"tsrs --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.5",ajv:"8.18.0","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:"8.40.0",playwright:"1.63.0",typescript:"7.1.0-beta",vitest:"5.0.5",yaml:"2.9.0"},peerDependencies:{playwright:">=1.63.0 <2",vitest:">=4.1.0 <6"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:">=1.4.0"},tolokaBuild:{commit:"6aaf74ca79d5f9ceda49959d27ec565eb6c37159"}};var Ee=qg.name,pe=qg.version,ed=(e)=>{let t=/^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/u.exec(e);if(t===null)return;let[,i,n,r,o]=t;return[Number(i),Number(n),Number(r),o===void 0?Number.POSITIVE_INFINITY:Number(o)]},yC=(e)=>{let t=ed(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},td=(e,t)=>{let i=ed(e),n=ed(t);if(i===void 0||n===void 0)return;let r=Math.max(i.length,n.length);for(let o=0;o<r;o+=1){let s=i[o]??0,a=n[o]??0;if(s<a)return-1;if(s>a)return 1}return 0};var en=(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},vH=(e)=>{if(e.code==="wait_timeout")return"Hint: The job is still running. Check it later with its status command; commands that accept --timeout can wait longer.";if(e.status===401||e.status===403)return"Hint: Run toloka whoami to see which key and platform are in use; toloka login stores a new key.";if(e.status===404)return"Hint: Check the id against toloka project current and the matching list command; ids belong to one project on one platform.";if(e.status===429)return"Hint: The platform is rate limiting this key; wait a moment and retry.";if(e.status===503&&e.body==="Tunnel unavailable; the request was not sent")return"Hint: The sandbox lost its connection to the platform (usually a platform restart) and it was not restored within 90 seconds; the request was not sent. Retry in a minute.";if(e.status!==void 0&&e.status>=500)return"Hint: The platform failed to handle the request. Retry; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>.";return},WC=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
39
+ `,{mode:384}),await Je.chmod(i,384),i}var wH=async(e)=>{try{return await Je.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},$g=(e=process.env)=>[It(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[fC(e)]:[]];async function bC(e=process.env){let t=[];for(let i of $g(e)){if(!await wH(i))continue;await Je.rm(i,{force:!0}),t.push(i)}return t}var FH=16,ZC=(e)=>e.length>FH?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var ut=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},Dn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var qg={name:"@toloka-platform/sdk",version:"0.24.0",private:!1,description:"Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","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","generate:check":"bun ./scripts/check-generated-client.ts","docs:generate":"bun ./scripts/generate-docs-reference.ts","docs:check":"bun ./scripts/generate-docs-reference.ts --check",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:"tsrs --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.5",ajv:"8.18.0","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:"8.40.0",playwright:"1.63.0",typescript:"7.1.0-beta",vitest:"5.0.5",yaml:"2.9.0"},peerDependencies:{playwright:">=1.63.0 <2",vitest:">=4.1.0 <6"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:">=1.4.0"},tolokaBuild:{commit:"c1ddaeeb736da2435326b4454cebf8bf8da74ff1"}};var Ee=qg.name,pe=qg.version,ed=(e)=>{let t=/^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/u.exec(e);if(t===null)return;let[,i,n,r,o]=t;return[Number(i),Number(n),Number(r),o===void 0?Number.POSITIVE_INFINITY:Number(o)]},yC=(e)=>{let t=ed(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},td=(e,t)=>{let i=ed(e),n=ed(t);if(i===void 0||n===void 0)return;let r=Math.max(i.length,n.length);for(let o=0;o<r;o+=1){let s=i[o]??0,a=n[o]??0;if(s<a)return-1;if(s>a)return 1}return 0};var en=(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},vH=(e)=>{if(e.code==="wait_timeout")return"Hint: The job is still running. Check it later with its status command; commands that accept --timeout can wait longer.";if(e.status===401||e.status===403)return"Hint: Run toloka whoami to see which key and platform are in use; toloka login stores a new key.";if(e.status===404)return"Hint: Check the id against toloka project current and the matching list command; ids belong to one project on one platform.";if(e.status===429)return"Hint: The platform is rate limiting this key; wait a moment and retry.";if(e.status===503&&e.body==="Tunnel unavailable; the request was not sent")return"Hint: The sandbox lost its connection to the platform (usually a platform restart) and it was not restored within 90 seconds; the request was not sent. Retry in a minute.";if(e.status!==void 0&&e.status>=500)return"Hint: The platform failed to handle the request. Retry; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>.";return},WC=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
40
40
  `),zn=(e)=>{if(e instanceof K)return e;if(e instanceof AggregateError)for(let t of e.errors){let i=zn(t);if(i!==void 0)return i}return e instanceof Error?zn(e.cause):void 0},Ci=(e)=>{if(e instanceof k){let t=zn(e.cause),i=t===void 0?[]:t.message===e.message?[en(t)]:[t.message,en(t)];return WC([e.message,...i,uC(e.hint)])}if(e instanceof K)return WC([e.message,en(e),vH(e)]);return e instanceof Error?e.message:String(e)};var PH="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",kH="https://eu.posthog.com",xH={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0};function SH(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(Dn(t))return!1;if(ut(t))return!0;if(ut(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(ut(e.CI??process.env.CI))return!1;if(ut(process.env.VITEST))return!1;return!0}var EH={project:{list:!0,add:!0,switch:!0,current:!0,remove:!0,create:!0},pipeline:{list:!0,run:!0,status:!0,runs:!0,cost:!0,cancel:!0,results:!0},dataset:{list:!0,create:!0,fields:!0,load:!0,upload:!0},"delivery-order":{list:!0},audience:{specialization:{list:!0}},training:{list:!0,get:!0,create:!0,update:!0,cost:!0,run:!0,runs:!0,status:!0,resume:!0,cancel:!0,metrics:!0,logs:!0},"batch-inference":{run:!0,list:!0,status:!0,confirm:!0,resume:!0,cancel:!0},"base-model":{list:!0,get:!0},"generation-model":{list:!0},model:{list:!0,get:!0,versions:!0,create:!0,archive:!0,version:{download:!0}},secret:{set:!0},skill:{list:!0,search:!0,install:!0},config:{get:!0,set:!0}},NH={apply:!0,check:!0,"auth-status":!0,config:!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},RC=(e)=>{let t=e[0];if(t===void 0)return"help";let i=EH[t];if(i===void 0)return NH[t]===!0?t:"unknown";let n=e[1],r=n===void 0?void 0:i[n];if(r===void 0)return t;if(r===!0)return`${t} ${n}`;let o=e[2];return o!==void 0&&r[o]===!0?`${t} ${n} ${o}`:`${t} ${n}`};function na(e){if(e.includes("-v")||e.includes("--version"))return"version";let t=[];for(let i=0;i<e.length;i+=1){let n=e[i];if(n===void 0)continue;if(n==="--help"||n==="-h")break;if(n.startsWith("-")){if(xH[n]===!0)i+=1;continue}t.push(n)}return RC(t)}function TH(e){if(e===void 0)return{error_code:"command_failed"};let t=zn(e);if(t!==void 0)return{error_code:t.code};if(e instanceof $i)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var YH=(e)=>{let t=zn(e);return t===void 0?{}:{status_code:t.status,request_id:t.requestId}},OH=(e)=>ia.join(ia.dirname(It(e)),"anonymous-id"),XH=async(e)=>{let t=OH(e);await ri(t);try{let n=(await tn.readFile(t,"utf8")).trim();if(n.length>0)return await tn.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let i=VC.randomUUID();return await tn.writeFile(t,`${i}
41
41
  `,{mode:384}),await tn.chmod(t,384),i},UH=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){f(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}})},async shutdown(){}});function BC(e){let{environment:t}=e;if(e.client===void 0&&!SH(t))return UH();let{client:i,distinctId:n}=e,r,o=[],s=(d)=>{o.push(d)};i?.on?.("error",s);let a=async()=>{if(i!==void 0&&n!==void 0)return;if(i===void 0){let d=new Kg(PH,{host:kH,flushAt:1,flushInterval:0});d.on("error",s),i=d}n??=await XH(t)},l=()=>({sdk_version:pe,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),g=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(d){g=g.then(()=>{if(i===void 0||n===void 0)return;if(r===d.id)return;if(r=d.id,n!==d.id)i.alias({distinctId:d.id,alias:n});n=d.id}).catch(()=>{})},captureCommand(d){g=g.then(()=>{if(i===void 0||n===void 0)return;let c=l(),I=RC(d.command.split(" "));if(d.outcome==="failed"){let m=TH(d.error),p=YH(d.error);if(d.error!==void 0){let C=new k(`CLI command failed: ${m.error_code}`,{hint:{disabled:!0}});C.name="PotatoCliError",i.captureException(C,n,{...c,command:I,duration_ms:d.durationMs,exit_code:d.exitCode,$process_person_profile:!1,$geoip_disable:!0,...m,...p})}i.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...c,command:I,duration_ms:d.durationMs,exit_code:d.exitCode,...m,...p}});return}i.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...c,command:I,duration_ms:d.durationMs,exit_code:d.exitCode,outcome:d.outcome}})}).catch(()=>{})},submitIssueReport(d){let c=g.then(async()=>{f(i&&n,"PostHog issue reporting could not be initialized.",{hint:{description:"Set TOLOKA_TELEMETRY=1 and check that this machine can reach PostHog, then retry."}}),o.length=0,i.capture({distinctId:n,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...l(),report_id:d.reportId,report_text:d.reportText,report_length_bytes:new TextEncoder().encode(d.reportText).length,authored_by:d.authoredBy,platform:d.platform,$process_person_profile:!1}}),await i.flush();let I=o[0];if(o.length=0,I!==void 0)throw I});return g=c.catch(()=>{}),c},async shutdown(){try{await g,await i?.shutdown(2000)}catch{}}}}var wr=require("crypto"),ml=require("child_process"),zo=require("events"),ai=require("fs"),ie=require("fs/promises"),We=require("path"),pl=require("stream"),wZ=require("stream/promises");var Zo=require("fs"),rn=require("path");var nn=()=>Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0,ho=(e,t=nn())=>t?{...e,BUN_BE_BUN:"1"}:e;var GC=rn.join("bin","toloka.js"),wC=(e)=>{try{return Zo.realpathSync(e)}catch{return e}},bo=(e)=>{let t=rn.join(e,GC);if(Zo.existsSync(t))return t;let i=rn.dirname(e);return i===e?void 0:bo(i)},FC=(e=process.argv[1])=>(e===void 0?void 0:bo(rn.dirname(wC(e))))??bo(process.cwd()),JH=(e=process.argv[1])=>{let t=e===void 0?void 0:wC(e);if(t!==void 0&&Zo.existsSync(t)&&bo(rn.dirname(t))!==void 0)return t;let i=bo(process.cwd());return f(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${GC} 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.`,{hint:{disabled:!0}}),i},ra=(e,t,i={})=>{let n=i.executable??process.execPath;if(!(i.native??nn()))return{executable:i.executable??(Reflect.get(process.versions,"bun")?process.execPath:"bun"),args:[JH(i.runtimeEntry),...e],environment:t};let r={...t};return delete r.BUN_BE_BUN,{executable:n,args:[...e],environment:r}};var Qn=require("fs/promises"),HC=require("path");var Ln="auto-update",vC={autoUpdate:!0};class oa extends k{constructor(e,t){super(e,t);this.name="SettingsError"}}var PC=(e=process.env)=>HC.join(ta(e),"settings.json"),_H=(e)=>{let t=typeof e==="object"&&e!==null?Reflect.get(e,"autoUpdate"):void 0;if(typeof t!=="boolean")return vC;return{autoUpdate:t}};async function yo(e=process.env){try{return _H(JSON.parse(await Qn.readFile(PC(e),"utf8")))}catch{return vC}}async function jH(e,t=process.env){let i=PC(t);return await ri(i),await Qn.writeFile(i,`${JSON.stringify({autoUpdate:e.autoUpdate},null,2)}
42
42
  `,{mode:384}),await Qn.chmod(i,384),i}var DH=(e)=>{if(ut(e))return!0;if(Dn(e))return!1;throw new oa(`Expected a boolean (true or false), got ${JSON.stringify(e)}.`,{hint:{description:"Run toloka config set auto-update true or false."}})},zH=(e)=>`${Ln}=${e.autoUpdate}`,id=(e,t)=>{if(t===void 0||t.length===0)return{output:zH(e)};if(t!==Ln)throw new oa(`Unknown setting "${t}". Known settings: ${Ln}.`,{hint:{disabled:!0}});return{output:String(e.autoUpdate)}};async function kC(e,t,i){if(t!==Ln)throw new oa(`Unknown setting "${t}". Known settings: ${Ln}.`,{hint:{disabled:!0}});let n={autoUpdate:DH(i)};return await jH(n,e),{settings:n,output:`Set ${Ln} to ${n.autoUpdate}.`}}var bZ=require("fs"),ZZ=require("child_process"),yZ=require("module"),WZ=require("events"),Oi=require("fs/promises"),fI=require("os"),Yi=require("path");var EC=require("oxc-parser");var xC=require("oxc-parser"),nd=(e,t,i)=>{let n=xC.parseSync(e,t,{lang:i,preserveParens:!1});return n.errors.some((r)=>r.severity==="Error")?null:n.program},SC=(e)=>{let t=e?.value;if(!t)return null;if(t.type==="Literal")return typeof t.value==="string"?t.value:null;if(t.type==="JSXExpressionContainer"){let i=t.expression;if(i.type==="Literal"&&typeof i.value==="string")return i.value;if(i.type==="TemplateLiteral"&&i.expressions.length===0)return i.quasis[0]?.value.cooked??null}return null};var rd=(e)=>{let t=QH(e.postprocess);if(!t||t.size===0)return[];let i=LH(e.code);if(!i||i.size===0)return[];return[...i].filter(([n])=>t.has(n)).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let o=r===n?`path="${r}"`:`path="${r}" \u2014 a dotted path binds its top-level key "${n}"`;return{severity:"error",text:`Postprocess returns the key "${n}", but a Field component is bound to it (${o}). Every submission of this interface fails at runtime with: Postprocess cannot write key '${n}' because a component is bound to it. Fix: bind the Field to a raw key (e.g. path="raw_${n}") and derive "${n}" in postprocess, or remove "${n}" from the postprocess return.`}})},LH=(e)=>{let t=nd("code.tsx",`(
@@ -115,7 +115,7 @@ ${e.code}
115
115
  `),l=s.category===rt.default.DiagnosticCategory.Error?"error":"warning";P(s.file&&s.start!=null,"Diagnostic location is missing");let{line:g,character:d}=s.file.getLineAndCharacterOfPosition(r),{line:c,character:I}=s.file.getLineAndCharacterOfPosition(s.start),m=c-g,p=c===g?I-d:I,C=s.file.text.split(/\r?\n/gu)[c]??"",h=" ".repeat(I)+"^".repeat(s.length&&s.length>0?s.length:1);return{severity:l,text:[`${m}:${p+1} - [${rt.default.DiagnosticCategory[s.category]}] TS${s.code}`,a,"",C,h].join(`
116
116
  `)}})};return{data:i(xt.data),constants:i(xt.constants),preprocess:i(xt.preprocess),postprocess:i(xt.postprocess),code:i(xt.code)}},ad=(e,t)=>{let i=[0];for(let l=0;l<e.length;l+=1)if(e[l]===`
117
117
  `)i.push(l+1);let n=(l)=>{let g=0;while(g+1<i.length&&i[g+1]<=l)g+=1;return{line:g,character:l-i[g]}},r=e.split(/\r?\n/gu),o=dx.map(([l,g])=>({key:l,start:e.indexOf(`/* ${g}_START */`)+`/* ${g}_START */`.length+1,end:e.indexOf(`/* ${g}_END */`)-1})),s=(l)=>{let g=o.find((I)=>l>=I.start&&l<=I.end);if(g)return g;let c=o.filter((I)=>I.start<=l).at(-1)??o[0];return P(c,"Task UI diagnostic block is missing"),c},a=cx();for(let l of t){let g=l.labels[0],d=g?.start??e.length,c=s(d),I=l.severity==="Error"?"error":"warning",{line:m,character:p}=n(c.start),{line:C,character:h}=n(d),Z=C-m,y=C===m?h-p:h,W=r[C]??"",u=g?g.end-g.start:0,A=" ".repeat(h)+"^".repeat(u>0?u:1);a[c.key].push({severity:I,text:[`${Z}:${y+1} - [${l.severity}]`,l.message,"",W,A].join(`
118
- `)})}return a},UC=(e)=>{let t=ad(e,ga.parseSync("runtime.jsx",e).errors);return{...ad(e,ga.parseSync("runtime.tsx",e).errors),preprocess:t.preprocess,postprocess:t.postprocess}},JC=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=TC(i),r=oi.createDefaultMapFromNodeModules({target:rt.default.ScriptTarget.Latest},rt.default,gx);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(Kn,n);let o=oi.createSystem(r),{languageService:s}=oi.createVirtualTypeScriptEnvironment(o,[Kn],rt.default,{target:rt.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:rt.default.ModuleKind.CommonJS,moduleResolution:rt.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:rt.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],l=[];try{a=s.getSyntacticDiagnostics(Kn),l=[...s.getSemanticDiagnostics(Kn),...s.getSuggestionDiagnostics(Kn),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let g=XC(n,a),d=XC(n,[...a,...l]),c=UC(YC(i));return OC(d,g,c)},performSyntaxCheck:(i)=>{let n=TC(i),r=ad(n,ga.parseSync(Kn,n).errors),o=UC(YC(i));return OC(r,r,o)}}),ld=()=>JC({reactDeclaration:Wo.react.source,elementsDeclaration:Wo.elements.source});var dd=require("crypto"),Mn=require("fs/promises"),jC=require("path");var DC="TOLOKA_CHECK_EVIDENCE_DIR",cd="TOLOKA_CHECK_PIPELINE_FINGERPRINT",Id="TOLOKA_CHECK_NODE_ID",ud="TOLOKA_CHECK_TYPED_ONLY",ux=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),mx=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),gd=(e)=>{if(Array.isArray(e))return e.map(gd);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,gd(i)]))},da=(e)=>dd.createHash("sha256").update(JSON.stringify(gd(e))).digest("hex"),px=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,_C=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),zC=(e,t)=>t===void 0?_C(`[toloka:${e}:`):_C(px(e,t));var Cx=(e)=>e==="code"||e==="ui"||e==="pipeline",Ax=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",fx=(e,t)=>{P(ux(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(Cx(i.kind),`Invalid test evidence kind in ${t}`),P(Ax(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||mx(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 LC=async(e)=>{let i=(await Mn.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=jC.join(e,n),o;try{o=JSON.parse(await Mn.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return fx(o,r)}))};var iZ=Le(rI(),1),nZ=Le(Mb(),1);var uI=["JUDGEMENT","EXPLANATION","PROMPT","USER_PROMPT","RESPONSE","RESPONSE_EVALUATION","RUBRIC","RUBRICS_GROUP","DIALOG","DIALOG_STEP","DIALOG_EVALUATION","SHORT_ANSWER","FEEDBACK","CONTEXT","IMAGE","ANNOTATION","SINGLE_LABEL","MULTI_LABEL","VIDEO","DOCUMENT","GOLDEN_SET","LOGS","SOLUTION","CODE","METADATA","AUDIO","AGENT_TRAJECTORY","MCP_SERVER","CONTAINER","CUSTOM"];var Ze={namePattern:"^[a-z]([a-z0-9_]*[a-z0-9])?$",nodeNameMinLength:4,nodeNameMaxLength:32,minTimeForTaskSeconds:10,minHumanQaTimeForTaskSeconds:30,humanQaSecondsPerQualityCriterion:3,minQualityThresholdLength:10,maxExamTasksPerExpert:10,mediaUploadComponentPattern:"<Field\\.(?:Video(?:Upload|Record)|FileUpload)\\b",nodeSettingMaxCharacters:150000,minTrainingSteps:3,maxTrainingSteps:6};var $b={$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:{type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{type:["string","number","boolean","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:{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:{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}$"}},slice:{type:"object",properties:{sliceId:{type:"string",pattern:"^dsl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["sliceId"],additionalProperties:!1},parts:{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}$"},names:{minItems:1,maxItems:10,type:"array",items:{type:"string",maxLength:64,pattern:"^[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*$"}}},required:["fieldId","names"],additionalProperties:!1},excludeParts:{maxItems:500,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}$"},names:{minItems:1,maxItems:10,type:"array",items:{type:"string",maxLength:64,pattern:"^[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*$"}}},required:["fieldId","names"],additionalProperties:!1}},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:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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:{type:["number","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:{type:["number","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:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Requires `audienceMode: service`. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]}},required:["qaMode"],additionalProperties:!1},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Requires `audienceMode: service`. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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"],additionalProperties:!1},{type:"object",properties:{qaMode:{type:"string",const:"customer_review",description:"Review mode: `customer_review` has your team accept or reject every task of the node; an LLM QA check verifies the evidence of each reject. Only for teams with customer review enabled."}},required:["qaMode"],additionalProperties:!1}]},audienceAndPricing:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Requires `audienceMode: service`. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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/__schema2"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema2"},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:{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:{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"}]},audienceMode:{description:"How the node finds experts. `legacy`: audience filters and smart search. `service`: the audience service, which can also take experts from an expert list. Only teams with the audience service enabled can use `service`. Omitted when `legacy`.",type:"string",enum:["legacy","service"]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{type:["string","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","annotation_qa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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:{type:["string","number","boolean","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:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Requires `audienceMode: service`. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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:{type:["number","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:{type:["number","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/__schema2"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema2"},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:{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:{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"}]},audienceMode:{description:"How the node finds experts. `legacy`: audience filters and smart search. `service`: the audience service, which can also take experts from an expert list. Only teams with the audience service enabled can use `service`. Omitted when `legacy`.",type:"string",enum:["legacy","service"]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{type:["string","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","annotation_qa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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"}],items:!1,minItems:2,maxItems:2},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"},ref:"JsonSchemaProperties"},__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,ref:"JsonSchema"},__schema2:{ref:"JsonValue",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:{type:"object",properties:{logic:{type:"string",enum:["and","or"]},predicates:{minItems:1,type:"array",items:{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"}}},required:["logic","predicates"],additionalProperties:!1,ref:"ExpertListConditionGroup"}}};var rZ=new iZ.default({strict:!1});nZ.default(rZ);var qb=rZ.compile($b),iT=new Set(uI),nT=new Set(["SINGLE_LABEL","MULTI_LABEL"]),rT=/^[a-z0-9]+(_[a-z0-9]+)*$/,eZ=(e,t,i)=>e.flatMap((n,r)=>{let o=`${i}/${t}/${r}`,s=[];if(!iT.has(n.entityType))s.push({path:`${o}/entityType`,reason:`must be one of the supported core entity types: ${uI.join(", ")}`});if(t==="output"&&nT.has(n.entityType)){let a=n.allowedLabels??[];if(a.length<2)s.push({path:`${o}/allowedLabels`,reason:"label entities require at least 2 allowedLabels"});if(a.some(({value:l})=>!rT.test(l)))s.push({path:`${o}/allowedLabels`,reason:"label values must be snake_case (e.g. this_is_value)"})}return s}),oT=(e)=>e.nodes.flatMap((t,i)=>{if(t.type!=="generation"&&t.type!=="quorum")return[];let n=`/nodes/${i}/settings/entities`;return[...eZ(t.settings.entities.input,"input",n),...eZ(t.settings.entities.output,"output",n)]}),sT=new RegExp(Ze.namePattern),aT=new RegExp(Ze.mediaUploadComponentPattern),tZ=(e)=>Number(/\[(\d+)\]$/.exec(e)?.[1]??0),lT=(e)=>{let t=e.nodes.find((o)=>o.type==="root");if(t===void 0)return new Set;let i=new Set([t.id]),n=new Set,r=[[t.id,0]];for(let o=r.pop();o!==void 0;o=r.pop()){let[s,a]=o;for(let l of e.connections){if(l.from.node!==s||tZ(l.from.handle)!==a)continue;if(l.to.node===t.id)continue;let g=[l.to.node,tZ(l.to.handle)];if(n.has(g.join("#")))continue;n.add(g.join("#")),i.add(g[0]),r.push(g)}}return i},gT=(e)=>e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,""),dT=(e,t,i)=>{if(t.type==="root")return[];let n=`${i}/about/name`,{name:r}=t.settings.about;if(r==="")return[{path:n,reason:"The node must have a name"}];if(r.length<Ze.nodeNameMinLength||r.length>Ze.nodeNameMaxLength)return[{path:n,reason:`The name must be between ${Ze.nodeNameMinLength} and ${Ze.nodeNameMaxLength} characters long`}];if(!sT.test(r))return[{path:n,reason:"The name must start with a letter, can contain only lowercase letters, numbers and underscores, and must end with a letter or number"}];return e.nodes.some((s)=>s.id!==t.id&&s.type!=="root"&&s.settings.about.name===r)?[{path:n,reason:"The name must be unique across all nodes"}]:[]},cT=(e,t)=>e.flatMap((i,n)=>["pass","fail"].filter((r)=>i.thresholds[r].length<Ze.minQualityThresholdLength).map((r)=>({path:`${t}/qualityCriteria/${n}/thresholds/${r}`,reason:`${r==="pass"?"Pass":"Fail"} condition must be at least ${Ze.minQualityThresholdLength} characters`}))),IT=(e,t)=>{let i=e.map((n)=>n.qualityElement===""?void 0:gT(n.qualityElement));return i.flatMap((n,r)=>n!==void 0&&i.indexOf(n)!==i.lastIndexOf(n)?[{path:`${t}/qualityCriteria/${r}/qualityElement`,reason:"Quality element names must be unique"}]:[])},uT=(e,t)=>{let{qualityAssurance:i,qualityCriteria:n}=e;if(i?.qaMode!=="human_only"&&i?.qaMode!=="hybrid")return[];let r=Math.max(Ze.minHumanQaTimeForTaskSeconds,Ze.humanQaSecondsPerQualityCriterion*n.length);return(i.humanQaTimeForTask??0)<r?[{path:`${t}/qualityAssurance/humanQaTimeForTask`,reason:`Time for one Human QA review must be at least ${r} seconds`}]:[]},ll=({audienceAndPricing:e})=>e?.audienceType==="synthetic",mT=(e,t)=>{let{about:i,audienceAndPricing:n,ui:r}=e;if(ll(e))return[];let o=[];if(i.projectType==="data_collection"&&!aT.test(r.code))o.push({path:`${t}/ui/code`,reason:"Data collection projects require a media upload component (VideoUpload, VideoRecord, or FileUpload) in the UI"});if(n?.audienceType!=="human")return o;if(n.timeForTask<Ze.minTimeForTaskSeconds)o.push({path:`${t}/audienceAndPricing/timeForTask`,reason:`The task execution time cannot be less than ${Ze.minTimeForTaskSeconds} seconds`});if(n.pricePerTask<=0)o.push({path:`${t}/audienceAndPricing/pricePerTask`,reason:"The price per task must be greater than 0"});return o},pT=(e,t)=>{let{exam:i}=e;if(!i?.enabled||ll(e))return[];let n=[];if(i.tasksPerExpert>Ze.maxExamTasksPerExpert)n.push({path:`${t}/exam/tasksPerExpert`,reason:`Tasks per expert cannot exceed ${Ze.maxExamTasksPerExpert}`});if(i.passThreshold<1)n.push({path:`${t}/exam/passThreshold`,reason:"Pass threshold must be at least 1"});if(i.passThreshold>i.tasksPerExpert)n.push({path:`${t}/exam/passThreshold`,reason:"Pass threshold cannot exceed tasks per expert"});return n},ot=(e)=>(e??"").trim()==="",CT=({questions:[e]},t)=>{if(e===void 0)return[{path:`${t}/questions`,reason:"Question text is required"}];let i=`${t}/questions/0`,n=[];if(ot(e.question))n.push({path:`${i}/question`,reason:"Question text is required"});if(e.options.length<2)n.push({path:`${i}/options`,reason:"At least 2 options are required"});else if(e.options.some(({label:o})=>ot(o)))n.push({path:`${i}/options`,reason:"Option label is required"});let r=[e.correctAnswer].flat().filter((o)=>o!=="");if(r.length===0)n.push({path:`${i}/correctAnswer`,reason:"At least one correct answer must be selected"});else if(r.some((o)=>!e.options.some(({value:s})=>s===o)))n.push({path:`${i}/correctAnswer`,reason:"Correct answer must be one of the options"});return n},AT=({path:e,golden:t},i)=>[...ot(e)?[{path:`${i}/path`,reason:"Check path is required"}]:[],...t===void 0||t===null||typeof t==="string"&&ot(t)?[{path:`${i}/golden`,reason:"Check golden is required"}]:[]],fT=(e,t)=>{let i=e.type==="exact"?AT(e,t):[];if(e.type==="code"&&ot(e.code))i.push({path:`${t}/code`,reason:"Check code is required"});if(e.type==="llm"){if(e.paths.every(ot))i.push({path:`${t}/paths`,reason:"Check paths are required"});if(ot(e.criteria))i.push({path:`${t}/criteria`,reason:"Check criteria is required"})}if(e.type!=="llm"&&ot(e.hint))i.push({path:`${t}/hint`,reason:"Check hint is required"});return i},hT=({examples:e},t)=>e.length===0?[{path:`${t}/examples`,reason:"An examples block must have at least one example"}]:e.flatMap(({checks:i},n)=>{let r=`${t}/examples/${n}`;return i.length===0?[{path:`${r}/checks`,reason:"An example must have at least one check"}]:i.flatMap((o,s)=>fT(o,`${r}/checks/${s}`))}),bT=({content:e,validators:t},i)=>[...ot(e?.[0]?.value)?[{path:`${i}/content`,reason:"Task description is required"}]:[],...ot(t?.[0]?.criteria)?[{path:`${i}/validators/0/criteria`,reason:"LLM instruction is required: an LLM grades every practice answer against validators[0].criteria"}]:[]],ZT=(e,t)=>{switch(e.type){case"info":return[];case"text":return ot(e.content?.[0]?.value)?[{path:`${t}/content`,reason:"Content is required"}]:[];case"consent":return ot(e.consentLabel)?[{path:`${t}/consentLabel`,reason:"Consent label is required"}]:[];case"practice":return bT(e,t);case"quiz":return CT(e,t);case"examples":return hT(e,t)}},yT=(e,t)=>{let{onboarding:i,ui:n}=e;if(!i.enabled||ll(e))return[];let r=`${t}/onboarding`,o=["role","goal","successCriteria"].filter((g)=>ot(i.info[g])).map((g)=>({path:`${r}/info/${g}`,reason:`info.${g} is required`})),{steps:s}=i;if(s.length<Ze.minTrainingSteps||s.length>Ze.maxTrainingSteps)o.push({path:`${r}/steps`,reason:`Training must have ${Ze.minTrainingSteps} to ${Ze.maxTrainingSteps} steps`});let a=s.flatMap((g)=>g.blocks??[]),l=(g)=>a.some((d)=>d.type===g);if(!l("quiz"))o.push({path:`${r}/steps`,reason:"Training must include at least one quiz block"});if(l("practice")&&l("examples"))o.push({path:`${r}/steps`,reason:"Training must use either a practice block or an examples block, not both"});if(l("examples")&&["","<></>"].includes(n.code.trim()))o.push({path:`${r}/steps`,reason:"A Training examples block requires the task UI to be built first"});return[...o,...s.flatMap(({blocks:g=[]},d)=>{let c=`${r}/steps/${d}`;return g.length===0?[{path:`${c}/blocks`,reason:"Step must have at least one block"}]:g.flatMap((I,m)=>ZT(I,`${c}/blocks/${m}`))})]},WT=({settings:e},t)=>[...cT(e.qualityCriteria,t),...IT(e.qualityCriteria,t),...uT(e,t),...mT(e,t),...pT(e,t),...yT(e,t)],VT=new Set(["audienceAndPricing","code","conditions","entities","envVars","exam","fieldProxies","instruction","offboardingRules","onboarding","overlap","qualityAssurance","qualityCriteria","ui"]),oZ=(e)=>typeof e==="string"?e.length:typeof e==="object"&&e!==null?Object.values(e).reduce((t,i)=>t+oZ(i),0):0,RT=new Set(["exam","onboarding"]),BT=(e,t)=>{let{settings:i}=e,n=e.type==="generation"&&ll(e.settings)?RT:new Set;return[["about/description",i.about.description],...Object.entries(i).filter(([o])=>VT.has(o)&&!n.has(o))].flatMap(([o,s])=>{let a=oZ(s);return a>Ze.nodeSettingMaxCharacters?[{path:`${t}/${o}`,reason:`This setting holds ${a} characters of text; the platform allows at most ${Ze.nodeSettingMaxCharacters} in one node setting`}]:[]})},gl=(e)=>{let t=lT(e);return e.nodes.flatMap((i,n)=>{if(!t.has(i.id))return[];let r=`/nodes/${n}/settings`,o=i.type==="root"||i.settings.about.name===""?i.id:i.settings.about.name;return[...dT(e,i,r),...i.type==="root"?[]:BT(i,r),...i.type==="generation"||i.type==="quorum"?WT(i,r):[]].map((s)=>({...s,node:o,setting:s.path.slice(r.length+1)}))})},GT=(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 mI(e){if(qb(e)){let r=oT(e);if(r.length>0)throw $i.fromIssues(r);return}let t=qb.errors;P(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=GT(r),s=`${o.path}
118
+ `)})}return a},UC=(e)=>{let t=ad(e,ga.parseSync("runtime.jsx",e).errors);return{...ad(e,ga.parseSync("runtime.tsx",e).errors),preprocess:t.preprocess,postprocess:t.postprocess}},JC=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=TC(i),r=oi.createDefaultMapFromNodeModules({target:rt.default.ScriptTarget.Latest},rt.default,gx);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(Kn,n);let o=oi.createSystem(r),{languageService:s}=oi.createVirtualTypeScriptEnvironment(o,[Kn],rt.default,{target:rt.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:rt.default.ModuleKind.CommonJS,moduleResolution:rt.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:rt.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],l=[];try{a=s.getSyntacticDiagnostics(Kn),l=[...s.getSemanticDiagnostics(Kn),...s.getSuggestionDiagnostics(Kn),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let g=XC(n,a),d=XC(n,[...a,...l]),c=UC(YC(i));return OC(d,g,c)},performSyntaxCheck:(i)=>{let n=TC(i),r=ad(n,ga.parseSync(Kn,n).errors),o=UC(YC(i));return OC(r,r,o)}}),ld=()=>JC({reactDeclaration:Wo.react.source,elementsDeclaration:Wo.elements.source});var dd=require("crypto"),Mn=require("fs/promises"),jC=require("path");var DC="TOLOKA_CHECK_EVIDENCE_DIR",cd="TOLOKA_CHECK_PIPELINE_FINGERPRINT",Id="TOLOKA_CHECK_NODE_ID",ud="TOLOKA_CHECK_TYPED_ONLY",ux=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),mx=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),gd=(e)=>{if(Array.isArray(e))return e.map(gd);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,gd(i)]))},da=(e)=>dd.createHash("sha256").update(JSON.stringify(gd(e))).digest("hex"),px=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,_C=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),zC=(e,t)=>t===void 0?_C(`[toloka:${e}:`):_C(px(e,t));var Cx=(e)=>e==="code"||e==="ui"||e==="pipeline",Ax=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",fx=(e,t)=>{P(ux(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(Cx(i.kind),`Invalid test evidence kind in ${t}`),P(Ax(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||mx(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 LC=async(e)=>{let i=(await Mn.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=jC.join(e,n),o;try{o=JSON.parse(await Mn.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return fx(o,r)}))};var iZ=Le(rI(),1),nZ=Le(Mb(),1);var uI=["JUDGEMENT","EXPLANATION","PROMPT","USER_PROMPT","RESPONSE","RESPONSE_EVALUATION","RUBRIC","RUBRICS_GROUP","DIALOG","DIALOG_STEP","DIALOG_EVALUATION","SHORT_ANSWER","FEEDBACK","CONTEXT","IMAGE","ANNOTATION","SINGLE_LABEL","MULTI_LABEL","VIDEO","DOCUMENT","GOLDEN_SET","LOGS","SOLUTION","CODE","METADATA","AUDIO","AGENT_TRAJECTORY","MCP_SERVER","CONTAINER","CUSTOM"];var Ze={namePattern:"^[a-z]([a-z0-9_]*[a-z0-9])?$",nodeNameMinLength:4,nodeNameMaxLength:32,minTimeForTaskSeconds:10,minHumanQaTimeForTaskSeconds:30,humanQaSecondsPerQualityCriterion:3,minQualityThresholdLength:10,maxExamTasksPerExpert:10,mediaUploadComponentPattern:"<Field\\.(?:Video(?:Upload|Record)|FileUpload)\\b",nodeSettingMaxCharacters:150000,minTrainingSteps:3,maxTrainingSteps:6};var $b={$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:{type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{type:["string","number","boolean","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:{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:{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}$"}},slice:{type:"object",properties:{sliceId:{type:"string",pattern:"^dsl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["sliceId"],additionalProperties:!1},parts:{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}$"},names:{minItems:1,maxItems:10,type:"array",items:{type:"string",maxLength:64,pattern:"^[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*$"}}},required:["fieldId","names"],additionalProperties:!1},excludeParts:{maxItems:500,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}$"},names:{minItems:1,maxItems:10,type:"array",items:{type:"string",maxLength:64,pattern:"^[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*$"}}},required:["fieldId","names"],additionalProperties:!1}},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:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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:{type:["number","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:{type:["number","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:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Not available to teams on the older team ban list. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]}},required:["qaMode"],additionalProperties:!1},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Not available to teams on the older team ban list. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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"],additionalProperties:!1},{type:"object",properties:{qaMode:{type:"string",const:"customer_review",description:"Review mode: `customer_review` has your team accept or reject every task of the node; an LLM QA check verifies the evidence of each reject. Only for teams with customer review enabled."}},required:["qaMode"],additionalProperties:!1}]},audienceAndPricing:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Not available to teams on the older team ban list. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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/__schema2"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema2"},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:{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:{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:{type:["string","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","annotation_qa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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:{type:["string","number","boolean","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:{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},expertListCondition:{description:'The expert lists the node takes its experts from: experts in any of the `list_in` lists, but not in any of the `list_nin` lists. One list is `{ operator: "list_in", expertListId }` with an `exl.` id; several are `{ logic: "or", predicates: [list_in\u2026] }`; excluding lists wraps that in `{ logic: "and", predicates: [<the list_in part>, { operator: "list_nin", expertListId }\u2026] }`. Other combinations (intersections, nested exclusions) are rejected. The platform stores the condition in canonical form (groups flattened, predicates deduplicated and sorted). Not available to teams on the older team ban list. `null` detaches the lists. Omitted when no lists are attached.',anyOf:[{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"},{type:"null"}]},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:{type:["number","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:{type:["number","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/__schema2"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema2"},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:{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:{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:{type:["string","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","annotation_qa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{anyOf:[{type:"string"},{type:"object",propertyNames:{type:"string"},additionalProperties:{type:"string"}}]}},required:["id","name","input"]}}}},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"}],items:!1,minItems:2,maxItems:2},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"},ref:"JsonSchemaProperties"},__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,ref:"JsonSchema"},__schema2:{ref:"JsonValue",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:{type:"object",properties:{logic:{type:"string",enum:["and","or"]},predicates:{minItems:1,type:"array",items:{anyOf:[{type:"object",properties:{operator:{type:"string",enum:["list_in","list_nin"]},expertListId:{type:"string",pattern:"^exl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},required:["operator","expertListId"],additionalProperties:!1,ref:"ExpertListPredicate"},{$ref:"#/$defs/__schema3"}],ref:"ExpertListCondition"}}},required:["logic","predicates"],additionalProperties:!1,ref:"ExpertListConditionGroup"}}};var rZ=new iZ.default({strict:!1});nZ.default(rZ);var qb=rZ.compile($b),iT=new Set(uI),nT=new Set(["SINGLE_LABEL","MULTI_LABEL"]),rT=/^[a-z0-9]+(_[a-z0-9]+)*$/,eZ=(e,t,i)=>e.flatMap((n,r)=>{let o=`${i}/${t}/${r}`,s=[];if(!iT.has(n.entityType))s.push({path:`${o}/entityType`,reason:`must be one of the supported core entity types: ${uI.join(", ")}`});if(t==="output"&&nT.has(n.entityType)){let a=n.allowedLabels??[];if(a.length<2)s.push({path:`${o}/allowedLabels`,reason:"label entities require at least 2 allowedLabels"});if(a.some(({value:l})=>!rT.test(l)))s.push({path:`${o}/allowedLabels`,reason:"label values must be snake_case (e.g. this_is_value)"})}return s}),oT=(e)=>e.nodes.flatMap((t,i)=>{if(t.type!=="generation"&&t.type!=="quorum")return[];let n=`/nodes/${i}/settings/entities`;return[...eZ(t.settings.entities.input,"input",n),...eZ(t.settings.entities.output,"output",n)]}),sT=new RegExp(Ze.namePattern),aT=new RegExp(Ze.mediaUploadComponentPattern),tZ=(e)=>Number(/\[(\d+)\]$/.exec(e)?.[1]??0),lT=(e)=>{let t=e.nodes.find((o)=>o.type==="root");if(t===void 0)return new Set;let i=new Set([t.id]),n=new Set,r=[[t.id,0]];for(let o=r.pop();o!==void 0;o=r.pop()){let[s,a]=o;for(let l of e.connections){if(l.from.node!==s||tZ(l.from.handle)!==a)continue;if(l.to.node===t.id)continue;let g=[l.to.node,tZ(l.to.handle)];if(n.has(g.join("#")))continue;n.add(g.join("#")),i.add(g[0]),r.push(g)}}return i},gT=(e)=>e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,""),dT=(e,t,i)=>{if(t.type==="root")return[];let n=`${i}/about/name`,{name:r}=t.settings.about;if(r==="")return[{path:n,reason:"The node must have a name"}];if(r.length<Ze.nodeNameMinLength||r.length>Ze.nodeNameMaxLength)return[{path:n,reason:`The name must be between ${Ze.nodeNameMinLength} and ${Ze.nodeNameMaxLength} characters long`}];if(!sT.test(r))return[{path:n,reason:"The name must start with a letter, can contain only lowercase letters, numbers and underscores, and must end with a letter or number"}];return e.nodes.some((s)=>s.id!==t.id&&s.type!=="root"&&s.settings.about.name===r)?[{path:n,reason:"The name must be unique across all nodes"}]:[]},cT=(e,t)=>e.flatMap((i,n)=>["pass","fail"].filter((r)=>i.thresholds[r].length<Ze.minQualityThresholdLength).map((r)=>({path:`${t}/qualityCriteria/${n}/thresholds/${r}`,reason:`${r==="pass"?"Pass":"Fail"} condition must be at least ${Ze.minQualityThresholdLength} characters`}))),IT=(e,t)=>{let i=e.map((n)=>n.qualityElement===""?void 0:gT(n.qualityElement));return i.flatMap((n,r)=>n!==void 0&&i.indexOf(n)!==i.lastIndexOf(n)?[{path:`${t}/qualityCriteria/${r}/qualityElement`,reason:"Quality element names must be unique"}]:[])},uT=(e,t)=>{let{qualityAssurance:i,qualityCriteria:n}=e;if(i?.qaMode!=="human_only"&&i?.qaMode!=="hybrid")return[];let r=Math.max(Ze.minHumanQaTimeForTaskSeconds,Ze.humanQaSecondsPerQualityCriterion*n.length);return(i.humanQaTimeForTask??0)<r?[{path:`${t}/qualityAssurance/humanQaTimeForTask`,reason:`Time for one Human QA review must be at least ${r} seconds`}]:[]},ll=({audienceAndPricing:e})=>e?.audienceType==="synthetic",mT=(e,t)=>{let{about:i,audienceAndPricing:n,ui:r}=e;if(ll(e))return[];let o=[];if(i.projectType==="data_collection"&&!aT.test(r.code))o.push({path:`${t}/ui/code`,reason:"Data collection projects require a media upload component (VideoUpload, VideoRecord, or FileUpload) in the UI"});if(n?.audienceType!=="human")return o;if(n.timeForTask<Ze.minTimeForTaskSeconds)o.push({path:`${t}/audienceAndPricing/timeForTask`,reason:`The task execution time cannot be less than ${Ze.minTimeForTaskSeconds} seconds`});if(n.pricePerTask<=0)o.push({path:`${t}/audienceAndPricing/pricePerTask`,reason:"The price per task must be greater than 0"});return o},pT=(e,t)=>{let{exam:i}=e;if(!i?.enabled||ll(e))return[];let n=[];if(i.tasksPerExpert>Ze.maxExamTasksPerExpert)n.push({path:`${t}/exam/tasksPerExpert`,reason:`Tasks per expert cannot exceed ${Ze.maxExamTasksPerExpert}`});if(i.passThreshold<1)n.push({path:`${t}/exam/passThreshold`,reason:"Pass threshold must be at least 1"});if(i.passThreshold>i.tasksPerExpert)n.push({path:`${t}/exam/passThreshold`,reason:"Pass threshold cannot exceed tasks per expert"});return n},ot=(e)=>(e??"").trim()==="",CT=({questions:[e]},t)=>{if(e===void 0)return[{path:`${t}/questions`,reason:"Question text is required"}];let i=`${t}/questions/0`,n=[];if(ot(e.question))n.push({path:`${i}/question`,reason:"Question text is required"});if(e.options.length<2)n.push({path:`${i}/options`,reason:"At least 2 options are required"});else if(e.options.some(({label:o})=>ot(o)))n.push({path:`${i}/options`,reason:"Option label is required"});let r=[e.correctAnswer].flat().filter((o)=>o!=="");if(r.length===0)n.push({path:`${i}/correctAnswer`,reason:"At least one correct answer must be selected"});else if(r.some((o)=>!e.options.some(({value:s})=>s===o)))n.push({path:`${i}/correctAnswer`,reason:"Correct answer must be one of the options"});return n},AT=({path:e,golden:t},i)=>[...ot(e)?[{path:`${i}/path`,reason:"Check path is required"}]:[],...t===void 0||t===null||typeof t==="string"&&ot(t)?[{path:`${i}/golden`,reason:"Check golden is required"}]:[]],fT=(e,t)=>{let i=e.type==="exact"?AT(e,t):[];if(e.type==="code"&&ot(e.code))i.push({path:`${t}/code`,reason:"Check code is required"});if(e.type==="llm"){if(e.paths.every(ot))i.push({path:`${t}/paths`,reason:"Check paths are required"});if(ot(e.criteria))i.push({path:`${t}/criteria`,reason:"Check criteria is required"})}if(e.type!=="llm"&&ot(e.hint))i.push({path:`${t}/hint`,reason:"Check hint is required"});return i},hT=({examples:e},t)=>e.length===0?[{path:`${t}/examples`,reason:"An examples block must have at least one example"}]:e.flatMap(({checks:i},n)=>{let r=`${t}/examples/${n}`;return i.length===0?[{path:`${r}/checks`,reason:"An example must have at least one check"}]:i.flatMap((o,s)=>fT(o,`${r}/checks/${s}`))}),bT=({content:e,validators:t},i)=>[...ot(e?.[0]?.value)?[{path:`${i}/content`,reason:"Task description is required"}]:[],...ot(t?.[0]?.criteria)?[{path:`${i}/validators/0/criteria`,reason:"LLM instruction is required: an LLM grades every practice answer against validators[0].criteria"}]:[]],ZT=(e,t)=>{switch(e.type){case"info":return[];case"text":return ot(e.content?.[0]?.value)?[{path:`${t}/content`,reason:"Content is required"}]:[];case"consent":return ot(e.consentLabel)?[{path:`${t}/consentLabel`,reason:"Consent label is required"}]:[];case"practice":return bT(e,t);case"quiz":return CT(e,t);case"examples":return hT(e,t)}},yT=(e,t)=>{let{onboarding:i,ui:n}=e;if(!i.enabled||ll(e))return[];let r=`${t}/onboarding`,o=["role","goal","successCriteria"].filter((g)=>ot(i.info[g])).map((g)=>({path:`${r}/info/${g}`,reason:`info.${g} is required`})),{steps:s}=i;if(s.length<Ze.minTrainingSteps||s.length>Ze.maxTrainingSteps)o.push({path:`${r}/steps`,reason:`Training must have ${Ze.minTrainingSteps} to ${Ze.maxTrainingSteps} steps`});let a=s.flatMap((g)=>g.blocks??[]),l=(g)=>a.some((d)=>d.type===g);if(!l("quiz"))o.push({path:`${r}/steps`,reason:"Training must include at least one quiz block"});if(l("practice")&&l("examples"))o.push({path:`${r}/steps`,reason:"Training must use either a practice block or an examples block, not both"});if(l("examples")&&["","<></>"].includes(n.code.trim()))o.push({path:`${r}/steps`,reason:"A Training examples block requires the task UI to be built first"});return[...o,...s.flatMap(({blocks:g=[]},d)=>{let c=`${r}/steps/${d}`;return g.length===0?[{path:`${c}/blocks`,reason:"Step must have at least one block"}]:g.flatMap((I,m)=>ZT(I,`${c}/blocks/${m}`))})]},WT=({settings:e},t)=>[...cT(e.qualityCriteria,t),...IT(e.qualityCriteria,t),...uT(e,t),...mT(e,t),...pT(e,t),...yT(e,t)],VT=new Set(["audienceAndPricing","code","conditions","entities","envVars","exam","fieldProxies","instruction","offboardingRules","onboarding","overlap","qualityAssurance","qualityCriteria","ui"]),oZ=(e)=>typeof e==="string"?e.length:typeof e==="object"&&e!==null?Object.values(e).reduce((t,i)=>t+oZ(i),0):0,RT=new Set(["exam","onboarding"]),BT=(e,t)=>{let{settings:i}=e,n=e.type==="generation"&&ll(e.settings)?RT:new Set;return[["about/description",i.about.description],...Object.entries(i).filter(([o])=>VT.has(o)&&!n.has(o))].flatMap(([o,s])=>{let a=oZ(s);return a>Ze.nodeSettingMaxCharacters?[{path:`${t}/${o}`,reason:`This setting holds ${a} characters of text; the platform allows at most ${Ze.nodeSettingMaxCharacters} in one node setting`}]:[]})},gl=(e)=>{let t=lT(e);return e.nodes.flatMap((i,n)=>{if(!t.has(i.id))return[];let r=`/nodes/${n}/settings`,o=i.type==="root"||i.settings.about.name===""?i.id:i.settings.about.name;return[...dT(e,i,r),...i.type==="root"?[]:BT(i,r),...i.type==="generation"||i.type==="quorum"?WT(i,r):[]].map((s)=>({...s,node:o,setting:s.path.slice(r.length+1)}))})},GT=(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 mI(e){if(qb(e)){let r=oT(e);if(r.length>0)throw $i.fromIssues(r);return}let t=qb.errors;P(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=GT(r),s=`${o.path}
119
119
  ${o.reason}`;if(i.has(s))continue;i.add(s),n.push(o)}throw $i.fromIssues(n)}var wT={POTATO_API_KEY:"TOLOKA_API_KEY",POTATO_BASE_URL:"TOLOKA_BASE_URL",POTATO_PROJECT_ID:"TOLOKA_PROJECT_ID"},Uo=["TOLOKA_SCOPED_TOKEN","TOLOKA_API_KEY","POTATO_API_KEY"],sZ=(e)=>{let t={...e},i=[];for(let[n,r]of Object.entries(wT)){let o=e[n];if(o===void 0)continue;t[r]??=o,i.push(`${n} is deprecated and will stop being read; set ${r} instead.`)}return{environment:t,warnings:i}};var _o=require("fs/promises"),je=require("path"),IZ=require("url");var FT=Symbol("fieldDefinition"),HT=Symbol.for("@toloka-platform/sdk/pipeline-definition"),lZ=Symbol("portDefinition"),vT=Symbol("nodeFieldReferences");function gZ(e,t){return{node:e,handle:t,direction:"input",[lZ]:"input"}}function dZ(e,t){return{node:e,handle:t,direction:"output",[lZ]:"output"}}function cZ(e){return typeof e==="object"&&e!==null&&FT in e}function pI(e,t){if(cZ(e)){t.push(e);return}if(Array.isArray(e)){for(let i of e)pI(i,t);return}if(typeof e==="object"&&e!==null)for(let i of Object.values(e))pI(i,t)}function PT(e){let t=[];return pI(e,t),t}function aZ(e){return cZ(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function kT(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(aZ)},completedFieldProxies:{input:r.map(aZ)}},started:dZ(i,"started"),completed:gZ(i,"completed"),[vT]:PT(e)}}var f4=Object.assign(kT,{started:dZ("root","started"),completed:gZ("root","completed")});function xT(e){return typeof e==="object"&&e!==null&&HT in e}function dl(e){P(xT(e),"Invalid pipeline definition: expected a value returned by definePipeline"),P(e.dataset!=="","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")}mI(e.graph)}function Jo(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,...t.datasetId===void 0?{}:{datasetId:t.datasetId}}}:n),connections:e.graph.connections.map((n)=>({from:{...n.from},to:{...n.to},settings:{...n.settings}}))};return mI(i),i}var uZ=async(e)=>{let t;try{t=await _o.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=je.join(e,n.name);if(n.isDirectory())i.push(...await uZ(r));else if(n.isFile()&&n.name==="pipeline.ts")i.push(r)}return i},ST="toloka.json",ET=async(e)=>{try{return(await _o.stat(je.join(e,ST))).isFile()}catch{return!1}};async function mZ(e){let t=je.resolve(e);for(;;){if(await ET(t))return t;let i=je.dirname(t);if(i===t)return;t=i}}async function Br(e){let t=await uZ(je.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(n)=>{let r=await _o.stat(n),o=IZ.pathToFileURL(n);o.searchParams.set("version",`${r.mtimeMs}-${r.size}`);let s=await import(o.href);f(typeof s==="object"&&s!==null,`Invalid ${n}: expected a module`,{hint:{description:"Make the file a TypeScript module that exports the pipeline definition."}});let a=Reflect.get(s,"default");dl(a);let l=je.relative(e,je.dirname(n)).split(je.sep).join("/");return{sourceDirectory:l,name:je.basename(l),definition:a}}))).toSorted((n,r)=>n.sourceDirectory.localeCompare(r.sourceDirectory))}}class Gr extends k{phase;constructor(e,t,i){super(t,i);this.name="FreshCheckProcessError",this.phase=e}}var pZ=5000,NT=65536,Xi="TOLOKA_INTERNAL_CHECK_RESULT_FILE",TT=(e)=>e.message.length<=pZ?e:{...e,message:`${e.message.slice(0,pZ)}
120
120
  \u2026output truncated`},CI=20,CZ=async(e)=>{let t=[],i=0,n=!1;for await(let o of e){let s=Buffer.isBuffer(o)?o:Buffer.from(o),a=NT-i;if(a>0){let l=s.subarray(0,a);t.push(l),i+=l.length}if(s.length>a)n=!0}let r=Buffer.concat(t).toString("utf8");return n?`${r}
121
121
  \u2026output truncated`:r},hI=async(e,t,i,n,r)=>{r?.throwIfAborted();let o=ZZ.spawn(t,i,{cwd:e,env:n,stdio:["ignore","pipe","pipe"]}),s=()=>o.kill("SIGTERM");if(r?.addEventListener("abort",s,{once:!0}),r?.aborted===!0)s();try{let[a,l,g]=await Promise.all([WZ.once(o,"close"),CZ(o.stdout),CZ(o.stderr)]),d=a[0];return typeof d==="number"?{exitCode:d,stdout:l,stderr:g}:{exitCode:2,stdout:l,stderr:[g,`Process terminated by ${String(a[1])}`].filter(Boolean).join(`
@@ -313,12 +313,12 @@ ${c} fields: ${d(a,1)},
313
313
  nodes: ${d(l,1)},
314
314
  connections: ${d(g,1)}
315
315
  });
316
- `}function wV(e,t={dataset:"imported-dataset"}){let i=[...e.fields.map((g)=>({key:`field:${g.id}`,name:g.name,fallback:"field"})),...e.nodes.map((g)=>({key:`node:${g.id}`,name:g.type==="root"?"root":g.settings.about.name||g.type,fallback:g.type}))],n=uu(i,({name:g,fallback:d})=>RV(g,d),WV),r=uu(e.nodes.map((g)=>({key:`node:${g.id}`,name:g.type==="root"?"root":g.settings.about.name||g.type,fallback:g.type})),({name:g,fallback:d})=>KU(g,d)),o=new Map(e.fields.map((g)=>{let d=n.get(`field:${g.id}`);return P(d,`Field "${g.id}" has no allocated binding`),[g.id,d]})),s=new Map(e.nodes.map((g)=>{let d=n.get(`node:${g.id}`);return P(d,`Node "${g.id}" has no allocated binding`),[g.id,d]})),a=e.nodes.map((g)=>{let d=s.get(g.id),c=r.get(`node:${g.id}`);return P(d&&c,`Node "${g.id}" has no allocated source name`),qU(g,d,`nodes/${c}/node.ts`,o)}),l=[{path:"fields.ts",source:eJ(e,o,t.invalidFieldSchemas??[])},...a.map(({path:g,source:d})=>({path:g,source:d})),{path:"pipeline.ts",source:tJ(e,t.dataset,a,o,s)}].toSorted((g,d)=>Di(g.path,d.path));return Object.fromEntries(l.map(({path:g,source:d})=>[g,d]))}var gi=require("fs/promises"),Wn=require("path");function FV(e){let t=new Set;for(let i of e.nodes){if(i.type!=="code")continue;for(let n of i.settings.envVars??[])if(n.type==="secret")t.add(n.secretName)}return[...t].toSorted((i,n)=>i.localeCompare(n))}var iJ=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,Au=(e)=>{if(Array.isArray(e))return e.map(Au);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,Au(i)]))},De=(e)=>JSON.stringify(Au(e)),di=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),PV=(e,t)=>{if(!di(e)||!di(t))return t;return Object.fromEntries(Object.keys(e).map((i)=>[i,PV(e[i],t[i])]))},nJ=(e,t)=>De(e)===De(PV(e,t)),rJ=(e)=>di(e)&&(e.qaMode==="human_only"||e.qaMode==="hybrid"),kV=(e)=>{if(!di(e)||!Array.isArray(e.predicates))return e;let t=[...new Map(e.predicates.map(kV).flatMap((i)=>di(i)&&i.logic===e.logic&&Array.isArray(i.predicates)?i.predicates:[i]).map((i)=>[De(i),i]))].toSorted(([i],[n])=>i.localeCompare(n)).map(([,i])=>i);return t.length===1?t[0]:{logic:e.logic,predicates:t}},oJ=(e)=>di(e)&&("expertListCondition"in e)?{...e,expertListCondition:kV(e.expertListCondition)}:e,HV=(e)=>di(e)&&di(e.settings)?{...e,settings:Object.fromEntries(Object.entries(e.settings).map(([t,i])=>[t,oJ(i)]))}:e,sJ=(e)=>{if(e.type!=="generation"&&e.type!=="quorum")return e;let t=e.settings.audienceAndPricing,i=e.type==="generation"?e.settings.qualityAssurance:void 0;return{...e,settings:{audienceMode:"legacy",...e.settings,...di(t)&&t.audienceType==="human"?{audienceAndPricing:{expertListCondition:null,...t}}:{},...rJ(i)?{qualityAssurance:{expertListCondition:null,...i}}:{}}}},ts=async(e)=>{let t=[];for await(let i of e)t.push(i);return t},fu=(e)=>{let t=Reflect.get(e.settings,"about");if(typeof t==="object"&&t!==null){let i=Reflect.get(t,"name");if(typeof i==="string"&&i.length>0)return`${i} (${e.id})`}return e.id},aJ=(e)=>`${e.name} (${e.id})`,lJ=(e,t)=>{let i=t.get(e.from.node),n=t.get(e.to.node),r=i===void 0?e.from.node:fu(i),o=n===void 0?e.to.node:fu(n);return`${r}.${e.from.handle} -> ${o}.${e.to.handle}`},Pl=(e)=>new Map(e.map((t)=>[t.id,t])),pu=(e,t,i,n)=>{let r=[];for(let[o,s]of[...e].toSorted(([a],[l])=>a.localeCompare(l))){let a=t.get(o);if(a===void 0)r.push(n(s,"added"));else if(!i(s,a))r.push(n(s,"changed"))}for(let[o,s]of[...t].toSorted(([a],[l])=>a.localeCompare(l)))if(!e.has(o))r.push(n(s,"removed"));return r};function gJ(e,t){let i=Pl(e.nodes),n=Pl(t.nodes),r=new Map(e.connections.map((s)=>[De(s),s])),o=new Map(t.connections.map((s)=>[De(s),s]));return[...pu(Pl(e.fields),Pl(t.fields),(s,a)=>De(s)===De(a),(s,a)=>({kind:"field",action:a,label:aJ(s),id:s.id})),...pu(i,n,(s,a)=>nJ(HV(s),HV(sJ(a))),(s,a)=>({kind:"node",action:a,label:fu(s),id:s.id})),...pu(r,o,()=>!0,(s,a)=>({kind:"connection",action:a,label:lJ(s,a==="removed"?n:i)})),...De(e.layout)===De(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var Cu=(e,t)=>t.settings.checks===void 0?e:{...e,settings:{...e.settings,checks:{...t.settings.checks,...e.settings.checks}}},bu=(e,t)=>{let i=t.nodes.find((o)=>o.type==="root"),n=i===void 0?{}:{...i.settings.itemFilter===void 0?{}:{itemFilter:i.settings.itemFilter},...i.settings.itemLimit===void 0?{}:{itemLimit:i.settings.itemLimit}},r=new Map(t.nodes.map((o)=>[o.id,o]));return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((o)=>{let s=r.get(o.id);switch(o.type){case"root":return{...o,settings:{...n,...o.settings}};case"code":return s?.type==="code"?Cu(o,s):o;case"generation":return s?.type==="generation"?Cu(o,s):o;case"quorum":return s?.type==="quorum"?Cu(o,s):o;case"match":return o}})}},kl=(e)=>{let t=new Map;for(let i of e.pipelines){let n=i.definition.dataset;if(n===void 0)continue;let r=t.get(n);if(r===void 0)r=new Map,t.set(n,r);for(let o of i.definition.graph.fields){let s=r.get(o.name);if(f(s===void 0||De(s.jsonSchema)===De(o.jsonSchema),`Dataset "${n}" has conflicting schemas for field "${o.name}".`,{hint:{description:"Give the field one JSON schema across all pipelines that share the dataset."}}),s===void 0)r.set(o.name,o)}}return[...t].toSorted(([i],[n])=>i.localeCompare(n)).map(([i,n])=>({name:i,fields:[...n.values()].toSorted((r,o)=>r.name.localeCompare(o.name))}))},dJ=(e)=>{let t=new Set;for(let i of e.pipelines)f(iJ.test(i.sourceDirectory),`Invalid pipeline source directory ${i.sourceDirectory}`,{hint:{description:"Use a relative path without backslashes, // or . and .. segments."}}),f(!t.has(i.sourceDirectory),`Pipeline source directory ${i.sourceDirectory} is declared more than once`,{hint:{description:"Give each pipeline its own source directory."}}),t.add(i.sourceDirectory),dl(i.definition);kl(e)},cJ=(e,t,i)=>{let n=t===void 0?void 0:i.find((o)=>o.id===t.datasetId);if(n!==void 0)return f(n.name===e,`Dataset ${n.id} is bound as "${e}" but is named "${n.name}".`,{hint:{description:"Rename the dataset in source to match the platform, or run toloka project untrack dataset <name> and bind it again with toloka apply."}}),n;let r=i.filter((o)=>o.name===e);return f(r.length<=1,`Project has multiple datasets named "${e}".`,{hint:{description:"Rename the duplicate datasets in the platform, or reference the dataset by id."}}),r[0]},IJ=(e,t,i)=>{let n=t===void 0?void 0:i.find((o)=>o.id===t.pipelineId);if(n!==void 0)return n;let r=i.filter((o)=>o.name===e.name);return f(r.length<=1,`Project has multiple pipelines named "${e.name}".`,{hint:{description:"Rename the duplicate pipelines in the platform, then re-run the command."}}),r[0]},uJ=(e)=>{let t=e.action==="added"?"+":e.action==="removed"?"-":e.action==="missing"?"!":"~";switch(e.kind){case"pipeline":return`${t} Pipeline ${e.action}: ${e.label}`;case"dataset":return`${t} Dataset ${e.action}: ${e.label}`;case"datasetField":return`${t} Dataset field ${e.action}: ${e.dataset}.${e.label}`;case"secret":return`${t} Missing secret: ${e.label}`;case"node":return`${t} Node ${e.action} in ${e.pipeline}: ${e.label}`;case"connection":return`${t} Connection ${e.action} in ${e.pipeline}: ${e.label}`;case"field":return`${t} Graph field ${e.action} in ${e.pipeline}: ${e.label}`;case"layout":return`${t} Layout ${e.action} in ${e.pipeline}: ${e.label}`}},mJ=(e,t)=>{if(e.length===0)return"No changes.";let i=e.length===1?"change":"changes",n=[`Plan: ${e.length} ${i}`,...e.map(uJ)];if(t.length>0){n.push("","Required secrets are missing:");for(let r of t)n.push(` ${r}`);n.push("Run `toloka secret set <name>` before apply.")}return n.join(`
316
+ `}function wV(e,t={dataset:"imported-dataset"}){let i=[...e.fields.map((g)=>({key:`field:${g.id}`,name:g.name,fallback:"field"})),...e.nodes.map((g)=>({key:`node:${g.id}`,name:g.type==="root"?"root":g.settings.about.name||g.type,fallback:g.type}))],n=uu(i,({name:g,fallback:d})=>RV(g,d),WV),r=uu(e.nodes.map((g)=>({key:`node:${g.id}`,name:g.type==="root"?"root":g.settings.about.name||g.type,fallback:g.type})),({name:g,fallback:d})=>KU(g,d)),o=new Map(e.fields.map((g)=>{let d=n.get(`field:${g.id}`);return P(d,`Field "${g.id}" has no allocated binding`),[g.id,d]})),s=new Map(e.nodes.map((g)=>{let d=n.get(`node:${g.id}`);return P(d,`Node "${g.id}" has no allocated binding`),[g.id,d]})),a=e.nodes.map((g)=>{let d=s.get(g.id),c=r.get(`node:${g.id}`);return P(d&&c,`Node "${g.id}" has no allocated source name`),qU(g,d,`nodes/${c}/node.ts`,o)}),l=[{path:"fields.ts",source:eJ(e,o,t.invalidFieldSchemas??[])},...a.map(({path:g,source:d})=>({path:g,source:d})),{path:"pipeline.ts",source:tJ(e,t.dataset,a,o,s)}].toSorted((g,d)=>Di(g.path,d.path));return Object.fromEntries(l.map(({path:g,source:d})=>[g,d]))}var gi=require("fs/promises"),Wn=require("path");function FV(e){let t=new Set;for(let i of e.nodes){if(i.type!=="code")continue;for(let n of i.settings.envVars??[])if(n.type==="secret")t.add(n.secretName)}return[...t].toSorted((i,n)=>i.localeCompare(n))}var iJ=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,Au=(e)=>{if(Array.isArray(e))return e.map(Au);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,Au(i)]))},De=(e)=>JSON.stringify(Au(e)),di=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),PV=(e,t)=>{if(!di(e)||!di(t))return t;return Object.fromEntries(Object.keys(e).map((i)=>[i,PV(e[i],t[i])]))},nJ=(e,t)=>De(e)===De(PV(e,t)),rJ=(e)=>di(e)&&(e.qaMode==="human_only"||e.qaMode==="hybrid"),kV=(e)=>{if(!di(e)||!Array.isArray(e.predicates))return e;let t=[...new Map(e.predicates.map(kV).flatMap((i)=>di(i)&&i.logic===e.logic&&Array.isArray(i.predicates)?i.predicates:[i]).map((i)=>[De(i),i]))].toSorted(([i],[n])=>i.localeCompare(n)).map(([,i])=>i);return t.length===1?t[0]:{logic:e.logic,predicates:t}},oJ=(e)=>di(e)&&("expertListCondition"in e)?{...e,expertListCondition:kV(e.expertListCondition)}:e,HV=(e)=>di(e)&&di(e.settings)?{...e,settings:Object.fromEntries(Object.entries(e.settings).map(([t,i])=>[t,oJ(i)]))}:e,sJ=(e)=>{if(e.type!=="generation"&&e.type!=="quorum")return e;let t=e.settings.audienceAndPricing,i=e.type==="generation"?e.settings.qualityAssurance:void 0;return{...e,settings:{...e.settings,...di(t)&&t.audienceType==="human"?{audienceAndPricing:{expertListCondition:null,...t}}:{},...rJ(i)?{qualityAssurance:{expertListCondition:null,...i}}:{}}}},ts=async(e)=>{let t=[];for await(let i of e)t.push(i);return t},fu=(e)=>{let t=Reflect.get(e.settings,"about");if(typeof t==="object"&&t!==null){let i=Reflect.get(t,"name");if(typeof i==="string"&&i.length>0)return`${i} (${e.id})`}return e.id},aJ=(e)=>`${e.name} (${e.id})`,lJ=(e,t)=>{let i=t.get(e.from.node),n=t.get(e.to.node),r=i===void 0?e.from.node:fu(i),o=n===void 0?e.to.node:fu(n);return`${r}.${e.from.handle} -> ${o}.${e.to.handle}`},Pl=(e)=>new Map(e.map((t)=>[t.id,t])),pu=(e,t,i,n)=>{let r=[];for(let[o,s]of[...e].toSorted(([a],[l])=>a.localeCompare(l))){let a=t.get(o);if(a===void 0)r.push(n(s,"added"));else if(!i(s,a))r.push(n(s,"changed"))}for(let[o,s]of[...t].toSorted(([a],[l])=>a.localeCompare(l)))if(!e.has(o))r.push(n(s,"removed"));return r};function gJ(e,t){let i=Pl(e.nodes),n=Pl(t.nodes),r=new Map(e.connections.map((s)=>[De(s),s])),o=new Map(t.connections.map((s)=>[De(s),s]));return[...pu(Pl(e.fields),Pl(t.fields),(s,a)=>De(s)===De(a),(s,a)=>({kind:"field",action:a,label:aJ(s),id:s.id})),...pu(i,n,(s,a)=>nJ(HV(s),HV(sJ(a))),(s,a)=>({kind:"node",action:a,label:fu(s),id:s.id})),...pu(r,o,()=>!0,(s,a)=>({kind:"connection",action:a,label:lJ(s,a==="removed"?n:i)})),...De(e.layout)===De(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var Cu=(e,t)=>t.settings.checks===void 0?e:{...e,settings:{...e.settings,checks:{...t.settings.checks,...e.settings.checks}}},bu=(e,t)=>{let i=t.nodes.find((o)=>o.type==="root"),n=i===void 0?{}:{...i.settings.itemFilter===void 0?{}:{itemFilter:i.settings.itemFilter},...i.settings.itemLimit===void 0?{}:{itemLimit:i.settings.itemLimit}},r=new Map(t.nodes.map((o)=>[o.id,o]));return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((o)=>{let s=r.get(o.id);switch(o.type){case"root":return{...o,settings:{...n,...o.settings}};case"code":return s?.type==="code"?Cu(o,s):o;case"generation":return s?.type==="generation"?Cu(o,s):o;case"quorum":return s?.type==="quorum"?Cu(o,s):o;case"match":return o}})}},kl=(e)=>{let t=new Map;for(let i of e.pipelines){let n=i.definition.dataset;if(n===void 0)continue;let r=t.get(n);if(r===void 0)r=new Map,t.set(n,r);for(let o of i.definition.graph.fields){let s=r.get(o.name);if(f(s===void 0||De(s.jsonSchema)===De(o.jsonSchema),`Dataset "${n}" has conflicting schemas for field "${o.name}".`,{hint:{description:"Give the field one JSON schema across all pipelines that share the dataset."}}),s===void 0)r.set(o.name,o)}}return[...t].toSorted(([i],[n])=>i.localeCompare(n)).map(([i,n])=>({name:i,fields:[...n.values()].toSorted((r,o)=>r.name.localeCompare(o.name))}))},dJ=(e)=>{let t=new Set;for(let i of e.pipelines)f(iJ.test(i.sourceDirectory),`Invalid pipeline source directory ${i.sourceDirectory}`,{hint:{description:"Use a relative path without backslashes, // or . and .. segments."}}),f(!t.has(i.sourceDirectory),`Pipeline source directory ${i.sourceDirectory} is declared more than once`,{hint:{description:"Give each pipeline its own source directory."}}),t.add(i.sourceDirectory),dl(i.definition);kl(e)},cJ=(e,t,i)=>{let n=t===void 0?void 0:i.find((o)=>o.id===t.datasetId);if(n!==void 0)return f(n.name===e,`Dataset ${n.id} is bound as "${e}" but is named "${n.name}".`,{hint:{description:"Rename the dataset in source to match the platform, or run toloka project untrack dataset <name> and bind it again with toloka apply."}}),n;let r=i.filter((o)=>o.name===e);return f(r.length<=1,`Project has multiple datasets named "${e}".`,{hint:{description:"Rename the duplicate datasets in the platform, or reference the dataset by id."}}),r[0]},IJ=(e,t,i)=>{let n=t===void 0?void 0:i.find((o)=>o.id===t.pipelineId);if(n!==void 0)return n;let r=i.filter((o)=>o.name===e.name);return f(r.length<=1,`Project has multiple pipelines named "${e.name}".`,{hint:{description:"Rename the duplicate pipelines in the platform, then re-run the command."}}),r[0]},uJ=(e)=>{let t=e.action==="added"?"+":e.action==="removed"?"-":e.action==="missing"?"!":"~";switch(e.kind){case"pipeline":return`${t} Pipeline ${e.action}: ${e.label}`;case"dataset":return`${t} Dataset ${e.action}: ${e.label}`;case"datasetField":return`${t} Dataset field ${e.action}: ${e.dataset}.${e.label}`;case"secret":return`${t} Missing secret: ${e.label}`;case"node":return`${t} Node ${e.action} in ${e.pipeline}: ${e.label}`;case"connection":return`${t} Connection ${e.action} in ${e.pipeline}: ${e.label}`;case"field":return`${t} Graph field ${e.action} in ${e.pipeline}: ${e.label}`;case"layout":return`${t} Layout ${e.action} in ${e.pipeline}: ${e.label}`}},mJ=(e,t)=>{if(e.length===0)return"No changes.";let i=e.length===1?"change":"changes",n=[`Plan: ${e.length} ${i}`,...e.map(uJ)];if(t.length>0){n.push("","Required secrets are missing:");for(let r of t)n.push(` ${r}`);n.push("Run `toloka secret set <name>` before apply.")}return n.join(`
317
317
  `)},pJ=async(e,t,i,n)=>{let r=t.map((s)=>({desired:s,dataset:cJ(s.name,i?.datasets[s.name],n)})),o=await Promise.all(r.map(async({dataset:s})=>s===void 0?[]:ts(e.datasets.listAllFields({datasetId:s.id}))));return r.map(({desired:s,dataset:a},l)=>{let g=o[l]??[],d=new Map(g.map((c)=>[c.name,c]));return{...s,...a===void 0?{}:{dataset:a},liveFields:g,missingFields:s.fields.filter((c)=>!d.has(c.name)),conflictingFields:s.fields.filter((c)=>{let I=d.get(c.name);return I!==void 0&&De(I.jsonSchema)!==De(c.jsonSchema)})}})},CJ=(e,t,i)=>{if(t===void 0)return[];let n=e.definition.dataset,r=t.graph.nodes.find((a)=>a.type==="root")?.settings.datasetId;if(n===void 0&&r!==void 0)return[{kind:"node",action:"removed",label:"root dataset binding",id:"root"}];let o=n===void 0?void 0:i.find((a)=>a.name===n)?.dataset;if(n!==void 0&&o===void 0)return[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}];let s=Jo(e.definition,o===void 0?{}:{datasetId:o.id});return gJ(bu(s,t.graph),t.graph)},AJ=async(e,t,i,n,r)=>{let o=t.pipelines.map((a)=>({source:a,pipeline:IJ(a,i?.pipelines[a.sourceDirectory],r)})),s=await Promise.all(o.map(async({pipeline:a})=>a===void 0?void 0:e.pipelines.getGraph({pipelineId:a.id})));return o.map(({source:a,pipeline:l},g)=>{let d=s[g];return{source:a,...l===void 0?{}:{pipeline:l},...d===void 0?{}:{snapshot:d},graphChanges:CJ(a,d,n)}})},fJ=(e,t,i,n,r)=>{let o=[];for(let s of r)o.push({kind:"pipeline",action:"removed",label:s});for(let s of n)o.push({kind:"dataset",action:"removed",label:s});for(let s of e){if(s.dataset===void 0)o.push({kind:"dataset",action:"added",label:s.name});for(let a of s.missingFields)o.push({kind:"datasetField",action:"added",label:a.name,dataset:s.name});for(let a of s.conflictingFields)o.push({kind:"datasetField",action:"changed",label:a.name,dataset:s.name})}for(let s of t)if(s.pipeline===void 0)o.push({kind:"pipeline",action:"added",label:s.source.sourceDirectory});else for(let a of s.graphChanges)o.push({...a,pipeline:s.source.sourceDirectory});for(let s of i)o.push({kind:"secret",action:"missing",label:s});return o},xl=async(e,t)=>{let i=t.source??await Br(t.sourceRoot);dJ(i);let n=await ke(t.sourceRoot),r=t.projectId??n?.projectId;N(r);let o=n?.projectId===r?n:void 0,s=new Set(i.pipelines.flatMap(({definition:y})=>FV(y.graph))),a=t.listAllSecrets===!0||s.size>0,[l,g,d]=await Promise.all([ts(e.pipelines.listAll({projectId:r})),ts(e.datasets.listAll({projectId:r})),a?e.secrets.list({projectId:r}):Promise.resolve([])]),c=kl(i),I=Object.keys(o?.datasets??{}).filter((y)=>!c.some((W)=>W.name===y)).toSorted(),m=Object.keys(o?.pipelines??{}).filter((y)=>!i.pipelines.some((W)=>W.sourceDirectory===y)).toSorted(),p=await pJ(e,c,o,g),C=await AJ(e,i,o,p,l),h=new Set(d.map((y)=>y.name)),Z=[...s].filter((y)=>!h.has(y)).toSorted();return{projectId:r,source:i,state:n,datasets:p,pipelines:C,livePipelines:l,liveDatasets:g,liveSecrets:d,changes:fJ(p,C,Z,I,m),missingSecrets:Z,removedDatasets:I,removedPipelines:m}},vV=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",hJ=(e)=>{let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},bJ=(e)=>{let t=Map.groupBy(e,(i)=>vV(i.name));return new Map(e.map((i)=>{let n=vV(i.name),r=(t.get(n)?.length??0)>1;return[i.id,`pipelines/${r?`${n}-${hJ(i.id)}`:n}`]}))};async function xV(e,t){let i=(await ts(e.pipelines.listAll({projectId:t.projectId}))).toSorted((y,W)=>y.name.localeCompare(W.name)||y.id.localeCompare(W.id)),n=await Promise.all(i.map((y)=>e.pipelines.getGraph({pipelineId:y.id}))),r=new Set;for(let y of n){let W=y.graph.nodes.find((u)=>u.type==="root")?.settings.datasetId;if(W!==void 0)r.add(W)}let o=await ts(e.datasets.listAll({projectId:t.projectId})),s=[];for(let y of[...r].toSorted()){let W=o.find((u)=>u.id===y);f(W,`Project ${t.projectId} has no dataset ${y}.`,{hint:{description:"Check toloka dataset list; the pipeline's dataset binding must point at a dataset of this project."}}),s.push(W)}let a=new Map(s.map((y)=>[y.id,y])),l=bJ(i),g={},d={},c={};for(let[y,W]of i.entries()){let u=n[y];f(u,`Pipeline ${W.id} has no graph snapshot.`,{hint:Y});let A=u.graph.nodes.find((S)=>S.type==="root")?.settings.datasetId,b=A===void 0?void 0:a.get(A);if(f(A===void 0||b!==void 0,`Pipeline ${W.id} references unknown dataset ${A}.`,{hint:{description:"Check toloka dataset list; the pipeline's dataset binding must point at a dataset of this project."}}),b!==void 0){let S=c[b.name];f(S===void 0||S.datasetId===b.id,`Project has multiple referenced datasets named "${b.name}".`,{hint:{description:"Rename the duplicate datasets in the platform, then re-run toloka import."}}),c[b.name]={datasetId:b.id}}let R=l.get(W.id);f(R,`Pipeline ${W.id} has no source directory.`,{hint:Y}),d[R]={pipelineId:W.id};for(let[S,E]of Object.entries(wV(u.graph,{...b===void 0?{}:{dataset:b.name},invalidFieldSchemas:u.invalidFieldSchemas})))g[`${R}/${S}`]=E}await gi.mkdir(t.sourceRoot,{recursive:!0});let I=Wn.join(t.sourceRoot,"pipelines"),m=!1;try{m=(await gi.stat(I)).isDirectory()}catch(y){if(!(y instanceof Error)||!("code"in y)||y.code!=="ENOENT")throw y}if(f(!m||t.force===!0,`Folder already exists: ${I}. Pass --force to replace it.`,{hint:{disabled:!0}}),m)await gi.rm(I,{recursive:!0,force:!0});for(let[y,W]of Object.entries(g).toSorted(([u],[A])=>u.localeCompare(A))){let u=Wn.join(t.sourceRoot,y);await gi.mkdir(Wn.dirname(u),{recursive:!0}),await gi.writeFile(u,W,"utf8")}let p={projectId:t.projectId,pipelines:d,datasets:c};await _i(t.sourceRoot,p);let C=[...Object.keys(g),un].toSorted(),h=i.length===1?"pipeline":"pipelines",Z=s.length===1?"dataset":"datasets";return{state:p,files:C,output:`Imported project ${t.projectId} with ${i.length} ${h} and ${s.length} ${Z} into ${Wn.resolve(t.sourceRoot)}.`}}async function SV(e,t){let i=await xl(e,t);return{projectId:i.projectId,changes:i.changes,missingSecrets:i.missingSecrets,output:mJ(i.changes,i.missingSecrets)}}async function EV(e,t){let i=t.projectId;N(i);let n=await e.projects.get({projectId:i}),r=await xl(e,{...t,listAllSecrets:!0}),o=r.changes.length,s=o===0?"Source has no pending changes.":`Source has ${o} pending change${o===1?"":"s"}.`;return{projectId:i,output:[`Project: ${i} (${n.name})`,`Team: ${n.teamId}`,`Pipelines: ${r.livePipelines.length}`,`Datasets: ${r.liveDatasets.length}`,`Secrets: ${r.liveSecrets.length}`,s].join(`
318
318
  `)}}var ZJ=async(e,t,i,n)=>{let r=t.source.definition.dataset,o=r===void 0?void 0:i.get(r);if(f(r===void 0||o!==void 0,`Dataset ${r} has no resolved ID.`,{hint:Y}),n!==void 0){if(o===void 0)return{pipelineId:n,writes:0};return await e.pipelines.attachDataset({pipelineId:n,datasetId:o}),{pipelineId:n,writes:1}}f(t.pipeline,`Pipeline ${t.source.sourceDirectory} has no live pipeline.`,{hint:Y});let s=Jo(t.source.definition,o===void 0?{}:{datasetId:o}),a=t.pipeline.id;if(t.graphChanges.length===0)return{pipelineId:a,writes:0};let l=t.snapshot;return f(l,`Pipeline ${a} has no graph snapshot.`,{hint:Y}),await e.pipelines.replaceGraph({pipelineId:a,graph:bu(s,l.graph),expectedVersion:l.version}),{pipelineId:a,writes:1}};async function NV(e,t){let i=await xl(e,t);f(i.removedPipelines.length===0,`Refusing to delete pipelines absent from source: ${i.removedPipelines.join(", ")}.`,{hint:{description:"Restore the pipeline in source, or run toloka project untrack pipeline <name> to stop managing it."}});let n=i.pipelines.filter((p)=>p.graphChanges.some((C)=>C.label==="root dataset binding"&&C.action==="removed")).map((p)=>p.source.sourceDirectory);f(n.length===0,`Refusing to unbind the dataset of ${n.join(", ")}: the source declares no dataset, but the pipeline has one on the platform.`,{hint:{description:"Declare the dataset in definePipeline; toloka import writes the name of the bound dataset."}}),f(i.removedDatasets.length===0,`Refusing to delete datasets absent from source: ${i.removedDatasets.join(", ")}. Dataset items are never deleted.`,{hint:{description:"Restore the dataset in source, or run toloka project untrack dataset <name> to stop managing it."}}),f(i.missingSecrets.length===0,`Required secrets are missing: ${i.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`,{hint:{disabled:!0}});let r=i.datasets.flatMap((p)=>p.conflictingFields.map((C)=>`${p.name}.${C.name}`));f(r.length===0,`Dataset field schemas conflict with source: ${r.join(", ")}. Existing fields are never rewritten.`,{hint:{description:"Add the changed columns under new field names, or create a new dataset for the new schema."}});let o=i.pipelines.filter((p)=>p.pipeline===void 0||p.graphChanges.length>0).flatMap((p)=>gl(p.source.definition.graph).map((C)=>`- ${p.source.sourceDirectory}, node ${C.node}, ${C.setting}: ${C.reason}`));f(o.length===0,`The platform would reject these pipelines:
319
319
  ${o.join(`
320
320
  `)}`,{hint:{description:"Fix the listed nodes in source; toloka check reports the same rules as warnings."}});let s=0,a=new Map;for(let p of i.pipelines){if(p.pipeline!==void 0)continue;let C=await e.pipelines.import({projectId:i.projectId,name:p.source.name,graph:Jo(p.source.definition,{})});a.set(p.source.sourceDirectory,C.id),s+=1}let l=new Map;for(let p of i.datasets){let C=p.dataset;if(C===void 0)C=await e.datasets.create({projectId:i.projectId,name:p.name}),s+=1;if(l.set(p.name,C.id),p.missingFields.length>0)await e.datasets.createFields({datasetId:C.id,fields:p.missingFields.map((h)=>({name:h.name,jsonSchema:h.jsonSchema}))}),s+=p.missingFields.length}let g=new Map;for(let p of i.pipelines){let C=await ZJ(e,p,l,a.get(p.source.sourceDirectory));g.set(p.source.sourceDirectory,C.pipelineId),s+=C.writes}let d={projectId:i.projectId,pipelines:Object.fromEntries(i.source.pipelines.map((p)=>{let C=g.get(p.sourceDirectory);return f(C,`Pipeline ${p.sourceDirectory} has no resolved ID.`,{hint:Y}),[p.sourceDirectory,{pipelineId:C}]})),datasets:Object.fromEntries(i.datasets.map((p)=>{let C=l.get(p.name);return f(C,`Dataset ${p.name} has no resolved ID.`,{hint:Y}),[p.name,{datasetId:C}]}))};if(De(i.state)!==De(d))await _i(t.sourceRoot,d);let c=s===0?"unchanged":"changed",I=i.changes.length,m=s===0?"No changes.":`Applied ${I} planned ${I===1?"change":"changes"} with ${s} platform ${s===1?"write":"writes"} to project ${i.projectId}.`;return{action:c,state:d,changes:i.changes,writes:s,output:m}}var yJ=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),hu="not_ran_node_check",TV="running_node_check",YV=(e)=>e.issues.some((t)=>t.code===TV),WJ=(e)=>e.code==="empty_node_checks"?{...e,message:"No stored check cases are configured for this node"}:e,VJ=(e)=>{let t=new Set,i=e.issues.flatMap((s)=>{let a=WJ(s),l=[a.code,a.severity,a.nodeId??"",a.checkId??"",a.message].join(`
321
- `);if(t.has(l))return[];return t.add(l),[a]}),n=i.some((s)=>s.code===hu),o=i.some((s)=>s.severity==="error"&&s.code!==hu)||!e.valid&&!n?"invalid":n?"checks_pending":"valid";return{status:o,report:{...e,valid:o!=="invalid",issues:i}}},RJ=(e)=>e.issues.map((t)=>{let i=yJ(t);return` ${t.code===hu?"pending":t.code===TV?"running":t.severity} ${t.code}${i.length===0?"":` ${i}`}: ${t.message}`}),BJ=(e)=>new Promise((t)=>{setTimeout(t,e)}),GJ=async(e,t)=>{try{let{report:i,status:n}=await t.validate();return e[t.index]={...e[t.index],report:i,status:n},YV(i)?{index:t.index,validate:t.validate}:void 0}catch(i){return{...t,failure:i instanceof Error?i.message:String(i)}}},wJ=async(e,t,i,n)=>{let r=n+i.timeoutMs,o=t;while(o.length>0&&Date.now()<r){await BJ(Math.min(i.pollIntervalMs,r-Date.now()));let a=[];for(let l of o){let g=await GJ(e,l);if(g!==void 0)a.push(g)}o=a}let s=Math.round((Date.now()-n)/1000);for(let a of o){let l=e[a.index];e[a.index]={...l,status:l.status==="invalid"?"invalid":"checks_running",note:a.failure===void 0?`checks are still running after ${s}s; run toloka validate --wait again`:`validation failed while waiting (${a.failure}); run toloka validate --wait again`}}},FJ=async(e,t,i,n)=>{let{sourceDirectory:r}=i.source,o=i.source.definition.dataset,s=o===void 0?void 0:t.datasets.find((C)=>C.name===o)?.dataset;if(i.pipeline===void 0)return{result:{sourceDirectory:r,skipped:"pipeline is not on the platform yet; run toloka apply first"}};if(o!==void 0&&s===void 0)return{result:{sourceDirectory:r,pipelineId:i.pipeline.id,skipped:`dataset "${o}" is not on the platform yet; run toloka apply first`}};let a=Jo(i.source.definition,s===void 0?{}:{datasetId:s.id}),l=i.snapshot===void 0?a:bu(a,i.snapshot.graph),g=i.pipeline.id,d=async()=>VJ(await e.pipelines.validateGraph({pipelineId:g,graph:l})),{report:c,status:I}=await d(),m=n!==void 0&&YV(c),p=m&&i.graphChanges.length>0;return{result:{sourceDirectory:r,pipelineId:g,report:c,status:I,...p?{note:"lints run on the applied graph; run toloka apply, then toloka validate --wait"}:{}},...m&&!p?{poll:d}:{}}},HJ=(e)=>{if(e.skipped!==void 0)return[`- ${e.sourceDirectory}: skipped (${e.skipped})`];return f(e.report,`Pipeline ${e.sourceDirectory} is missing a validation report`,{hint:Y}),f(e.status,`Pipeline ${e.sourceDirectory} is missing a validation status`,{hint:Y}),[`- ${e.sourceDirectory}: ${e.status.replace("_","-")}`,...RJ(e.report),...e.note===void 0?[]:[` note: ${e.note}`]]};async function OV(e,t){let i=Date.now(),n=await xl(e,t),{wait:r}=t,o=[],s=[];for(let g of n.pipelines){let{result:d,poll:c}=await FJ(e,n,g,r);if(o.push(d),c!==void 0)s.push({index:o.length-1,validate:c})}if(r!==void 0)await wJ(o,s,r,i);let a=o.every((g)=>g.status!=="invalid"&&g.status!=="checks_running"),l=o.flatMap(HJ);return{projectId:n.projectId,results:o,valid:a,output:l.length===0?"No pipelines to validate.":l.join(`
321
+ `);if(t.has(l))return[];return t.add(l),[a]}),n=i.some((s)=>s.code===hu),o=i.some((s)=>s.severity==="error"&&s.code!==hu)||!e.valid&&!n?"invalid":n?"checks_pending":"valid";return{status:o,report:{...e,valid:o!=="invalid",issues:i}}},RJ=(e)=>[...e.issues.filter((t)=>t.severity!=="info"),...e.issues.filter((t)=>t.severity==="info")].map((t)=>{let i=yJ(t);return` ${t.code===hu?"pending":t.code===TV?"running":t.severity} ${t.code}${i.length===0?"":` ${i}`}: ${t.message}`}),BJ=(e)=>new Promise((t)=>{setTimeout(t,e)}),GJ=async(e,t)=>{try{let{report:i,status:n}=await t.validate();return e[t.index]={...e[t.index],report:i,status:n},YV(i)?{index:t.index,validate:t.validate}:void 0}catch(i){return{...t,failure:i instanceof Error?i.message:String(i)}}},wJ=async(e,t,i,n)=>{let r=n+i.timeoutMs,o=t;while(o.length>0&&Date.now()<r){await BJ(Math.min(i.pollIntervalMs,r-Date.now()));let a=[];for(let l of o){let g=await GJ(e,l);if(g!==void 0)a.push(g)}o=a}let s=Math.round((Date.now()-n)/1000);for(let a of o){let l=e[a.index];e[a.index]={...l,status:l.status==="invalid"?"invalid":"checks_running",note:a.failure===void 0?`checks are still running after ${s}s; run toloka validate --wait again`:`validation failed while waiting (${a.failure}); run toloka validate --wait again`}}},FJ=async(e,t,i,n)=>{let{sourceDirectory:r}=i.source,o=i.source.definition.dataset,s=o===void 0?void 0:t.datasets.find((C)=>C.name===o)?.dataset;if(i.pipeline===void 0)return{result:{sourceDirectory:r,skipped:"pipeline is not on the platform yet; run toloka apply first"}};if(o!==void 0&&s===void 0)return{result:{sourceDirectory:r,pipelineId:i.pipeline.id,skipped:`dataset "${o}" is not on the platform yet; run toloka apply first`}};let a=Jo(i.source.definition,s===void 0?{}:{datasetId:s.id}),l=i.snapshot===void 0?a:bu(a,i.snapshot.graph),g=i.pipeline.id,d=async()=>VJ(await e.pipelines.validateGraph({pipelineId:g,graph:l})),{report:c,status:I}=await d(),m=n!==void 0&&YV(c),p=m&&i.graphChanges.length>0;return{result:{sourceDirectory:r,pipelineId:g,report:c,status:I,...p?{note:"lints run on the applied graph; run toloka apply, then toloka validate --wait"}:{}},...m&&!p?{poll:d}:{}}},HJ=(e)=>{if(e.skipped!==void 0)return[`- ${e.sourceDirectory}: skipped (${e.skipped})`];return f(e.report,`Pipeline ${e.sourceDirectory} is missing a validation report`,{hint:Y}),f(e.status,`Pipeline ${e.sourceDirectory} is missing a validation status`,{hint:Y}),[`- ${e.sourceDirectory}: ${e.status.replace("_","-")}`,...RJ(e.report),...e.note===void 0?[]:[` note: ${e.note}`]]};async function OV(e,t){let i=Date.now(),n=await xl(e,t),{wait:r}=t,o=[],s=[];for(let g of n.pipelines){let{result:d,poll:c}=await FJ(e,n,g,r);if(o.push(d),c!==void 0)s.push({index:o.length-1,validate:c})}if(r!==void 0)await wJ(o,s,r,i);let a=o.every((g)=>g.status!=="invalid"&&g.status!=="checks_running"),l=o.flatMap(HJ);return{projectId:n.projectId,results:o,valid:a,output:l.length===0?"No pipelines to validate.":l.join(`
322
322
  `)}}var vJ="uploaded",PJ=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,XV=3;class is extends k{constructor(e,t){super(e,t);this.name="DatasetUploadError"}}var kJ=(e)=>PJ.test(e)?e.toLowerCase():void 0,xJ={json:"application/json",jsonl:"application/x-ndjson",csv:"text/csv"},Zu=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),ns=(e)=>{if(!Zu(e))return"unknown";if(Array.isArray(e.anyOf)){let n=[...new Set(e.anyOf.map(ns))];return n.length===0?"unknown":n.join(" | ")}let t=e.type,i=typeof t==="string"?[t]:Array.isArray(t)?t.filter((n)=>typeof n==="string"):[];if(i.length===0)return"unknown";return i.map((n)=>{if(n!=="array")return n;let r=ns(e.items);return r==="unknown"?"array":`array<${r}>`}).join(" | ")},SJ=(e)=>{if(e.length===0)return"No inferred fields are available yet.";return["Types inferred from the uploaded rows (not the column schemas, which keep the constraints declared in source):",...e.toSorted((t,i)=>t.jsonPath.localeCompare(i.jsonPath)).map((t)=>`${" ".repeat(t.depth)}- ${t.jsonPath}: ${ns(t.jsonSchema)}`)].join(`
323
323
  `)},JV=async(e)=>{let t=e.source??await Br(e.sourceRoot),i=kl(t).find((n)=>n.name===e.datasetName);return i===void 0?[]:i.fields.map((n)=>({name:n.name,jsonSchema:n.jsonSchema}))},UV=(e)=>`${e.name} (${e.id})`,El=10,Vn=(e)=>e.length<=El?e.join(", "):`${e.slice(0,El).join(", ")} and ${e.length-El} more`,_V=async(e,t)=>{let i=[];for await(let n of e.datasets.listAll({projectId:t}))i.push(n);return i.toSorted((n,r)=>{let o=n.name.localeCompare(r.name);return o===0?n.id.localeCompare(r.id):o})},at=async(e,t,i)=>{let n=await ke(t.sourceRoot),r=t.projectId??n?.projectId;N(r);let o=t.datasetName,s=await _V(e,r),a=(m)=>s.filter((p)=>p.name===m).length<=1,l=kJ(o),g=s.find((m)=>m.id===o||m.id.toLowerCase()===l);if(g!==void 0)return{datasetId:g.id,name:g.name,nameIsUnique:a(g.name)};let d=s.filter((m)=>m.name===o);if(f(d.length<=1,`Project ${r} has multiple datasets named "${o}": ${d.map(UV).join(", ")}.`,{hint:{description:"Pass the dataset id (ds.\u2026) instead of the name."}}),d.length===1){let[m]=d;return f(m,`Dataset "${o}" has no resolved ID.`,{hint:Y}),{datasetId:m.id,name:m.name,nameIsUnique:!0}}let c=n?.projectId===r?n.datasets[o]:void 0;if(c!==void 0){let m=s.find((p)=>p.id===c.datasetId);if(m!==void 0)return{datasetId:m.id,name:m.name,nameIsUnique:a(m.name)}}f(i&&l===void 0,s.length===0?`Dataset "${o}" does not exist in project ${r}. Run toloka dataset create ${JSON.stringify(o)} first, or toloka apply for a dataset a pipeline declares.`:`Dataset "${o}" does not exist in project ${r}. This project has: ${Vn(s.map(UV))}.`,s.length<=El?{hint:{disabled:!0}}:{hint:{description:"Run toloka dataset list to see every dataset of the project."}}),f((await JV(t)).length>0,`Dataset "${o}" does not exist in project ${r} and no pipeline in source declares it. Run toloka dataset create ${JSON.stringify(o)} to create it empty, bind a pipeline to it in source so its columns are known, or upload to an existing dataset.`,{hint:{disabled:!0}});let I=await e.datasets.create({projectId:r,name:o});return{datasetId:I.id,name:I.name,nameIsUnique:!0}},EJ=(e)=>{let t=e.toLowerCase();if(t.endsWith(".json"))return"json";if(t.endsWith(".jsonl"))return"jsonl";if(t.endsWith(".csv"))return"csv";f(!1,`${e} must have a .json, .jsonl, or .csv extension`,{hint:{description:"Rename the file with the extension that matches its format."}})},NJ=async(e)=>{let t=rs.basename(e),i=EJ(t),n=await Er.readFile(e,"utf8");if(i==="jsonl")for(let{line:r,lineNumber:o}of n.split(/\r?\n/u).map((s,a)=>({line:s,lineNumber:a+1})).filter(({line:s})=>s.length>0)){let s;try{s=JSON.parse(r)}catch{f(!1,`${t}:${o} is not valid JSON`,{hint:{description:"Fix the JSON on that line; every line of a JSONL file must be one complete object."}})}f(Zu(s),`${t}:${o} must contain a JSON object`,{hint:{description:"Wrap the value in an object with named fields, one object per line."}})}return{payload:n,format:i,contentType:xJ[i]}},Sl=async(e,t,i)=>{let n=i instanceof Error?i.message:String(i);try{await e.datasets.cancelUpload({uploadId:t})}catch(r){let o=r instanceof Error?r.message:String(r);throw new is(`Dataset upload ${t} failed and could not be canceled. Upload error: ${n}. Cancellation error: ${o}.`,{cause:AggregateError([i,r]),hint:{description:"Check toloka dataset list before re-running toloka dataset upload; an upload that never finalized is cleaned up automatically."}})}throw new is(`Dataset upload ${t} failed and was canceled: ${n}`,{cause:i,hint:{description:"Fix the upload error above, then re-run toloka dataset upload."}})},TJ=async({client:e,started:t,payload:i,contentType:n,fetch:r,retryIntervalMs:o})=>{let s;try{s=await r(t.uploadUrl,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:i})}catch(l){return Sl(e,t.job.id,l)}if(!s.ok)return Sl(e,t.job.id,new is(`Dataset upload failed with HTTP ${s.status}.`,{hint:ni}));let a=0;while(!0)try{await e.datasets.finalizeUpload({uploadId:t.job.id});return}catch(l){if(!(l instanceof K&&l.status===503))return Sl(e,t.job.id,l);if(a+=1,a===XV)return Sl(e,t.job.id,new is(`Storage remained unavailable after ${XV} finalization attempts.`,{cause:l,hint:ni}));let{promise:g,resolve:d}=Promise.withResolvers();setTimeout(d,o),await g}};async function jV(e,t){let i=t.name.trim();f(i.length>0,"Dataset name cannot be empty.",{hint:{description:"Pass a non-empty dataset name."}});let n=await e.datasets.create({projectId:t.projectId,name:i});return{datasetId:n.id,output:`Created dataset ${n.name} (${n.id}). Upload rows with toloka dataset upload ${n.id} <file>.`}}async function DV(e,t){let{payload:i,format:n,contentType:r}=await NJ(t.filePath),o=await at(e,t,!0),s=o.datasetId,a=new Map;for await(let y of e.datasets.listAllFields({datasetId:s})){if(y.internal||y.name===vJ)continue;a.set(y.name,{name:y.name,jsonSchema:y.jsonSchema})}for(let y of await JV({...t,datasetName:o.name}))if(!a.has(y.name))a.set(y.name,y);let l=[...a.values()],g=await e.datasets.startUpload({datasetId:s,filename:rs.basename(t.filePath),format:n,declaredSizeBytes:new TextEncoder().encode(i).byteLength,fields:l});await TJ({client:e,started:g,payload:i,contentType:r,fetch:t.fetch??globalThis.fetch,retryIntervalMs:t.waitFor?.intervalMs??1000});let d=await e.waitFor({type:"datasetUpload",uploadId:g.job.id},t.waitFor),c=o.nameIsUnique?o.name:o.datasetId,I=d.status==="failed"&&d.error?.startsWith("Schema incompatible with existing upload")===!0?`
324
324
  Run toloka dataset fields ${JSON.stringify(c)} to inspect the inferred schema stored from the first successful upload.`:"";f(d.status==="succeeded",`${d.error??`Dataset upload ${d.id} failed.`}${I}`,{hint:{disabled:!0}});let m=`Uploaded ${d.result.itemsIngested} rows to dataset ${o.name}.`,p=[],C,h=[];try{p=(await e.datasets.getInferredFields({datasetId:s})).fields,C=SJ(p)}catch(y){let W=y instanceof Error?y.message:String(y);h.push(`Upload succeeded, but inferred fields could not be fetched: ${W}`)}if(l.length>0)try{await e.waitFor({type:"datasetFields",datasetId:s},t.waitFor)}catch(y){if(!(y instanceof K&&y.code==="wait_timeout"))throw y;h.push(`Upload succeeded, but its rows are still being copied into the dataset fields; check them with toloka dataset columns ${c} --json.`)}let Z=l.length===0&&p.some((y)=>y.depth===1)?`To filter, balance or split by these fields, add them as dataset fields: toloka dataset fields add ${c} <field>\u2026 (or --all).`:void 0;return{datasetId:s,rowsUploaded:d.result.itemsIngested,inferredFields:p,output:[m,C,Z].filter((y)=>y!==void 0).join(`
@@ -362,7 +362,7 @@ ${o}`}}async function LV(e,t){let i=await _V(e,t.projectId);if(i.length===0)retu
362
362
  `)}}var HB=(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},D_=(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(" "))},vB=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let r of e.subLines??[])if(HB(r))n.push(...vB(r,t+1));return n},z_=(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(HB(r))t.push(...vB(r,1));continue}i.push(n.kind==="validation-errors"?` ${n.nodeNameDisplay} skipped (validation errors)`:` ${n.nodeNameDisplay} not billed`)}return{billed:t,unpriced:i}},L_=(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},Q_=(e,t)=>{let{billed:i,unpriced:n}=z_(e.nodes),r=L_(e.total),o=D_([["Item","Expected","Maximum"],...i,...r]),s=o.slice(0,1+i.length),a=o.slice(1+i.length),l=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...s];if(i.length===0)l.push(" (no billed nodes)");if(l.push("",...a),n.length>0)l.push("","Not billed",...n);if(e.isInternalPricing===!0)l.push("","Internal-team pricing.");return l.push("",e.disclaimer),l.join(`
363
363
  `)};async function PB(e,t){let i=await Jr({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:i.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:Q_(n,i.name)}}var kB=(e,t)=>{let{context:i,exitCode:n,globals:r}=t,o="pipeline name or id; required unless a TTY picker can choose among several",s=e.command("pipeline").description("operate on a live pipeline in the selected project");s.command("list").option("--limit <n>","maximum pipelines to list",se).description("list live pipelines in the selected project").action(async(a)=>{let{client:l,projectId:g,state:d}=await w(r(),i);N(g);let c=await bB({client:l,projectId:g,state:d,...a.limit===void 0?{}:{limit:a.limit}});i.io.stdout(c.output)}),s.command("run").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long the command may wait in total, for the lints and, with --wait, for the run",se).description("start a run on an applied pipeline").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await w(r(),i);N(c);let I=await RB(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},wait:l.wait,...l.timeout===void 0?{}:{timeoutMs:l.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output),n.value=$o(I.outcome)}),s.command("lint").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--wait","wait for the lints to finish",!1).option("--timeout <ms>","how long to wait",se).description("run the pipeline's lints that have no current result").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await w(r(),i);N(c);let I=await VB(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},wait:l.wait,...l.timeout===void 0?{}:{timeoutMs:l.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output),n.value=$o(I.outcome)}),s.command("status").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").description("report the latest run's state and item counts").action(async(a)=>{let{client:l,state:g,projectId:d}=await w(r(),i);N(d);let c=await GB(l,{projectId:d,state:g,...a===void 0?{}:{pipeline:a},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(c.output),n.value=$o(c.outcome)}),s.command("runs").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--limit <n>","how many runs to list",se).description("list recent runs").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await w(r(),i);N(c);let I=await BB(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},...l.limit===void 0?{}:{limit:l.limit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output)}),s.command("cost").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--item-limit <n>","cap how many items to price",se).description("forecast what a run of this pipeline would bill").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await w(r(),i);N(c);let I=await PB(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},...l.itemLimit===void 0?{}:{itemLimit:l.itemLimit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output)}),s.command("cancel").argument("<runId>","run to cancel").option("--accept-without-review","accept items in Human QA without review now; you pay for them as for completed items",!1).description("request cancellation of a run").action(async(a,l)=>{let{client:g}=await w(r(),i),d=await wB(g,{runId:a,acceptWithoutReview:l.acceptWithoutReview});i.io.stdout(d.output)}),s.command("results").argument("<runId>","run to read").option("--limit <n>","maximum matching items to return (default 20). With --failed, scans up to 500 items, or --limit if larger",se).option("--failed","only report failed items",!1).description("report a run's items").action(async(a,l)=>{let{client:g}=await w(r(),i),d=await FB(g,{runId:a,failedOnly:l.failed,...l.limit===void 0?{}:{limit:l.limit}});i.io.stdout(d.output),n.value=$o(d.outcome)})};var K_=["read","write","deploy","labeling-read","labeling-write","labeling-deploy"],xB=(e,t)=>{let{context:i,exitCode:n,globals:r}=t,o=e.command("project").description("select and manage the current platform project");o.command("list").option("--limit <n>","maximum projects to list",se).description("list remote projects this key can see").action(async(a)=>{let l=r(),{client:g,stored:d,state:c}=await w(l,i),I=Gl(l,i,d,c);await FW({client:g,io:i.io,...I===void 0?{}:{context:I},...a.limit===void 0?{}:{limit:a.limit}})}),o.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(a,l)=>{let g=r(),d=await pi(i.environment),{client:c}=await hn(g,i,void 0,d.credentials);await vW({environment:i.environment,flags:g,client:c,io:i.io,afterPreflight:async()=>fn(c,i.analytics),...a===void 0?{}:{alias:a},...l===void 0?{}:{projectId:l}})}),o.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(a)=>{await PW({environment:i.environment,flags:r(),alias:a,io:i.io})}),o.command("current").description("show the project this command would use").action(async()=>{let a=r(),l=await lu(a,i),g=await Be(a,i.io),d=await ke(g);if(xW({flags:a,environment:i.environment,stored:l,...d===void 0?{}:{state:d},io:i.io}).project===void 0)n.value=1}),o.command("url").description("print the current project URL").action(async()=>{let{baseUrl:a,client:l,projectId:g}=await w(r(),i);N(g);let d=await l.projects.get({projectId:g}),c=new URL(`/teams/${encodeURIComponent(d.teamId)}/projects/${encodeURIComponent(d.id)}`,a);i.io.stdout(c.href)}),o.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(a)=>{await kW({environment:i.environment,flags:r(),alias:a,io:i.io})}),o.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(a,l,g)=>{f(a==="pipeline"||a==="dataset","Resource type must be pipeline or dataset.",{hint:{description:"Run toloka project untrack pipeline <name> or toloka project untrack dataset <name>."}});let d=await Be(r(),i.io);await HW({sourceRoot:d,type:a,name:l,confirm:g.confirm,io:i.io})}),o.command("token").addOption(new ei("--preset <name>","permission preset").choices(K_).default("write")).option("--permissions <list>","comma-separated resource:operation pairs instead of a preset").option("--expires-in <seconds>","lifetime in seconds (60..21600)",se).option("--projects <list>","comma-separated ids of further projects the token may act in (same team)").description("mint a project-scoped token for agents and scripts; printed once, never stored").action(async(a)=>{let{client:l,credential:g,projectId:d}=await w(r(),i);N(d);let c=g.type==="scopedToken"||g.type==="apiKey"&&g.apiKey.startsWith(WI);f(!c,"A scoped token cannot issue tokens.",{hint:{disabled:!0}});let I=a.permissions===void 0?{preset:a.preset}:{permissions:a.permissions.split(",").map((C)=>C.trim())},{token:m,expiresAt:p}=await l.projects.createToken({projectId:d,...I,...a.expiresIn===void 0?{}:{expiresInSeconds:a.expiresIn},...a.projects===void 0?{}:{projectIds:a.projects.split(",").map((C)=>C.trim())}});i.io.stdout(m),i.io.stderr(`Token expires at ${p}. Use it as TOLOKA_SCOPED_TOKEN.`)}),o.command("tokens").description("list live project-scoped tokens").action(async()=>{let{client:a,projectId:l}=await w(r(),i);N(l);let g=[];for await(let d of a.projects.listAllTokens({projectId:l}))g.push(d);i.io.stdout(g.length===0?"No live tokens.":_([["Id","User","Expires","Projects","Permissions"],...g.map((d)=>[d.id,d.userId,d.expiresAt,d.projectIds.join(","),d.permissions.join(",")])]))}),o.command("revoke-token").argument("<tokenId>","token id from toloka project tokens").description("revoke a project-scoped token; it stops working immediately").action(async(a)=>{let{client:l,projectId:g}=await w(r(),i);N(g),await l.projects.revokeToken({projectId:g,tokenId:a}),i.io.stdout(`Revoked ${a}.`)}),o.command("revoke-tokens").description("revoke every live project-scoped token of the project; they stop working immediately").action(async()=>{let{client:a,projectId:l}=await w(r(),i);N(l);let{revokedCount:g}=await a.projects.revokeAllTokens({projectId:l});i.io.stdout(`Revoked ${g} token${g===1?"":"s"}.`)});let s=o.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");s.option("--delivery-order-id <id>","Sunday delivery order id (required when the owning team is internal)"),s.action(async(a,l)=>{let g=r(),d=await pi(i.environment),{client:c}=await hn(g,i,void 0,d.credentials),I=await Be(g,i.io);await SW({environment:i.environment,flags:g,client:c,io:i.io,sourceRoot:I,afterPreflight:async()=>fn(c,i.analytics),...a===void 0?{}:{alias:a},...l.name===void 0?{}:{name:l.name},...l.teamId===void 0?{}:{teamId:l.teamId},...l.deliveryOrderId===void 0?{}:{deliveryOrderId:l.deliveryOrderId}})})};var SB=require("crypto"),nm=require("fs"),Kl=require("fs/promises"),wt=require("path");var M_=262144,$_=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),q_=async(e,t)=>{let i=wt.relative(t,e);if(i===""||i===".."||i.startsWith(`..${wt.sep}`)||wt.isAbsolute(i))return;let n=i.split(wt.sep);for(let r=1;r<n.length;r+=1){let o=wt.join(t,...n.slice(0,r)),s=await Kl.lstat(o);f(!s.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${o}; select a path that does not traverse symbolic links.`,{hint:{disabled:!0}})}},ej=async(e,t,i)=>{let n=wt.resolve(i,e);await q_(n,t);let r;try{r=await Kl.open(n,nm.constants.O_RDONLY|nm.constants.O_NOFOLLOW)}catch(o){throw f(!(o instanceof Error&&("code"in o)&&o.code==="ELOOP"),`Report file ${n} is a symbolic link; select the file it points to directly.`,{hint:{disabled:!0}}),o}try{let o=await r.stat();return f(o.isFile(),`Report file ${n} is not a regular file.`,{hint:{description:"Pass the path of a Markdown or text file."}}),f(o.size>0,`Report file ${n} is empty.`,{hint:{description:"Write the report first; the toloka-report-issue skill describes the format."}}),f(o.size<=M_,`Report file ${n} is ${o.size} bytes; the limit is 256 KiB.`,{hint:{description:"Trim the report to under 256 KiB, for example by shortening logs."}}),{handle:r,absolutePath:n,size:o.size}}catch(o){throw await r.close(),o}},tj=async(e,t,i)=>{let n=await ej(e,t,i);try{let r=await n.handle.readFile();f(r.byteLength===n.size,`${n.absolutePath} changed while it was being read.`,{hint:{description:"Re-run toloka report once the file is no longer being written."}});try{return $_.decode(r)}catch{throw new k(`Report file ${n.absolutePath} is not valid UTF-8.`,{hint:{description:"Save the report as UTF-8 text."}})}}finally{await n.handle.close()}},ij=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 EB(e){let{analytics:t,io:i}=e;f(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}});let n=await tj(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 ij(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=SB.randomUUID();return await t.submitIssueReport({reportId:r,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),i.stdout(`Submitted issue report: ${r}`),0}var NB=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",YW,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka").action(async(o,s)=>{f(i.analytics,"Issue reporting requires CLI analytics.",{hint:{description:"Set TOLOKA_TELEMETRY=1 to enable analytics, then re-run toloka report."}});let a=Bl(r()),l=r().baseUrl??i.environment.TOLOKA_BASE_URL??ji(i.environment)??Cn;n.value=await EB({path:o,authoredBy:s.authoredBy,platform:new URL(l).origin,confirm:s.confirm,sourceRoot:a,cwd:process.cwd(),analytics:i.analytics,io:i.io})})};var YB=require("fs/promises");var TB=1e4,Ml=(e)=>`${e} expert${e===1?"":"s"}`,nj=(e,t)=>{if(e instanceof K&&e.status===404){let i=typeof e.body==="string"&&e.body.length>0?e.body:"Not found";throw new k(`${t}: ${i}.`,{cause:e,hint:{description:"Check the id or name you passed and the selected project (toloka status). If both are right, this feature is not enabled for the team."}})}throw e},Ft=async(e,t)=>{try{return await t()}catch(i){return nj(i,e)}},OB=(e,t)=>Ft("Expert lists",()=>e.expertLists.list({projectId:t})),XB=async(e,t)=>{if(t.list.startsWith("exl."))return t.list;let[i,...n]=(await OB(e,t.projectId)).filter((r)=>r.name===t.list);if(i===void 0||n.length>0)throw new k(i===void 0?`No expert list named "${t.list}" in this project.`:`Several expert lists are named "${t.list}"; pass the list id (exl.\u2026) instead.`,{hint:{description:"Run toloka expert-list list to see the lists and their ids."}});return i.id},_r=async(e)=>{let t=e.file===void 0?[]:(await YB.readFile(e.file,"utf8")).split(/\r?\n/u),i=[...new Set([...t,...e.expertIds].map((n)=>n.trim()).filter((n)=>n.length>0))];if(i.length===0)throw new k("No expert IDs given.",{hint:{description:"Pass expert IDs as arguments or a file with one ID per line with --file."}});if(i.length>TB)throw new k(`Too many expert IDs: ${i.length}, at most ${TB}.`,{hint:{description:"Split the file and run the command once per part."}});return i},UB=async(e,t,i)=>{let n=await OB(e,t.projectId);O(i,t.json,n,n.length===0?"No expert lists in this project.":_([["ID","NAME","EXPERTS","HIDDEN"],...n.map((r)=>[r.id,r.name,String(r.expertCount),r.hidden?"yes":"no"])]))},JB=async(e,t,i)=>{let n=await Ft("Expert lists",()=>e.expertLists.create({projectId:t.projectId,name:t.name}));O(i,t.json,n,`Created expert list ${n.id} "${n.name}".`)},_B=async(e,t,i)=>{let n=await Ft("Expert lists",()=>e.expertLists.get({expertListId:t.expertListId})),{stats:r}=n;O(i,t.json,n,_([["ID",n.id],["NAME",n.name],["HIDDEN",n.hidden?"yes":"no"],["EXPERTS",String(n.expertCount)],["AVAILABLE",String(r.available)],["PENDING",String(r.pending)],["UNAVAILABLE",String(r.unavailable)],["NOT FOUND",String(r.notFound)],["BANNED",String(r.banned)]]))},$l=async(e,t,i)=>{let{expertListId:n,...r}=t,o=await Ft("Expert lists",()=>e.expertLists.update({expertListId:n,...r}));i.stdout(`Updated expert list ${o.id} "${o.name}"${o.hidden?" (hidden)":""}.`)},jB=async(e,t,i)=>{let n=await Ft("Expert lists",()=>e.expertLists.addExperts({expertListId:t.expertListId,expertIds:t.expertIds}));i.stdout(`Added ${Ml(n.changedCount)}; experts already in the list were skipped. Availability is checked in the background: run toloka expert-list show to see it.`)},DB=async(e,t,i)=>{let n=await Ft("Expert lists",()=>e.expertLists.removeExperts({expertListId:t.expertListId,expertIds:t.expertIds}));i.stdout(`Removed ${Ml(n.changedCount)}; experts not in the list were skipped.`)},zB=async(e,t,i)=>{let n=await Ft("Expert lists",()=>e.expertLists.listExpertsPage({expertListId:t.expertListId,...t.after===void 0?{}:{after:t.after},...t.limit===void 0?{}:{limit:t.limit}}));O(i,t.json,n,[n.experts.length===0?"No experts.":_([["EXPERT","STATUS"],...n.experts.map((r)=>[r.expertId,r.status])]),...n.nextAfter===null?[]:[`More experts: pass --after ${n.nextAfter}`]].join(`
364
364
  `))},LB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.get({projectId:t.projectId}));O(i,t.json,n,_([["EXPERTS",String(n.expertCount)],["BANNED",String(n.stats.banned)],["PENDING",String(n.stats.pending)],["UNBANNING",String(n.stats.unbanning)],["NOT FOUND",String(n.stats.notFound)]]))},QB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.listExpertsPage({projectId:t.projectId,...t.after===void 0?{}:{after:t.after},...t.limit===void 0?{}:{limit:t.limit}}));O(i,t.json,n,[n.experts.length===0?"No banned experts.":_([["EXPERT","STATUS","REASON"],...n.experts.map((r)=>[r.expertId,r.status,r.reason])]),...n.nextAfter===null?[]:[`More experts: pass --after ${n.nextAfter}`]].join(`
365
- `))},KB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.addExperts({projectId:t.projectId,expertIds:t.expertIds,reason:t.reason}));i.stdout(`Banned ${Ml(n.changedCount)}.`)},MB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.removeExperts({projectId:t.projectId,expertIds:t.expertIds}));i.stdout(`Unbanned ${Ml(n.changedCount)}; experts that were not banned were skipped.`)};var $B=(e,t)=>{let{context:i,globals:n}=t,r=e.command("expert-ban-list").description("manage the project's expert ban list: banned experts can't work on the project");r.command("show").option("--json","print JSON",!1).description("show how many experts are banned and in which status").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await LB(s,{projectId:a,json:o.json},i.io)}),r.command("experts").option("--after <expertId>","start after this expert id, from the previous page").option("--limit <count>","experts per page, up to 1000",se).option("--json","print JSON",!1).description("list a page of the banned experts with their status").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await QB(s,{projectId:a,...o},i.io)}),r.command("add").argument("[expertIds...]","expert ids to ban").option("--file <path>","file with one expert id per line").requiredOption("--reason <text>","why the experts are banned, applied to each of them").description("ban experts: they can't be invited and are removed from the work they're in").action(async(o,s)=>{f(s.reason.trim().length>0,"Missing --reason.",{hint:{description:"Say why the experts are banned with --reason <text>."}});let{client:a,projectId:l}=await w(n(),i);N(l);let g=await _r({expertIds:o,...s.file===void 0?{}:{file:s.file}});await KB(a,{projectId:l,expertIds:g,reason:s.reason},i.io)}),r.command("remove").argument("[expertIds...]","expert ids to unban").option("--file <path>","file with one expert id per line").description("lift the bans of experts").action(async(o,s)=>{let{client:a,projectId:l}=await w(n(),i);N(l);let g=await _r({expertIds:o,...s.file===void 0?{}:{file:s.file}});await MB(a,{projectId:l,expertIds:g},i.io)})};var qB=(e,t)=>{let{context:i,globals:n}=t,r=async(s)=>{let{client:a,projectId:l}=await w(n(),i);return N(l),{client:a,projectId:l,expertListId:await XB(a,{projectId:l,list:s})}},o=e.command("expert-list").description("manage the project's expert lists, which nodes with audienceMode service take experts from");o.command("list").option("--json","print JSON",!1).description("list the project's expert lists").action(async(s)=>{let{client:a,projectId:l}=await w(n(),i);N(l),await UB(a,{projectId:l,json:s.json},i.io)}),o.command("create").argument("<name>","name of the new list").option("--json","print JSON",!1).description("create an empty expert list").action(async(s,a)=>{let{client:l,projectId:g}=await w(n(),i);N(g),await JB(l,{projectId:g,name:s,json:a.json},i.io)}),o.command("show").argument("<list>","list id (exl.\u2026) or name").option("--json","print JSON",!1).description("show a list and how many of its experts are available").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await _B(l,{expertListId:g,json:a.json},i.io)}),o.command("rename").argument("<list>","list id (exl.\u2026) or name").argument("<name>","new name").description("rename a list").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await $l(l,{expertListId:g,name:a},i.io)}),o.command("hide").argument("<list>","list id (exl.\u2026) or name").description("hide a list: its experts can't be added or removed until it is shown again; nodes that use it keep working").action(async(s)=>{let{client:a,expertListId:l}=await r(s);await $l(a,{expertListId:l,hidden:!0},i.io)}),o.command("unhide").argument("<list>","list id (exl.\u2026) or name").description("show a hidden list again").action(async(s)=>{let{client:a,expertListId:l}=await r(s);await $l(a,{expertListId:l,hidden:!1},i.io)}),o.command("experts").argument("<list>","list id (exl.\u2026) or name").option("--after <expertId>","start after this expert id, from the previous page").option("--limit <count>","experts per page, up to 1000",se).option("--json","print JSON",!1).description("list a page of the list's experts with their status").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await zB(l,{expertListId:g,...a},i.io)}),o.command("add").argument("<list>","list id (exl.\u2026) or name").argument("[expertIds...]","expert ids to add").option("--file <path>","file with one expert id per line").description("add experts to a list, from arguments or a file").action(async(s,a,l)=>{let{client:g,expertListId:d}=await r(s),c=await _r({expertIds:a,...l.file===void 0?{}:{file:l.file}});await jB(g,{expertListId:d,expertIds:c},i.io)}),o.command("remove").argument("<list>","list id (exl.\u2026) or name").argument("[expertIds...]","expert ids to remove").option("--file <path>","file with one expert id per line").description("remove experts from a list").action(async(s,a,l)=>{let{client:g,expertListId:d}=await r(s),c=await _r({expertIds:a,...l.file===void 0?{}:{file:l.file}});await DB(g,{expertListId:d,expertIds:c},i.io)})};var g0=require("path");var ig=require("fs/promises"),t0=require("path");var rj='The "customerReview" feature is not enabled for this team',jr=20,ql=1000,eg=8000,tg=(e)=>`${e.toLocaleString("en-US")} characters`,i0=["","The output is cut:",` at most ${jr} quality criteria, and at most ${jr} criteria in each decision;`,` at most ${tg(ql)} of each text: criterion descriptions, comments, LLM QA check reasons;`,` at most ${tg(eg)} of task content, which --json prints as JSON text in taskContentJson.`,"With --json, truncated is null when nothing was cut, and otherwise has:"," taskContentCharacters full length of the task content when it was cut, otherwise null"," truncatedQualityCriterionCount how many quality criteria were left out"," truncatedVerdictCriteria { field, truncatedCount } for each decision whose criteria were cut"," cutTexts { field, characters } for each cut text, with its full length"," hint the --out command that saves the full review","review accept and review reject print the review after the decision in the same cut view."].join(`
365
+ `))},KB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.addExperts({projectId:t.projectId,expertIds:t.expertIds,reason:t.reason}));i.stdout(`Banned ${Ml(n.changedCount)}.`)},MB=async(e,t,i)=>{let n=await Ft("Banned experts",()=>e.expertBanList.removeExperts({projectId:t.projectId,expertIds:t.expertIds}));i.stdout(`Unbanned ${Ml(n.changedCount)}; experts that were not banned were skipped.`)};var $B=(e,t)=>{let{context:i,globals:n}=t,r=e.command("expert-ban-list").description("manage the project's expert ban list: banned experts can't work on the project");r.command("show").option("--json","print JSON",!1).description("show how many experts are banned and in which status").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await LB(s,{projectId:a,json:o.json},i.io)}),r.command("experts").option("--after <expertId>","start after this expert id, from the previous page").option("--limit <count>","experts per page, up to 1000",se).option("--json","print JSON",!1).description("list a page of the banned experts with their status").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await QB(s,{projectId:a,...o},i.io)}),r.command("add").argument("[expertIds...]","expert ids to ban").option("--file <path>","file with one expert id per line").requiredOption("--reason <text>","why the experts are banned, applied to each of them").description("ban experts: they can't be invited and are removed from the work they're in").action(async(o,s)=>{f(s.reason.trim().length>0,"Missing --reason.",{hint:{description:"Say why the experts are banned with --reason <text>."}});let{client:a,projectId:l}=await w(n(),i);N(l);let g=await _r({expertIds:o,...s.file===void 0?{}:{file:s.file}});await KB(a,{projectId:l,expertIds:g,reason:s.reason},i.io)}),r.command("remove").argument("[expertIds...]","expert ids to unban").option("--file <path>","file with one expert id per line").description("lift the bans of experts").action(async(o,s)=>{let{client:a,projectId:l}=await w(n(),i);N(l);let g=await _r({expertIds:o,...s.file===void 0?{}:{file:s.file}});await MB(a,{projectId:l,expertIds:g},i.io)})};var qB=(e,t)=>{let{context:i,globals:n}=t,r=async(s)=>{let{client:a,projectId:l}=await w(n(),i);return N(l),{client:a,projectId:l,expertListId:await XB(a,{projectId:l,list:s})}},o=e.command("expert-list").description("manage the project's expert lists, which nodes can take their experts from");o.command("list").option("--json","print JSON",!1).description("list the project's expert lists").action(async(s)=>{let{client:a,projectId:l}=await w(n(),i);N(l),await UB(a,{projectId:l,json:s.json},i.io)}),o.command("create").argument("<name>","name of the new list").option("--json","print JSON",!1).description("create an empty expert list").action(async(s,a)=>{let{client:l,projectId:g}=await w(n(),i);N(g),await JB(l,{projectId:g,name:s,json:a.json},i.io)}),o.command("show").argument("<list>","list id (exl.\u2026) or name").option("--json","print JSON",!1).description("show a list and how many of its experts are available").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await _B(l,{expertListId:g,json:a.json},i.io)}),o.command("rename").argument("<list>","list id (exl.\u2026) or name").argument("<name>","new name").description("rename a list").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await $l(l,{expertListId:g,name:a},i.io)}),o.command("hide").argument("<list>","list id (exl.\u2026) or name").description("hide a list: its experts can't be added or removed until it is shown again; nodes that use it keep working").action(async(s)=>{let{client:a,expertListId:l}=await r(s);await $l(a,{expertListId:l,hidden:!0},i.io)}),o.command("unhide").argument("<list>","list id (exl.\u2026) or name").description("show a hidden list again").action(async(s)=>{let{client:a,expertListId:l}=await r(s);await $l(a,{expertListId:l,hidden:!1},i.io)}),o.command("experts").argument("<list>","list id (exl.\u2026) or name").option("--after <expertId>","start after this expert id, from the previous page").option("--limit <count>","experts per page, up to 1000",se).option("--json","print JSON",!1).description("list a page of the list's experts with their status").action(async(s,a)=>{let{client:l,expertListId:g}=await r(s);await zB(l,{expertListId:g,...a},i.io)}),o.command("add").argument("<list>","list id (exl.\u2026) or name").argument("[expertIds...]","expert ids to add").option("--file <path>","file with one expert id per line").description("add experts to a list, from arguments or a file").action(async(s,a,l)=>{let{client:g,expertListId:d}=await r(s),c=await _r({expertIds:a,...l.file===void 0?{}:{file:l.file}});await jB(g,{expertListId:d,expertIds:c},i.io)}),o.command("remove").argument("<list>","list id (exl.\u2026) or name").argument("[expertIds...]","expert ids to remove").option("--file <path>","file with one expert id per line").description("remove experts from a list").action(async(s,a,l)=>{let{client:g,expertListId:d}=await r(s),c=await _r({expertIds:a,...l.file===void 0?{}:{file:l.file}});await DB(g,{expertListId:d,expertIds:c},i.io)})};var g0=require("path");var ig=require("fs/promises"),t0=require("path");var rj='The "customerReview" feature is not enabled for this team',jr=20,ql=1000,eg=8000,tg=(e)=>`${e.toLocaleString("en-US")} characters`,i0=["","The output is cut:",` at most ${jr} quality criteria, and at most ${jr} criteria in each decision;`,` at most ${tg(ql)} of each text: criterion descriptions, comments, LLM QA check reasons;`,` at most ${tg(eg)} of task content, which --json prints as JSON text in taskContentJson.`,"With --json, truncated is null when nothing was cut, and otherwise has:"," taskContentCharacters full length of the task content when it was cut, otherwise null"," truncatedQualityCriterionCount how many quality criteria were left out"," truncatedVerdictCriteria { field, truncatedCount } for each decision whose criteria were cut"," cutTexts { field, characters } for each cut text, with its full length"," hint the --out command that saves the full review","review accept and review reject print the review after the decision in the same cut view."].join(`
366
366
  `),rm=(e)=>{let t=[],i=(m,p)=>{if(p.length<=ql)return p;return t.push({field:m,characters:p.length}),`${p.slice(0,ql)}\u2026 (${tg(p.length-ql)} more)`},{taskContent:n,qualityCriteria:r,verdicts:o,...s}=e,a=r.slice(0,jr).map((m,p)=>({...m,qualityElement:i(`qualityCriteria[${p}].qualityElement`,m.qualityElement),pass:i(`qualityCriteria[${p}].pass`,m.pass),fail:i(`qualityCriteria[${p}].fail`,m.fail)})),l=o.map((m,p)=>({...m,criteria:m.criteria.slice(0,jr),comment:i(`verdicts[${p}].comment`,m.comment),llmQaCheck:m.llmQaCheck===null?null:{...m.llmQaCheck,reason:i(`verdicts[${p}].llmQaCheck.reason`,m.llmQaCheck.reason)}})),g=JSON.stringify(n,null,2),d=g.length>eg,c=r.length-a.length,I=o.flatMap(({criteria:m},p)=>m.length>jr?[{field:`verdicts[${p}].criteria`,truncatedCount:m.length-jr}]:[]);return{...s,qualityCriteria:a,verdicts:l,taskContentJson:d?g.slice(0,eg):g,truncated:d||c>0||I.length>0||t.length>0?{taskContentCharacters:d?g.length:null,truncatedQualityCriterionCount:c,truncatedVerdictCriteria:I,cutTexts:t,hint:`Run toloka review get ${e.id} --out <file> to save the full review as JSON.`}:null}},e0=(e)=>typeof e.body==="string"&&e.body.length>0?e.body:e.message,om=(e)=>`Run toloka review get ${e} to see its status and how many checked rejects are left, then decide again.`,cs=async(e,t)=>{try{return await t()}catch(i){if(i instanceof K&&i.status===403&&e0(i).includes(rj))throw new k("Customer review is not enabled for this team.",{cause:i,hint:{description:"Customer review is not available for this team. Choose another QA mode."}});if(i instanceof K&&i.status===409&&e!==void 0)throw new k(e0(i),{cause:i,hint:{description:e}});throw i}},oj=(e)=>[e.id,e.itemId,`${e.nodeName} (${e.nodeId})`,e.status,e.closedAt??e.deadlineAt],n0=async(e,t,i)=>{let n=await cs(void 0,()=>e.reviews.listPage({runId:t.runId,status:t.status,limit:t.limit,offset:t.offset,...t.nodeId===void 0?{}:{nodeId:t.nodeId}})),{total:r,offset:o}=n.pagination,s=n.reviews.length===0?`No ${t.status} reviews (total ${r}).`:`Showing ${o+1}-${o+n.reviews.length} of ${r}.`;O(i,t.json,n,n.reviews.length===0?s:[_([["ID","ITEM","NODE","STATUS",t.status==="closed"?"CLOSED":"DEADLINE"],...n.reviews.map(oj)]),"",s].join(`
367
367
  `))},sj=(e)=>{let t=e.truncated?.taskContentCharacters??null,i=new Map((e.truncated?.truncatedVerdictCriteria??[]).map(({field:n,truncatedCount:r})=>[n,r]));return[`Review: ${e.id}`,`Status: ${e.status}`,`Node: ${e.nodeName} (${e.nodeId})`,`Item: ${e.itemId}`,`Performer: ${e.performer.type}${e.performer.expertId===null?"":` ${e.performer.expertId}`}`,`Deadline: ${e.deadlineAt}`,...e.closedAt===null?[]:[`Closed: ${e.closedAt}`],`Checked rejects left: ${e.checkedRejectsLeft}`,"","Quality criteria:",...e.qualityCriteria.map((n)=>` ${n.id} ${n.qualityElement}: fails when ${n.fail}`),...e.truncated!==null&&e.truncated.truncatedQualityCriterionCount>0?[` ${e.truncated.truncatedQualityCriterionCount} more quality criteria not shown`]:[],"","Decisions:",...e.verdicts.length===0?[" (none)"]:e.verdicts.map((n,r)=>{let o=i.get(`verdicts[${r}].criteria`);return[` ${n.createdAt} ${n.decision}${n.forced?" (forced)":""} via ${n.source}`,...n.decision==="reject"?[` criteria: ${n.criteria.join(", ")}${o===void 0?"":` and ${o} more`}`,` comment: ${n.comment}`]:[],...n.llmQaCheck===null?[]:[` LLM QA check: ${n.llmQaCheck.verdict}: ${n.llmQaCheck.reason}`]].join(`
368
368
  `)}),"","Task content:",e.taskContentJson,...t===null?[]:[`\u2026task content truncated: showing ${eg.toLocaleString("en-US")} of ${tg(t)}`],...e.truncated===null?[]:["",e.truncated.hint]].join(`
@@ -420,7 +420,7 @@ ${i}${n}`},oG=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunI
420
420
 
421
421
  `),IG=async({sourceRoot:e,names:t,json:i,io:n,describe:r})=>{let o=await r({resolveFrom:e,...t.length===0?{}:{names:[...t]}});if(i){n.stdout(JSON.stringify(o,void 0,2));return}n.stdout(t.length===0?nD(o):rD(o))};var uG=(e,t)=>{let{context:i,globals:n}=t;e.command("ui").description("inspect components available for labeling interfaces").command("components").argument("[names...]","component names such as Field.RadioGroup; omit to list every component").option("--json","print the component contracts as JSON",!1).description("list Task UI components, or print the props, value shape, and example of the named ones").action(async(o,s)=>{let a=await Be(n(),i.io);await IG({sourceRoot:a,names:o,json:s.json,io:i.io,describe:i.taskUiComponents??cG})})};var mG=require("crypto");var oD=600000,sD=new Set(["awaiting_confirmation","blocked","completed","failed","canceled"]),aD=(e)=>new Promise((t)=>{setTimeout(t,e)}),Cs=(e)=>_([["ID",e.id],["Status",e.status],["Dataset",e.datasetId],["Model",e.model.type==="base_model"?e.model.baseModelId:e.model.modelVersionId],["Output",e.output.type==="field"?`field ${e.output.fieldId} on dataset ${e.output.datasetId}`:`new dataset ${e.output.datasetId}`],...e.quote?[["Rows",String(e.quote.requests)],["Skipped rows",String(e.quote.skippedRows)],["Maximum charge",`$${e.quote.maximumCharge}`],...e.quote.confirmBefore?[["Confirm before",e.quote.confirmBefore]]:[]]:[],...e.progress?.requests?[["Progress",`${e.progress.requests.done}/${e.progress.requests.total} rows`]]:[],...e.chargedAmount?[["Charged",`$${e.chargedAmount}`]]:[],...e.result?[["Written",String(e.result.written)],["Failed",String(e.result.failed)],["Cut at max tokens",String(e.result.truncated)],["Tokens",`${e.result.inputTokens} in, ${e.result.outputTokens} out`]]:[],...e.message?[["Message",e.message]]:[]]),pG=async(e,t,i,n,r)=>{let o=Date.now()+r;for(;;){let s=await e.batchInference.getRun({batchInferenceRunId:t});if(i(s))return s;f(Date.now()<o,`Batch Inference Run ${s.id} is still ${s.status}.`,{hint:{description:`Check it later with toloka batch-inference status ${s.id}.`}}),await aD(n)}},lD=async(e,t)=>{f(t.splitColumn===void 0||t.parts!==void 0,"--split-column needs --parts.",{hint:{description:"Pass --parts test to answer the rows of the test part."}});let i={...t.filter!==void 0&&await Nr(e,{datasetId:t.datasetId,name:t.datasetId,nameIsUnique:!1},[t.filter]),...t.slice!==void 0&&{slice:{sliceId:t.slice}},...t.parts!==void 0&&{parts:await sR(e,t.datasetId,{splitColumn:t.splitColumn,parts:t.parts})}};return Object.keys(i).length>0?i:void 0},CG=async(e,t,i)=>{f(t.baseModel===void 0!==(t.modelVersion===void 0),"Pass exactly one of --base-model or --model-version.",{hint:{description:"Run toloka base-model list or toloka model versions <model> to pick one."}}),f(t.outputField===void 0!==(t.outputDataset===void 0),"Pass exactly one of --output-field or --output-dataset.",{hint:{description:"--output-field writes a column on the dataset; --output-dataset creates a new dataset with the prompts and answers."}});let n=await lD(e,t),r=t.baseModel?{type:"base_model",baseModelId:t.baseModel}:{type:"model_version",modelVersionId:(await Fu(e,t.projectId,t.modelVersion)).id},o=await e.batchInference.createRun({projectId:t.projectId,idempotencyKey:t.idempotencyKey??mG.randomUUID(),datasetId:t.datasetId,...n&&{itemFilter:n},model:r,sampling:{maxOutputTokens:t.maxOutputTokens,...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP},...t.stop.length>0&&{stop:t.stop},...t.seed!==void 0&&{seed:t.seed},...t.samplesPerRow!==void 0&&{samplesPerRow:t.samplesPerRow}},output:t.outputField===void 0?{type:"dataset",name:t.outputDataset}:{type:"field",fieldName:t.outputField}}),s=await pG(e,o.id,(l)=>l.status!=="preparing",t.pollIntervalMs??1000,oD);if(f(s.status==="awaiting_confirmation",Cs(s),{hint:{description:"Fix the selection or the model, then start a new run."}}),!t.yes){O(i,t.json,s,`${Cs(s)}
422
422
 
423
- Confirm the maximum charge with: toloka batch-inference confirm ${s.id}`);return}let a=await e.batchInference.confirmRun({batchInferenceRunId:s.id});O(i,t.json,a,Cs(a))},AG=async(e,t,i)=>{let n=await e.batchInference.listRunsPage({projectId:t.projectId,limit:100,offset:0});O(i,t.json,n.batchInferenceRuns,n.batchInferenceRuns.length===0?"No Batch Inference Runs found.":_([["ID","STATUS","DATASET","MAXIMUM CHARGE","CHARGED"],...n.batchInferenceRuns.map((r)=>[r.id,r.status,r.datasetId,r.quote?`$${r.quote.maximumCharge}`:"-",r.chargedAmount?`$${r.chargedAmount}`:"-"])]))},fG=async(e,t,i)=>{let n=t.wait?await pG(e,t.batchInferenceRunId,(r)=>sD.has(r.status),t.pollIntervalMs??5000,Number.POSITIVE_INFINITY):await e.batchInference.getRun({batchInferenceRunId:t.batchInferenceRunId});O(i,t.json,n,Cs(n))},hG=async(e,t,i)=>{let n={batchInferenceRunId:t.batchInferenceRunId},r=t.action==="confirm"?await e.batchInference.confirmRun(n):t.action==="cancel"?await e.batchInference.cancelRun(n):await e.batchInference.resumeRun(n);O(i,t.json,r,Cs(r))};var bG=(e,t)=>{let{context:i,globals:n}=t,r=e.command("batch-inference").description("answer dataset rows with a base model or Model Version");r.command("run").requiredOption("--dataset <id>","Dataset whose chat messages are the prompts").option("--filter <field=value>","only rows whose field equals the value").option("--slice <id>","only rows of this ready Dataset Slice, with the prompts it froze").option("--parts <names>","only rows in these split parts, comma-separated, for example test",Mo).option("--split-column <name-or-id>","split column that --parts names, when the dataset has more than one").option("--base-model <id>","catalog Base Model that answers; pass exactly one of --base-model or --model-version",zi).option("--model-version <id>","Model Version that answers: mdv.<id> or Model@name; pass exactly one of --base-model or --model-version").option("--output-field <name>","text field on the dataset that receives the answers; pass exactly one of --output-field or --output-dataset").option("--output-dataset <name>","new dataset that receives the prompts and answers; pass exactly one of --output-field or --output-dataset").requiredOption("--max-output-tokens <count>","token limit per answer, at most 8192",se).option("--temperature <value>","sampling temperature from 0 to 2 (default 0)",OW).option("--top-p <value>","nucleus sampling threshold above 0 and at most 1",XW).option("--stop <text>","stop sequence; repeat for up to four",An,[]).option("--seed <number>","sampling seed",Rl).option("--samples-per-row <count>","answers per row, at most 16; above 1 needs --output-dataset and a temperature above 0",se).option("--idempotency-key <key>","reuse the run of an earlier identical request").option("--yes","confirm the quoted maximum charge and start right away",!1).option("--json","print JSON",!1).description("quote a Batch Inference Run, then confirm it to start").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a);let{dataset:l,...g}=o;await CG(s,{...g,projectId:a,datasetId:l},i.io)}),r.command("list").option("--json","print JSON",!1).description("list up to 100 of the selected project's Batch Inference Runs (first page only)").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await AG(s,{projectId:a,json:o.json},i.io)}),r.command("status").argument("<batch-inference-run-id>","Batch Inference Run ID").option("--wait","wait until the run finishes or needs you",!1).option("--json","print JSON",!1).description("show one Batch Inference Run").action(async(o,s)=>{let{client:a}=await w(n(),i);await fG(a,{batchInferenceRunId:o,...s},i.io)});for(let[o,s]of[["confirm","accept the quoted maximum charge and start the run"],["resume","resume a run blocked on funds or payment"],["cancel","cancel a run; answers already generated are kept and the GPU time used is charged"]])r.command(o).argument("<batch-inference-run-id>","Batch Inference Run ID").option("--json","print JSON",!1).description(s).action(async(a,l)=>{let{client:g}=await w(n(),i);await hG(g,{batchInferenceRunId:a,action:o,json:l.json},i.io)})};var ZG=require("fs"),yG=require("os"),ze=require("path");var gD=`${ze.sep}install${ze.sep}global${ze.sep}`,ag=(e)=>{try{return ZG.realpathSync(e)}catch{return e}},dD=(e,t,i,n)=>{if(ag(e).includes(gD))return"global-registry";if(ag(n)===t)return"linked";if(ze.dirname(ze.resolve(e))===ze.resolve(i))return"linked";return"project-local"},WG=(e=process.argv[1],t={})=>{if(t.native??nn())return{version:pe,commit:"6aaf74ca79d5",channel:"native",path:ag(t.executablePath??process.execPath)};f(e,"CLI entry path is unavailable",{hint:Y});let i=t.globalBinDirectory??ze.resolve(process.env.BUN_INSTALL??ze.join(yG.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??ze.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=ze.resolve(ze.dirname(ag(e)),".."),o=dD(e,r,i,n);return{version:pe,commit:"6aaf74ca79d5",channel:o,...o==="linked"?{path:r}:{}}};var VG=(e,t)=>{e.command("version").option("--json","print version and build provenance as JSON",!1).description("print the current CLI version").action((i)=>t.context.io.stdout(i.json?JSON.stringify(WG()):pe))};var BG=require("readline/promises");var RG=()=>new k("Standard input closed before an API key was entered.",{hint:{description:"Run toloka login in an interactive terminal, or pipe the key with toloka login --api-key-stdin."}}),cD=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},ID=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",d),process.stdin.off("end",l),process.stdin.off("error",g),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
423
+ Confirm the maximum charge with: toloka batch-inference confirm ${s.id}`);return}let a=await e.batchInference.confirmRun({batchInferenceRunId:s.id});O(i,t.json,a,Cs(a))},AG=async(e,t,i)=>{let n=await e.batchInference.listRunsPage({projectId:t.projectId,limit:100,offset:0});O(i,t.json,n.batchInferenceRuns,n.batchInferenceRuns.length===0?"No Batch Inference Runs found.":_([["ID","STATUS","DATASET","MAXIMUM CHARGE","CHARGED"],...n.batchInferenceRuns.map((r)=>[r.id,r.status,r.datasetId,r.quote?`$${r.quote.maximumCharge}`:"-",r.chargedAmount?`$${r.chargedAmount}`:"-"])]))},fG=async(e,t,i)=>{let n=t.wait?await pG(e,t.batchInferenceRunId,(r)=>sD.has(r.status),t.pollIntervalMs??5000,Number.POSITIVE_INFINITY):await e.batchInference.getRun({batchInferenceRunId:t.batchInferenceRunId});O(i,t.json,n,Cs(n))},hG=async(e,t,i)=>{let n={batchInferenceRunId:t.batchInferenceRunId},r=t.action==="confirm"?await e.batchInference.confirmRun(n):t.action==="cancel"?await e.batchInference.cancelRun(n):await e.batchInference.resumeRun(n);O(i,t.json,r,Cs(r))};var bG=(e,t)=>{let{context:i,globals:n}=t,r=e.command("batch-inference").description("answer dataset rows with a base model or Model Version");r.command("run").requiredOption("--dataset <id>","Dataset whose chat messages are the prompts").option("--filter <field=value>","only rows whose field equals the value").option("--slice <id>","only rows of this ready Dataset Slice, with the prompts it froze").option("--parts <names>","only rows in these split parts, comma-separated, for example test",Mo).option("--split-column <name-or-id>","split column that --parts names, when the dataset has more than one").option("--base-model <id>","catalog Base Model that answers; pass exactly one of --base-model or --model-version",zi).option("--model-version <id>","Model Version that answers: mdv.<id> or Model@name; pass exactly one of --base-model or --model-version").option("--output-field <name>","text field on the dataset that receives the answers; pass exactly one of --output-field or --output-dataset").option("--output-dataset <name>","new dataset that receives the prompts and answers; pass exactly one of --output-field or --output-dataset").requiredOption("--max-output-tokens <count>","token limit per answer, at most 8192",se).option("--temperature <value>","sampling temperature from 0 to 2 (default 0)",OW).option("--top-p <value>","nucleus sampling threshold above 0 and at most 1",XW).option("--stop <text>","stop sequence; repeat for up to four",An,[]).option("--seed <number>","sampling seed",Rl).option("--samples-per-row <count>","answers per row, at most 16; above 1 needs --output-dataset and a temperature above 0",se).option("--idempotency-key <key>","reuse the run of an earlier identical request").option("--yes","confirm the quoted maximum charge and start right away",!1).option("--json","print JSON",!1).description("quote a Batch Inference Run, then confirm it to start").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a);let{dataset:l,...g}=o;await CG(s,{...g,projectId:a,datasetId:l},i.io)}),r.command("list").option("--json","print JSON",!1).description("list up to 100 of the selected project's Batch Inference Runs (first page only)").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);N(a),await AG(s,{projectId:a,json:o.json},i.io)}),r.command("status").argument("<batch-inference-run-id>","Batch Inference Run ID").option("--wait","wait until the run finishes or needs you",!1).option("--json","print JSON",!1).description("show one Batch Inference Run").action(async(o,s)=>{let{client:a}=await w(n(),i);await fG(a,{batchInferenceRunId:o,...s},i.io)});for(let[o,s]of[["confirm","accept the quoted maximum charge and start the run"],["resume","resume a run blocked on funds or payment"],["cancel","cancel a run; answers already generated are kept and the GPU time used is charged"]])r.command(o).argument("<batch-inference-run-id>","Batch Inference Run ID").option("--json","print JSON",!1).description(s).action(async(a,l)=>{let{client:g}=await w(n(),i);await hG(g,{batchInferenceRunId:a,action:o,json:l.json},i.io)})};var ZG=require("fs"),yG=require("os"),ze=require("path");var gD=`${ze.sep}install${ze.sep}global${ze.sep}`,ag=(e)=>{try{return ZG.realpathSync(e)}catch{return e}},dD=(e,t,i,n)=>{if(ag(e).includes(gD))return"global-registry";if(ag(n)===t)return"linked";if(ze.dirname(ze.resolve(e))===ze.resolve(i))return"linked";return"project-local"},WG=(e=process.argv[1],t={})=>{if(t.native??nn())return{version:pe,commit:"c1ddaeeb736d",channel:"native",path:ag(t.executablePath??process.execPath)};f(e,"CLI entry path is unavailable",{hint:Y});let i=t.globalBinDirectory??ze.resolve(process.env.BUN_INSTALL??ze.join(yG.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??ze.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=ze.resolve(ze.dirname(ag(e)),".."),o=dD(e,r,i,n);return{version:pe,commit:"c1ddaeeb736d",channel:o,...o==="linked"?{path:r}:{}}};var VG=(e,t)=>{e.command("version").option("--json","print version and build provenance as JSON",!1).description("print the current CLI version").action((i)=>t.context.io.stdout(i.json?JSON.stringify(WG()):pe))};var BG=require("readline/promises");var RG=()=>new k("Standard input closed before an API key was entered.",{hint:{description:"Run toloka login in an interactive terminal, or pipe the key with toloka login --api-key-stdin."}}),cD=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},ID=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",d),process.stdin.off("end",l),process.stdin.off("error",g),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
424
424
  `)},l=()=>{a(),r(RG())},g=(c)=>{a(),r(c)},d=(c)=>{for(let I of c){if(I==="\r"||I===`
425
425
  `){a(),n(o);return}if(I==="\x03"||I==="\x04"){a(),r(I==="\x03"?new k("Canceled.",{hint:{disabled:!0}}):RG());return}if(I==="\x7F"||I==="\b"){if(o.length>0)o=o.slice(0,-1),process.stdout.write("\b \b");continue}o+=I,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",l),process.stdin.once("error",g);try{return await i}finally{s()}},uD=async(e,t={})=>{if(t.mask===!0)return ID(e);let i=BG.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await i.question(e)}finally{i.close()}},mD=(e,t)=>zl({message:e,choices:t}),bm=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:cD,style:eV(process.env,process.stdout.isTTY),...process.stdin.isTTY?{prompt:uD,choose:mD,select:hB}:{}});function pD(e){let t=new kn("toloka"),i={value:0},n=!1;t.description("Build and operate Toloka pipeline projects from TypeScript source. The public API may change between minor versions before 1.0.").version(pe,"-v, --version","output the current version").option("--source-root <directory>","project root; otherwise search the working directory and parents; init and report use only the working directory").option("--api-key <key>","API key override; login stores the key it verifies").option("--base-url <url>","platform base URL override; login saves the selected URL").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
426
426
  ${TW}`).configureOutput({writeOut:(s)=>e.io.stdout(s.replace(/\n$/u,"")),writeErr:(s)=>e.io.stderr(s.replace(/\n$/u,""))}).exitOverride();let r=()=>t.opts(),o={context:e,exitCode:i,globals:r};return t.hook("postAction",async(s,a)=>{if(n)return;let l=[];for(let c=a;c!==null;c=c.parent)l.push(c.name());if(l.includes("init")||l.includes("help")||l.includes("report")||l.includes("url")||l.includes("version")||l.includes("config"))return;let g=await Be(r(),e.io),d=await S0(g).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),VG(t,o),fV(t,o),AV(t,o),xB(t,o),uR(t,o),QW(t,o),cR(t,o),T0(t,o),c0(t,o),qB(t,o),$B(t,o),VR(t,o),aG(t,o),bG(t,o),gR(t,o),kB(t,o),d0(t,o),Y0(t,o),NB(t,o),G0(t,o),uG(t,o),{program:t,exitCode:i}}var CD=(e,t)=>{for(let i=0;i<t.length;i+=1){let n=t[i];if(n===void 0)return;if(n==="--")return t[i+1];if(!n.startsWith("-"))return n;let r=e.options.find((o)=>o.short===n||o.long===n);if(r!==void 0&&(r.required||r.optional)&&!n.includes("="))i+=1}return},AD=(e,t)=>{let i=CD(e,t);if(i===void 0||i==="help")return;return e.commands.some((r)=>r.name()===i||r.aliases().includes(i))?void 0:i},fD=async(e,t,i,n)=>{let r=AD(e,i);if(r!==void 0)return n.stderr(`error: unknown command '${r}'