@toloka-platform/sdk 0.11.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/cli/toloka.js +68 -68
- package/dist/cli/toloka.js.jsc +0 -0
- package/dist/cli/toloka.js.jsc.sha256 +1 -1
- package/dist/cli/toloka.js.sha256 +1 -1
- package/package.json +2 -2
- package/skills/catalog.json +6 -6
- package/skills/toloka-build/references/workflow-and-cli.md +3 -1
- package/src/transport.ts +10 -1
package/dist/cli/toloka.js
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
`:""},this._extScope=e,this._scope=new rt.Scope({parent:e}),this._nodes=[new $C]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let i=this._extScope.value(e,t);return(this._values[i.prefix]||(this._values[i.prefix]=new Set)).add(i),i}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,i,n){let r=this._scope.toName(t);if(i!==void 0&&n)this._constants[r.str]=i;return this._leafNode(new DC(e,r,i)),r}const(e,t,i){return this._def(rt.varKinds.const,e,t,i)}let(e,t,i){return this._def(rt.varKinds.let,e,t,i)}var(e,t,i){return this._def(rt.varKinds.var,e,t,i)}assign(e,t,i){return this._leafNode(new vg(e,t,i))}add(e,t){return this._leafNode(new _C(e,X.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==J.nil)this._leafNode(new MC(e));return this}object(...e){let t=["{"];for(let[i,n]of e){if(t.length>1)t.push(",");if(t.push(i),i!==n||this.opts.es5)t.push(":"),(0,J.addCodeArg)(t,n)}return t.push("}"),new J._Code(t)}if(e,t,i){if(this._blockNode(new kt(e)),t&&i)this.code(t).else().code(i).endIf();else if(t)this.code(t).endIf();else if(i)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new kt(e))}else(){return this._elseNode(new fr)}endIf(){return this._endBlockNode(kt,fr)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new qC(e),t)}forRange(e,t,i,n,r=this.opts.es5?rt.varKinds.var:rt.varKinds.let){let o=this._scope.toName(e);return this._for(new em(r,o,t,i),()=>n(o))}forOf(e,t,i,n=rt.varKinds.const){let r=this._scope.toName(e);if(this.opts.es5){let o=t instanceof J.Name?t:this.var("_arr",t);return this.forRange("_i",0,J._`${o}.length`,(s)=>{this.var(r,J._`${o}[${s}]`),i(r)})}return this._for(new Fg("of",n,r,t),()=>i(r))}forIn(e,t,i,n=this.opts.es5?rt.varKinds.var:rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,J._`Object.keys(${t})`,i);let r=this._scope.toName(e);return this._for(new Fg("in",n,r,t),()=>i(r))}endFor(){return this._endBlockNode(ln)}label(e){return this._leafNode(new QC(e))}break(e){return this._leafNode(new KC(e))}return(e){let t=new is;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(is)}try(e,t,i){if(!t&&!i)throw Error('CodeGen: "try" without "catch" and "finally"');let n=new tm;if(this._blockNode(n),this.code(e),t){let r=this.name("e");this._currNode=n.catch=new ns(r),t(r)}if(i)this._currNode=n.finally=new rs,this.code(i);return this._endBlockNode(ns,rs)}throw(e){return this._leafNode(new LC(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let i=this._nodes.length-t;if(i<0||e!==void 0&&i!==e)throw Error(`CodeGen: wrong number of nodes: ${i} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=J.nil,i,n){if(this._blockNode(new ts(e,t,i)),n)this.code(n).endFunc();return this}endFunc(){return this._endBlockNode(ts)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let i=this._currNode;if(i instanceof e||t&&i instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof kt))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}X.CodeGen=im;function Zi(e,t){for(let i in t)e[i]=(e[i]||0)+(t[i]||0);return e}function os(e,t){return t instanceof J._CodeOrName?Zi(e,t.names):e}function dn(e,t,i){if(e instanceof J.Name)return n(e);if(!r(e))return e;return new J._Code(e._items.reduce((o,s)=>{if(s instanceof J.Name)s=n(s);if(s instanceof J._Code)o.push(...s._items);else o.push(s);return o},[]));function n(o){let s=i[o.str];if(s===void 0||t[o.str]!==1)return o;return delete t[o.str],s}function r(o){return o instanceof J._Code&&o._items.some((s)=>s instanceof J.Name&&t[s.str]===1&&i[s.str]!==void 0)}}function vF(e,t){for(let i in t)e[i]=(e[i]||0)-(t[i]||0)}function nm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:J._`!${Hg(e)}`}X.not=nm;var kF=rm(X.operators.AND);function PF(...e){return e.reduce(kF)}X.and=PF;var NF=rm(X.operators.OR);function xF(...e){return e.reduce(NF)}X.or=xF;function rm(e){return(t,i)=>t===J.nil?i:i===J.nil?t:J._`${Hg(t)} ${e} ${Hg(i)}`}function Hg(e){return e instanceof J.Name?e:J._`(${e})`}});var T=f(function(E){Object.defineProperty(E,"__esModule",{value:!0});E.checkStrictMode=E.getErrorPath=E.Type=E.useFunc=E.setEvaluated=E.evaluatedPropsToName=E.mergeEvaluated=E.eachItem=E.unescapeJsonPointer=E.escapeJsonPointer=E.escapeFragment=E.unescapeFragment=E.schemaRefOrVal=E.schemaHasRulesButRef=E.schemaHasRules=E.checkUnknownRules=E.alwaysValidSchema=E.toHash=void 0;var Q=N(),YF=hr();function SF(e){let t={};for(let i of e)t[i]=!0;return t}E.toHash=SF;function XF(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return am(e,t),!gm(t,e.self.RULES.all)}E.alwaysValidSchema=XF;function am(e,t=e.schema){let{opts:i,self:n}=e;if(!i.strictSchema)return;if(typeof t==="boolean")return;let r=n.RULES.keywords;for(let o in t)if(!r[o])Im(e,`unknown keyword: "${o}"`)}E.checkUnknownRules=am;function gm(e,t){if(typeof e=="boolean")return!e;for(let i in e)if(t[i])return!0;return!1}E.schemaHasRules=gm;function EF(e,t){if(typeof e=="boolean")return!e;for(let i in e)if(i!=="$ref"&&t.all[i])return!0;return!1}E.schemaHasRulesButRef=EF;function TF({topSchemaRef:e,schemaPath:t},i,n,r){if(!r){if(typeof i=="number"||typeof i=="boolean")return i;if(typeof i=="string")return Q._`${i}`}return Q._`${e}${t}${(0,Q.getProperty)(n)}`}E.schemaRefOrVal=TF;function JF(e){return lm(decodeURIComponent(e))}E.unescapeFragment=JF;function UF(e){return encodeURIComponent(Pg(e))}E.escapeFragment=UF;function Pg(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapeJsonPointer=Pg;function lm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapeJsonPointer=lm;function OF(e,t){if(Array.isArray(e))for(let i of e)t(i);else t(e)}E.eachItem=OF;function om({mergeNames:e,mergeToName:t,mergeValues:i,resultToName:n}){return(r,o,s,a)=>{let g=s===void 0?o:s instanceof Q.Name?(o instanceof Q.Name?e(r,o,s):t(r,o,s),s):o instanceof Q.Name?(t(r,s,o),o):i(o,s);return a===Q.Name&&!(g instanceof Q.Name)?n(r,g):g}}E.mergeEvaluated={props:om({mergeNames:(e,t,i)=>e.if(Q._`${i} !== true && ${t} !== undefined`,()=>{e.if(Q._`${t} === true`,()=>e.assign(i,!0),()=>e.assign(i,Q._`${i} || {}`).code(Q._`Object.assign(${i}, ${t})`))}),mergeToName:(e,t,i)=>e.if(Q._`${i} !== true`,()=>{if(t===!0)e.assign(i,!0);else e.assign(i,Q._`${i} || {}`),Ng(e,i,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:dm}),items:om({mergeNames:(e,t,i)=>e.if(Q._`${i} !== true && ${t} !== undefined`,()=>e.assign(i,Q._`${t} === true ? true : ${i} > ${t} ? ${i} : ${t}`)),mergeToName:(e,t,i)=>e.if(Q._`${i} !== true`,()=>e.assign(i,t===!0?!0:Q._`${i} > ${t} ? ${i} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function dm(e,t){if(t===!0)return e.var("props",!0);let i=e.var("props",Q._`{}`);if(t!==void 0)Ng(e,i,t);return i}E.evaluatedPropsToName=dm;function Ng(e,t,i){Object.keys(i).forEach((n)=>e.assign(Q._`${t}${(0,Q.getProperty)(n)}`,!0))}E.setEvaluated=Ng;var sm={};function zF(e,t){return e.scopeValue("func",{ref:t,code:sm[t.code]||(sm[t.code]=new YF._Code(t.code))})}E.useFunc=zF;var kg;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(kg||(E.Type=kg={}));function jF(e,t,i){if(e instanceof Q.Name){let n=t===kg.Num;return i?n?Q._`"[" + ${e} + "]"`:Q._`"['" + ${e} + "']"`:n?Q._`"/" + ${e}`:Q._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return i?(0,Q.getProperty)(e).toString():"/"+Pg(e)}E.getErrorPath=jF;function Im(e,t,i=e.opts.strictSchema){if(!i)return;if(t=`strict mode: ${t}`,i===!0)throw Error(t);e.self.logger.warn(t)}E.checkStrictMode=Im});var Ke=f(function(xg){Object.defineProperty(xg,"__esModule",{value:!0});var We=N(),DF={data:new We.Name("data"),valCxt:new We.Name("valCxt"),instancePath:new We.Name("instancePath"),parentData:new We.Name("parentData"),parentDataProperty:new We.Name("parentDataProperty"),rootData:new We.Name("rootData"),dynamicAnchors:new We.Name("dynamicAnchors"),vErrors:new We.Name("vErrors"),errors:new We.Name("errors"),this:new We.Name("this"),self:new We.Name("self"),scope:new We.Name("scope"),json:new We.Name("json"),jsonPos:new We.Name("jsonPos"),jsonLen:new We.Name("jsonLen"),jsonPart:new We.Name("jsonPart")};xg.default=DF});var Wr=f(function(ye){Object.defineProperty(ye,"__esModule",{value:!0});ye.extendErrors=ye.resetErrorsCount=ye.reportExtraError=ye.reportError=ye.keyword$DataError=ye.keywordError=void 0;var O=N(),gs=T(),we=Ke();ye.keywordError={message:({keyword:e})=>O.str`must pass "${e}" keyword validation`};ye.keyword$DataError={message:({keyword:e,schemaType:t})=>t?O.str`"${e}" keyword must be ${t} ($data)`:O.str`"${e}" keyword is invalid ($data)`};function _F(e,t=ye.keywordError,i,n){let{it:r}=e,{gen:o,compositeRule:s,allErrors:a}=r,g=Cm(e,t,i);if(n!==null&&n!==void 0?n:s||a)cm(o,g);else um(r,O._`[${g}]`)}ye.reportError=_F;function QF(e,t=ye.keywordError,i){let{it:n}=e,{gen:r,compositeRule:o,allErrors:s}=n,a=Cm(e,t,i);if(cm(r,a),!(o||s))um(n,we.default.vErrors)}ye.reportExtraError=QF;function KF(e,t){e.assign(we.default.errors,t),e.if(O._`${we.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(O._`${we.default.vErrors}.length`,t),()=>e.assign(we.default.vErrors,null)))}ye.resetErrorsCount=KF;function LF({gen:e,keyword:t,schemaValue:i,data:n,errsCount:r,it:o}){if(r===void 0)throw Error("ajv implementation error");let s=e.name("err");e.forRange("i",r,we.default.errors,(a)=>{if(e.const(s,O._`${we.default.vErrors}[${a}]`),e.if(O._`${s}.instancePath === undefined`,()=>e.assign(O._`${s}.instancePath`,(0,O.strConcat)(we.default.instancePath,o.errorPath))),e.assign(O._`${s}.schemaPath`,O.str`${o.errSchemaPath}/${t}`),o.opts.verbose)e.assign(O._`${s}.schema`,i),e.assign(O._`${s}.data`,n)})}ye.extendErrors=LF;function cm(e,t){let i=e.const("err",t);e.if(O._`${we.default.vErrors} === null`,()=>e.assign(we.default.vErrors,O._`[${i}]`),O._`${we.default.vErrors}.push(${i})`),e.code(O._`${we.default.errors}++`)}function um(e,t){let{gen:i,validateName:n,schemaEnv:r}=e;if(r.$async)i.throw(O._`new ${e.ValidationError}(${t})`);else i.assign(O._`${n}.errors`,t),i.return(!1)}var hi={keyword:new O.Name("keyword"),schemaPath:new O.Name("schemaPath"),params:new O.Name("params"),propertyName:new O.Name("propertyName"),message:new O.Name("message"),schema:new O.Name("schema"),parentSchema:new O.Name("parentSchema")};function Cm(e,t,i){let{createErrors:n}=e.it;if(n===!1)return O._`{}`;return MF(e,t,i)}function MF(e,t,i={}){let{gen:n,it:r}=e,o=[$F(r,i),qF(e,i)];return eH(e,t,o),n.object(...o)}function $F({errorPath:e},{instancePath:t}){let i=t?O.str`${e}${(0,gs.getErrorPath)(t,gs.Type.Str)}`:e;return[we.default.instancePath,(0,O.strConcat)(we.default.instancePath,i)]}function qF({keyword:e,it:{errSchemaPath:t}},{schemaPath:i,parentSchema:n}){let r=n?t:O.str`${t}/${e}`;if(i)r=O.str`${r}${(0,gs.getErrorPath)(i,gs.Type.Str)}`;return[hi.schemaPath,r]}function eH(e,{params:t,message:i},n){let{keyword:r,data:o,schemaValue:s,it:a}=e,{opts:g,propertyName:l,topSchemaRef:d,schemaPath:I}=a;if(n.push([hi.keyword,r],[hi.params,typeof t=="function"?t(e):t||O._`{}`]),g.messages)n.push([hi.message,typeof i=="function"?i(e):i]);if(g.verbose)n.push([hi.schema,s],[hi.parentSchema,O._`${d}${I}`],[we.default.data,o]);if(l)n.push([hi.propertyName,l])}});var pm=f(function(In){Object.defineProperty(In,"__esModule",{value:!0});In.boolOrEmptySchema=In.topBoolOrEmptySchema=void 0;var tH=Wr(),iH=N(),nH=Ke(),rH={message:"boolean schema is false"};function oH(e){let{gen:t,schema:i,validateName:n}=e;if(i===!1)mm(e,!1);else if(typeof i=="object"&&i.$async===!0)t.return(nH.default.data);else t.assign(iH._`${n}.errors`,null),t.return(!0)}In.topBoolOrEmptySchema=oH;function sH(e,t){let{gen:i,schema:n}=e;if(n===!1)i.var(t,!1),mm(e);else i.var(t,!0)}In.boolOrEmptySchema=sH;function mm(e,t){let{gen:i,data:n}=e,r={gen:i,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,tH.reportError)(r,rH,void 0,t)}});var Yg=f(function(cn){Object.defineProperty(cn,"__esModule",{value:!0});cn.getRules=cn.isJSONType=void 0;var aH=["string","number","integer","boolean","null","object","array"],gH=new Set(aH);function lH(e){return typeof e=="string"&&gH.has(e)}cn.isJSONType=lH;function dH(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}cn.getRules=dH});var Sg=f(function(Dt){Object.defineProperty(Dt,"__esModule",{value:!0});Dt.shouldUseRule=Dt.shouldUseGroup=Dt.schemaHasRulesForType=void 0;function IH({schema:e,self:t},i){let n=t.RULES.types[i];return n&&n!==!0&&Am(e,n)}Dt.schemaHasRulesForType=IH;function Am(e,t){return t.rules.some((i)=>bm(e,i))}Dt.shouldUseGroup=Am;function bm(e,t){var i;return e[t.keyword]!==void 0||((i=t.definition.implements)===null||i===void 0?void 0:i.some((n)=>e[n]!==void 0))}Dt.shouldUseRule=bm});var yr=f(function(Ve){Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var cH=Yg(),uH=Sg(),CH=Wr(),x=N(),Zm=T(),un;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(un||(Ve.DataType=un={}));function mH(e){let t=hm(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}Ve.getSchemaTypes=mH;function hm(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(cH.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}Ve.getJSONTypes=hm;function pH(e,t){let{gen:i,data:n,opts:r}=e,o=AH(t,r.coerceTypes),s=t.length>0&&!(o.length===0&&t.length===1&&(0,uH.schemaHasRulesForType)(e,t[0]));if(s){let a=Eg(t,n,r.strictNumbers,un.Wrong);i.if(a,()=>{if(o.length)bH(e,t,o);else Tg(e)})}return s}Ve.coerceAndCheckDataType=pH;var fm=new Set(["string","number","integer","boolean","null"]);function AH(e,t){return t?e.filter((i)=>fm.has(i)||t==="array"&&i==="array"):[]}function bH(e,t,i){let{gen:n,data:r,opts:o}=e,s=n.let("dataType",x._`typeof ${r}`),a=n.let("coerced",x._`undefined`);if(o.coerceTypes==="array")n.if(x._`${s} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>n.assign(r,x._`${r}[0]`).assign(s,x._`typeof ${r}`).if(Eg(t,r,o.strictNumbers),()=>n.assign(a,r)));n.if(x._`${a} !== undefined`);for(let l of i)if(fm.has(l)||l==="array"&&o.coerceTypes==="array")g(l);n.else(),Tg(e),n.endIf(),n.if(x._`${a} !== undefined`,()=>{n.assign(r,a),ZH(e,a)});function g(l){switch(l){case"string":n.elseIf(x._`${s} == "number" || ${s} == "boolean"`).assign(a,x._`"" + ${r}`).elseIf(x._`${r} === null`).assign(a,x._`""`);return;case"number":n.elseIf(x._`${s} == "boolean" || ${r} === null
|
|
5
5
|
|| (${s} == "string" && ${r} && ${r} == +${r})`).assign(a,x._`+${r}`);return;case"integer":n.elseIf(x._`${s} === "boolean" || ${r} === null
|
|
6
6
|
|| (${s} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(a,x._`+${r}`);return;case"boolean":n.elseIf(x._`${r} === "false" || ${r} === 0 || ${r} === null`).assign(a,!1).elseIf(x._`${r} === "true" || ${r} === 1`).assign(a,!0);return;case"null":n.elseIf(x._`${r} === "" || ${r} === 0 || ${r} === false`),n.assign(a,null);return;case"array":n.elseIf(x._`${s} === "string" || ${s} === "number"
|
|
7
|
-
|| ${s} === "boolean" || ${r} === null`).assign(a,x._`[${r}]`)}}}function ZH({gen:e,parentData:t,parentDataProperty:i},n){e.if(x._`${t} !== undefined`,()=>e.assign(x._`${t}[${i}]`,n))}function Xg(e,t,i,n=un.Correct){let r=n===un.Correct?x.operators.EQ:x.operators.NEQ,o;switch(e){case"null":return x._`${t} ${r} null`;case"array":o=x._`Array.isArray(${t})`;break;case"object":o=x._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s(x._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return x._`typeof ${t} ${r} ${e}`}return n===un.Correct?o:(0,x.not)(o);function s(a=x.nil){return(0,x.and)(x._`typeof ${t} == "number"`,a,i?x._`isFinite(${t})`:x.nil)}}Ve.checkDataType=Xg;function Eg(e,t,i,n){if(e.length===1)return Xg(e[0],t,i,n);let r,o=(0,Zm.toHash)(e);if(o.array&&o.object){let s=x._`typeof ${t} != "object"`;r=o.null?s:x._`!${t} || ${s}`,delete o.null,delete o.array,delete o.object}else r=x.nil;if(o.number)delete o.integer;for(let s in o)r=(0,x.and)(r,Xg(s,t,i,n));return r}Ve.checkDataTypes=Eg;var hH={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?x._`{type: ${e}}`:x._`{type: ${t}}`};function Tg(e){let t=fH(e);(0,CH.reportError)(t,hH)}Ve.reportTypeError=Tg;function fH(e){let{gen:t,data:i,schema:n}=e,r=(0,Zm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:i,schema:n.type,schemaCode:r,schemaValue:r,parentSchema:n,params:{},it:e}}});var ym=f(function(ls){Object.defineProperty(ls,"__esModule",{value:!0});ls.assignDefaults=void 0;var Cn=N(),WH=T();function yH(e,t){let{properties:i,items:n}=e.schema;if(t==="object"&&i)for(let r in i)Wm(e,r,i[r].default);else if(t==="array"&&Array.isArray(n))n.forEach((r,o)=>Wm(e,o,r.default))}ls.assignDefaults=yH;function Wm(e,t,i){let{gen:n,compositeRule:r,data:o,opts:s}=e;if(i===void 0)return;let a=Cn._`${o}${(0,Cn.getProperty)(t)}`;if(r){(0,WH.checkStrictMode)(e,`default is ignored for: ${a}`);return}let g=Cn._`${a} === undefined`;if(s.useDefaults==="empty")g=Cn._`${g} || ${a} === null || ${a} === ""`;n.if(g,Cn._`${a} = ${(0,Cn.stringify)(i)}`)}});var Le=f(function(_){Object.defineProperty(_,"__esModule",{value:!0});_.validateUnion=_.validateArray=_.usePattern=_.callValidateCode=_.schemaProperties=_.allSchemaProperties=_.noPropertyInData=_.propertyInData=_.isOwnProperty=_.hasPropFunc=_.reportMissingProp=_.checkMissingProp=_.checkReportMissingProp=void 0;var L=N(),Jg=T(),_t=Ke(),VH=T();function BH(e,t){let{gen:i,data:n,it:r}=e;i.if(Og(i,n,t,r.opts.ownProperties),()=>{e.setParams({missingProperty:L._`${t}`},!0),e.error()})}_.checkReportMissingProp=BH;function RH({gen:e,data:t,it:{opts:i}},n,r){return(0,L.or)(...n.map((o)=>(0,L.and)(Og(e,t,o,i.ownProperties),L._`${r} = ${o}`)))}_.checkMissingProp=RH;function GH(e,t){e.setParams({missingProperty:t},!0),e.error()}_.reportMissingProp=GH;function Vm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:L._`Object.prototype.hasOwnProperty`})}_.hasPropFunc=Vm;function Ug(e,t,i){return L._`${Vm(e)}.call(${t}, ${i})`}_.isOwnProperty=Ug;function wH(e,t,i,n){let r=L._`${t}${(0,L.getProperty)(i)} !== undefined`;return n?L._`${r} && ${Ug(e,t,i)}`:r}_.propertyInData=wH;function Og(e,t,i,n){let r=L._`${t}${(0,L.getProperty)(i)} === undefined`;return n?(0,L.or)(r,(0,L.not)(Ug(e,t,i))):r}_.noPropertyInData=Og;function Bm(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}_.allSchemaProperties=Bm;function FH(e,t){return Bm(t).filter((i)=>!(0,Jg.alwaysValidSchema)(e,t[i]))}_.schemaProperties=FH;function HH({schemaCode:e,data:t,it:{gen:i,topSchemaRef:n,schemaPath:r,errorPath:o},it:s},a,g,l){let d=l?L._`${e}, ${t}, ${n}${r}`:t,I=[[_t.default.instancePath,(0,L.strConcat)(_t.default.instancePath,o)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];if(s.opts.dynamicRef)I.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let C=L._`${d}, ${i.object(...I)}`;return g!==L.nil?L._`${a}.call(${g}, ${C})`:L._`${a}(${C})`}_.callValidateCode=HH;var vH=L._`new RegExp`;function kH({gen:e,it:{opts:t}},i){let n=t.unicodeRegExp?"u":"",{regExp:r}=t.code,o=r(i,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:L._`${r.code==="new RegExp"?vH:(0,VH.useFunc)(e,r)}(${i}, ${n})`})}_.usePattern=kH;function PH(e){let{gen:t,data:i,keyword:n,it:r}=e,o=t.name("valid");if(r.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(o,!0),s(()=>t.break()),o;function s(a){let g=t.const("len",L._`${i}.length`);t.forRange("i",0,g,(l)=>{e.subschema({keyword:n,dataProp:l,dataPropType:Jg.Type.Num},o),t.if((0,L.not)(o),a)})}}_.validateArray=PH;function NH(e){let{gen:t,schema:i,keyword:n,it:r}=e;if(!Array.isArray(i))throw Error("ajv implementation error");if(i.some((g)=>(0,Jg.alwaysValidSchema)(r,g))&&!r.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>i.forEach((g,l)=>{let d=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);if(t.assign(s,L._`${s} || ${a}`),!e.mergeValidEvaluated(d,a))t.if((0,L.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}_.validateUnion=NH});var wm=f(function(bt){Object.defineProperty(bt,"__esModule",{value:!0});bt.validateKeywordUsage=bt.validSchemaType=bt.funcKeywordCode=bt.macroKeywordCode=void 0;var Fe=N(),fi=Ke(),xH=Le(),YH=Wr();function SH(e,t){let{gen:i,keyword:n,schema:r,parentSchema:o,it:s}=e,a=t.macro.call(s.self,r,o,s),g=Gm(i,n,a);if(s.opts.validateSchema!==!1)s.self.validateSchema(a,!0);let l=i.name("valid");e.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:g,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}bt.macroKeywordCode=SH;function XH(e,t){var i;let{gen:n,keyword:r,schema:o,parentSchema:s,$data:a,it:g}=e;TH(g,t);let l=!a&&t.compile?t.compile.call(g.self,o,s,g):t.validate,d=Gm(n,r,l),I=n.let("valid");e.block$data(I,C),e.ok((i=t.valid)!==null&&i!==void 0?i:I);function C(){if(t.errors===!1){if(c(),t.modifying)Rm(e);u(()=>e.error())}else{let p=t.async?m():A();if(t.modifying)Rm(e);u(()=>EH(e,p))}}function m(){let p=n.let("ruleErrs",null);return n.try(()=>c(Fe._`await `),(Z)=>n.assign(I,!1).if(Fe._`${Z} instanceof ${g.ValidationError}`,()=>n.assign(p,Fe._`${Z}.errors`),()=>n.throw(Z))),p}function A(){let p=Fe._`${d}.errors`;return n.assign(p,null),c(Fe.nil),p}function c(p=t.async?Fe._`await `:Fe.nil){let Z=g.opts.passContext?fi.default.this:fi.default.self,h=!(("compile"in t)&&!a||t.schema===!1);n.assign(I,Fe._`${p}${(0,xH.callValidateCode)(e,d,Z,h)}`,t.modifying)}function u(p){var Z;n.if((0,Fe.not)((Z=t.valid)!==null&&Z!==void 0?Z:I),p)}}bt.funcKeywordCode=XH;function Rm(e){let{gen:t,data:i,it:n}=e;t.if(n.parentData,()=>t.assign(i,Fe._`${n.parentData}[${n.parentDataProperty}]`))}function EH(e,t){let{gen:i}=e;i.if(Fe._`Array.isArray(${t})`,()=>{i.assign(fi.default.vErrors,Fe._`${fi.default.vErrors} === null ? ${t} : ${fi.default.vErrors}.concat(${t})`).assign(fi.default.errors,Fe._`${fi.default.vErrors}.length`),(0,YH.extendErrors)(e)},()=>e.error())}function TH({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function Gm(e,t,i){if(i===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof i=="function"?{ref:i}:{ref:i,code:(0,Fe.stringify)(i)})}function JH(e,t,i=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||i&&typeof e>"u")}bt.validSchemaType=JH;function UH({schema:e,opts:t,self:i,errSchemaPath:n},r,o){if(Array.isArray(r.keyword)?!r.keyword.includes(o):r.keyword!==o)throw Error("ajv implementation error");let s=r.dependencies;if(s===null||s===void 0?void 0:s.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(r.validateSchema){if(!r.validateSchema(e[o])){let g=`keyword "${o}" value is invalid at path "${n}": `+i.errorsText(r.validateSchema.errors);if(t.validateSchema==="log")i.logger.error(g);else throw Error(g)}}}bt.validateKeywordUsage=UH});var Hm=f(function(Qt){Object.defineProperty(Qt,"__esModule",{value:!0});Qt.extendSubschemaMode=Qt.extendSubschemaData=Qt.getSubschema=void 0;var Zt=N(),Fm=T();function OH(e,{keyword:t,schemaProp:i,schema:n,schemaPath:r,errSchemaPath:o,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return i===void 0?{schema:a,schemaPath:Zt._`${e.schemaPath}${(0,Zt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[i],schemaPath:Zt._`${e.schemaPath}${(0,Zt.getProperty)(t)}${(0,Zt.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Fm.escapeFragment)(i)}`}}if(n!==void 0){if(r===void 0||o===void 0||s===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:r,topSchemaRef:s,errSchemaPath:o}}throw Error('either "keyword" or "schema" must be passed')}Qt.getSubschema=OH;function zH(e,t,{dataProp:i,dataPropType:n,data:r,dataTypes:o,propertyName:s}){if(r!==void 0&&i!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(i!==void 0){let{errorPath:l,dataPathArr:d,opts:I}=t,C=a.let("data",Zt._`${t.data}${(0,Zt.getProperty)(i)}`,!0);g(C),e.errorPath=Zt.str`${l}${(0,Fm.getErrorPath)(i,n,I.jsPropertySyntax)}`,e.parentDataProperty=Zt._`${i}`,e.dataPathArr=[...d,e.parentDataProperty]}if(r!==void 0){let l=r instanceof Zt.Name?r:a.let("data",r,!0);if(g(l),s!==void 0)e.propertyName=s}if(o)e.dataTypes=o;function g(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Qt.extendSubschemaData=zH;function jH(e,{jtdDiscriminator:t,jtdMetadata:i,compositeRule:n,createErrors:r,allErrors:o}){if(n!==void 0)e.compositeRule=n;if(r!==void 0)e.createErrors=r;if(o!==void 0)e.allErrors=o;e.jtdDiscriminator=t,e.jtdMetadata=i}Qt.extendSubschemaMode=jH});var zg=f(function(Ej,vm){vm.exports=function e(t,i){if(t===i)return!0;if(t&&i&&typeof t=="object"&&typeof i=="object"){if(t.constructor!==i.constructor)return!1;var n,r,o;if(Array.isArray(t)){if(n=t.length,n!=i.length)return!1;for(r=n;r--!==0;)if(!e(t[r],i[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(i).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(i,o[r]))return!1;for(r=n;r--!==0;){var s=o[r];if(!e(t[s],i[s]))return!1}return!0}return t!==t&&i!==i}});var Pm=f(function(Tj,km){var Kt=km.exports=function(e,t,i){if(typeof t=="function")i=t,t={};i=t.cb||i;var n=typeof i=="function"?i:i.pre||function(){},r=i.post||function(){};ds(t,n,r,e,"",e)};Kt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Kt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Kt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Kt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ds(e,t,i,n,r,o,s,a,g,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,r,o,s,a,g,l);for(var d in n){var I=n[d];if(Array.isArray(I)){if(d in Kt.arrayKeywords)for(var C=0;C<I.length;C++)ds(e,t,i,I[C],r+"/"+d+"/"+C,o,r,d,n,C)}else if(d in Kt.propsKeywords){if(I&&typeof I=="object")for(var m in I)ds(e,t,i,I[m],r+"/"+d+"/"+DH(m),o,r,d,n,m)}else if(d in Kt.keywords||e.allKeys&&!(d in Kt.skipKeywords))ds(e,t,i,I,r+"/"+d,o,r,d,n)}i(n,r,o,s,a,g,l)}}function DH(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Vr=f(function(Se){Object.defineProperty(Se,"__esModule",{value:!0});Se.getSchemaRefs=Se.resolveUrl=Se.normalizeId=Se._getFullPath=Se.getFullPath=Se.inlineRef=void 0;var _H=T(),QH=zg(),KH=Pm(),LH=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function MH(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!jg(e);if(!t)return!1;return Nm(e)<=t}Se.inlineRef=MH;var $H=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jg(e){for(let t in e){if($H.has(t))return!0;let i=e[t];if(Array.isArray(i)&&i.some(jg))return!0;if(typeof i=="object"&&jg(i))return!0}return!1}function Nm(e){let t=0;for(let i in e){if(i==="$ref")return 1/0;if(t++,LH.has(i))continue;if(typeof e[i]=="object")(0,_H.eachItem)(e[i],(n)=>t+=Nm(n));if(t===1/0)return 1/0}return t}function xm(e,t="",i){if(i!==!1)t=mn(t);let n=e.parse(t);return Ym(e,n)}Se.getFullPath=xm;function Ym(e,t){return e.serialize(t).split("#")[0]+"#"}Se._getFullPath=Ym;var qH=/#\/?$/;function mn(e){return e?e.replace(qH,""):""}Se.normalizeId=mn;function e5(e,t,i){return i=mn(i),e.resolve(t,i)}Se.resolveUrl=e5;var t5=/^[a-z_][-a-z0-9._]*$/i;function i5(e,t){if(typeof e=="boolean")return{};let{schemaId:i,uriResolver:n}=this.opts,r=mn(e[i]||t),o={"":r},s=xm(n,r,!1),a={},g=new Set;return KH(e,{allKeys:!0},(I,C,m,A)=>{if(A===void 0)return;let c=s+C,u=o[A];if(typeof I[i]=="string")u=p.call(this,I[i]);Z.call(this,I.$anchor),Z.call(this,I.$dynamicAnchor),o[C]=u;function p(h){let W=this.opts.uriResolver.resolve;if(h=mn(u?W(u,h):h),g.has(h))throw d(h);g.add(h);let y=this.refs[h];if(typeof y=="string")y=this.refs[y];if(typeof y=="object")l(I,y.schema,h);else if(h!==mn(c))if(h[0]==="#")l(I,a[h],h),a[h]=I;else this.refs[h]=c;return h}function Z(h){if(typeof h=="string"){if(!t5.test(h))throw Error(`invalid anchor "${h}"`);p.call(this,`#${h}`)}}}),a;function l(I,C,m){if(C!==void 0&&!QH(I,C))throw d(m)}function d(I){return Error(`reference "${I}" resolves to more than one schema`)}}Se.getSchemaRefs=i5});var pn=f(function(Lt){Object.defineProperty(Lt,"__esModule",{value:!0});Lt.getData=Lt.KeywordCxt=Lt.validateFunctionCode=void 0;var Jm=pm(),Sm=yr(),_g=Sg(),Is=yr(),n5=ym(),Rr=wm(),Dg=Hm(),G=N(),k=Ke(),r5=Vr(),Pt=T(),Br=Wr();function o5(e){if(zm(e)){if(jm(e),Om(e)){g5(e);return}}Um(e,()=>(0,Jm.topBoolOrEmptySchema)(e))}Lt.validateFunctionCode=o5;function Um({gen:e,validateName:t,schema:i,schemaEnv:n,opts:r},o){if(r.code.es5)e.func(t,G._`${k.default.data}, ${k.default.valCxt}`,n.$async,()=>{e.code(G._`"use strict"; ${Xm(i,r)}`),a5(e,r),e.code(o)});else e.func(t,G._`${k.default.data}, ${s5(r)}`,n.$async,()=>e.code(Xm(i,r)).code(o))}function s5(e){return G._`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${e.dynamicRef?G._`, ${k.default.dynamicAnchors}={}`:G.nil}}={}`}function a5(e,t){e.if(k.default.valCxt,()=>{if(e.var(k.default.instancePath,G._`${k.default.valCxt}.${k.default.instancePath}`),e.var(k.default.parentData,G._`${k.default.valCxt}.${k.default.parentData}`),e.var(k.default.parentDataProperty,G._`${k.default.valCxt}.${k.default.parentDataProperty}`),e.var(k.default.rootData,G._`${k.default.valCxt}.${k.default.rootData}`),t.dynamicRef)e.var(k.default.dynamicAnchors,G._`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{if(e.var(k.default.instancePath,G._`""`),e.var(k.default.parentData,G._`undefined`),e.var(k.default.parentDataProperty,G._`undefined`),e.var(k.default.rootData,k.default.data),t.dynamicRef)e.var(k.default.dynamicAnchors,G._`{}`)})}function g5(e){let{schema:t,opts:i,gen:n}=e;Um(e,()=>{if(i.$comment&&t.$comment)_m(e);if(u5(e),n.let(k.default.vErrors,null),n.let(k.default.errors,0),i.unevaluated)l5(e);Dm(e),p5(e)});return}function l5(e){let{gen:t,validateName:i}=e;e.evaluated=t.const("evaluated",G._`${i}.evaluated`),t.if(G._`${e.evaluated}.dynamicProps`,()=>t.assign(G._`${e.evaluated}.props`,G._`undefined`)),t.if(G._`${e.evaluated}.dynamicItems`,()=>t.assign(G._`${e.evaluated}.items`,G._`undefined`))}function Xm(e,t){let i=typeof e=="object"&&e[t.schemaId];return i&&(t.code.source||t.code.process)?G._`/*# sourceURL=${i} */`:G.nil}function d5(e,t){if(zm(e)){if(jm(e),Om(e)){I5(e,t);return}}(0,Jm.boolOrEmptySchema)(e,t)}function Om({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let i in e)if(t.RULES.all[i])return!0;return!1}function zm(e){return typeof e.schema!="boolean"}function I5(e,t){let{schema:i,gen:n,opts:r}=e;if(r.$comment&&i.$comment)_m(e);C5(e),m5(e);let o=n.const("_errs",k.default.errors);Dm(e,o),n.var(t,G._`${o} === ${k.default.errors}`)}function jm(e){(0,Pt.checkUnknownRules)(e),c5(e)}function Dm(e,t){if(e.opts.jtd)return Em(e,[],!1,t);let i=(0,Sm.getSchemaTypes)(e.schema),n=(0,Sm.coerceAndCheckDataType)(e,i);Em(e,i,!n,t)}function c5(e){let{schema:t,errSchemaPath:i,opts:n,self:r}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&(0,Pt.schemaHasRulesButRef)(t,r.RULES))r.logger.warn(`$ref: keywords ignored in schema at path "${i}"`)}function u5(e){let{schema:t,opts:i}=e;if(t.default!==void 0&&i.useDefaults&&i.strictSchema)(0,Pt.checkStrictMode)(e,"default is ignored in the schema root")}function C5(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,r5.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function m5(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function _m({gen:e,schemaEnv:t,schema:i,errSchemaPath:n,opts:r}){let o=i.$comment;if(r.$comment===!0)e.code(G._`${k.default.self}.logger.log(${o})`);else if(typeof r.$comment=="function"){let s=G.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(G._`${k.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function p5(e){let{gen:t,schemaEnv:i,validateName:n,ValidationError:r,opts:o}=e;if(i.$async)t.if(G._`${k.default.errors} === 0`,()=>t.return(k.default.data),()=>t.throw(G._`new ${r}(${k.default.vErrors})`));else{if(t.assign(G._`${n}.errors`,k.default.vErrors),o.unevaluated)A5(e);t.return(G._`${k.default.errors} === 0`)}}function A5({gen:e,evaluated:t,props:i,items:n}){if(i instanceof G.Name)e.assign(G._`${t}.props`,i);if(n instanceof G.Name)e.assign(G._`${t}.items`,n)}function Em(e,t,i,n){let{gen:r,schema:o,data:s,allErrors:a,opts:g,self:l}=e,{RULES:d}=l;if(o.$ref&&(g.ignoreKeywordsWithRef||!(0,Pt.schemaHasRulesButRef)(o,d))){r.block(()=>Km(e,"$ref",d.all.$ref.definition));return}if(!g.jtd)b5(e,t);r.block(()=>{for(let C of d.rules)I(C);I(d.post)});function I(C){if(!(0,_g.shouldUseGroup)(o,C))return;if(C.type){if(r.if((0,Is.checkDataType)(C.type,s,g.strictNumbers)),Tm(e,C),t.length===1&&t[0]===C.type&&i)r.else(),(0,Is.reportTypeError)(e);r.endIf()}else Tm(e,C);if(!a)r.if(G._`${k.default.errors} === ${n||0}`)}}function Tm(e,t){let{gen:i,schema:n,opts:{useDefaults:r}}=e;if(r)(0,n5.assignDefaults)(e,t.type);i.block(()=>{for(let o of t.rules)if((0,_g.shouldUseRule)(n,o))Km(e,o.keyword,o.definition,t.type)})}function b5(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(Z5(e,t),!e.opts.allowUnionTypes)h5(e,t);f5(e,e.dataTypes)}function Z5(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((i)=>{if(!Qm(e.dataTypes,i))Qg(e,`type "${i}" not allowed by context "${e.dataTypes.join(",")}"`)}),y5(e,t)}function h5(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Qg(e,"use allowUnionTypes to allow union type keyword")}function f5(e,t){let i=e.self.RULES.all;for(let n in i){let r=i[n];if(typeof r=="object"&&(0,_g.shouldUseRule)(e.schema,r)){let{type:o}=r.definition;if(o.length&&!o.some((s)=>W5(t,s)))Qg(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function W5(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Qm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y5(e,t){let i=[];for(let n of e.dataTypes)if(Qm(t,n))i.push(n);else if(t.includes("integer")&&n==="number")i.push("integer");e.dataTypes=i}function Qg(e,t){let i=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${i}" (strictTypes)`,(0,Pt.checkStrictMode)(e,t,e.opts.strictTypes)}class Kg{constructor(e,t,i){if((0,Rr.validateKeywordUsage)(e,t,i),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=i,this.data=e.data,this.schema=e.schema[i],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Pt.schemaRefOrVal)(e,this.schema,i,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Lm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Rr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${i} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",k.default.errors)}result(e,t,i){this.failResult((0,G.not)(e),t,i)}failResult(e,t,i){if(this.gen.if(e),i)i();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,G.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(G._`${t} !== undefined && (${(0,G.or)(this.invalid$data(),e)})`)}error(e,t,i){if(t){this.setParams(t),this._error(e,i),this.setParams({});return}this._error(e,i)}_error(e,t){(e?Br.reportExtraError:Br.reportError)(this,this.def.error,t)}$dataError(){(0,Br.reportError)(this,this.def.$dataError||Br.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Br.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,i=G.nil){this.gen.block(()=>{this.check$data(e,i),t()})}check$data(e=G.nil,t=G.nil){if(!this.$data)return;let{gen:i,schemaCode:n,schemaType:r,def:o}=this;if(i.if((0,G.or)(G._`${n} === undefined`,t)),e!==G.nil)i.assign(e,!0);if(r.length||o.validateSchema){if(i.elseIf(this.invalid$data()),this.$dataError(),e!==G.nil)i.assign(e,!1)}i.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:i,def:n,it:r}=this;return(0,G.or)(o(),s());function o(){if(i.length){if(!(t instanceof G.Name))throw Error("ajv implementation error");let a=Array.isArray(i)?i:[i];return G._`${(0,Is.checkDataTypes)(a,t,r.opts.strictNumbers,Is.DataType.Wrong)}`}return G.nil}function s(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return G._`!${a}(${t})`}return G.nil}}subschema(e,t){let i=(0,Dg.getSubschema)(this.it,e);(0,Dg.extendSubschemaData)(i,this.it,e),(0,Dg.extendSubschemaMode)(i,e);let n={...this.it,...i,items:void 0,props:void 0};return d5(n,t),n}mergeEvaluated(e,t){let{it:i,gen:n}=this;if(!i.opts.unevaluated)return;if(i.props!==!0&&e.props!==void 0)i.props=Pt.mergeEvaluated.props(n,e.props,i.props,t);if(i.items!==!0&&e.items!==void 0)i.items=Pt.mergeEvaluated.items(n,e.items,i.items,t)}mergeValidEvaluated(e,t){let{it:i,gen:n}=this;if(i.opts.unevaluated&&(i.props!==!0||i.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,G.Name)),!0}}Lt.KeywordCxt=Kg;function Km(e,t,i,n){let r=new Kg(e,i,t);if("code"in i)i.code(r,n);else if(r.$data&&i.validate)(0,Rr.funcKeywordCode)(r,i);else if("macro"in i)(0,Rr.macroKeywordCode)(r,i);else if(i.compile||i.validate)(0,Rr.funcKeywordCode)(r,i)}var V5=/^\/(?:[^~]|~0|~1)*$/,B5=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Lm(e,{dataLevel:t,dataNames:i,dataPathArr:n}){let r,o;if(e==="")return k.default.rootData;if(e[0]==="/"){if(!V5.test(e))throw Error(`Invalid JSON-pointer: ${e}`);r=e,o=k.default.rootData}else{let l=B5.exec(e);if(!l)throw Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(r=l[2],r==="#"){if(d>=t)throw Error(g("property/index",d));return n[t-d]}if(d>t)throw Error(g("data",d));if(o=i[t-d],!r)return o}let s=o,a=r.split("/");for(let l of a)if(l)o=G._`${o}${(0,G.getProperty)((0,Pt.unescapeJsonPointer)(l))}`,s=G._`${s} && ${o}`;return s;function g(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Lt.getData=Lm});var Gr=f(function(Lg){Object.defineProperty(Lg,"__esModule",{value:!0});class Mm extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Lg.default=Mm});var An=f(function($g){Object.defineProperty($g,"__esModule",{value:!0});var Mg=Vr();class $m extends Error{constructor(e,t,i,n){super(n||`can't resolve reference ${i} from id ${t}`);this.missingRef=(0,Mg.resolveUrl)(e,t,i),this.missingSchema=(0,Mg.normalizeId)((0,Mg.getFullPath)(e,this.missingRef))}}$g.default=$m});var Fr=f(function(Me){Object.defineProperty(Me,"__esModule",{value:!0});Me.resolveSchema=Me.getCompilingSchema=Me.resolveRef=Me.compileSchema=Me.SchemaEnv=void 0;var ot=N(),R5=Gr(),Wi=Ke(),st=Vr(),qm=T(),G5=pn();class wr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let i;if(typeof e.schema=="object")i=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,st.normalizeId)(i===null||i===void 0?void 0:i[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=i===null||i===void 0?void 0:i.$async,this.refs={}}}Me.SchemaEnv=wr;function el(e){let t=ep.call(this,e);if(t)return t;let i=(0,st.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:r}=this.opts.code,{ownProperties:o}=this.opts,s=new ot.CodeGen(this.scope,{es5:n,lines:r,ownProperties:o}),a;if(e.$async)a=s.scopeValue("Error",{ref:R5.default,code:ot._`require("ajv/dist/runtime/validation_error").default`});let g=s.scopeName("validate");e.validateName=g;let l={gen:s,allErrors:this.opts.allErrors,data:Wi.default.data,parentData:Wi.default.parentData,parentDataProperty:Wi.default.parentDataProperty,dataNames:[Wi.default.data],dataPathArr:[ot.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,ot.stringify)(e.schema)}:{ref:e.schema}),validateName:g,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:i,baseId:e.baseId||i,schemaPath:ot.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ot._`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,G5.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let I=s.toString();if(d=`${s.scopeRefs(Wi.default.scope)}return ${I}`,this.opts.code.process)d=this.opts.code.process(d,e);let m=Function(`${Wi.default.self}`,`${Wi.default.scope}`,d)(this,this.scope.get());if(this.scope.value(g,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async)m.$async=!0;if(this.opts.code.source===!0)m.source={validateName:g,validateCode:I,scopeValues:s._values};if(this.opts.unevaluated){let{props:A,items:c}=l;if(m.evaluated={props:A instanceof ot.Name?void 0:A,items:c instanceof ot.Name?void 0:c,dynamicProps:A instanceof ot.Name,dynamicItems:c instanceof ot.Name},m.source)m.source.evaluated=(0,ot.stringify)(m.evaluated)}return e.validate=m,e}catch(I){if(delete e.validate,delete e.validateName,d)this.logger.error("Error compiling schema, function code:",d);throw I}finally{this._compilations.delete(e)}}Me.compileSchema=el;function w5(e,t,i){var n;i=(0,st.resolveUrl)(this.opts.uriResolver,t,i);let r=e.refs[i];if(r)return r;let o=v5.call(this,e,i);if(o===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[i],{schemaId:a}=this.opts;if(s)o=new wr({schema:s,schemaId:a,root:e,baseId:t})}if(o===void 0)return;return e.refs[i]=F5.call(this,o)}Me.resolveRef=w5;function F5(e){if((0,st.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:el.call(this,e)}function ep(e){for(let t of this._compilations)if(H5(t,e))return t}Me.getCompilingSchema=ep;function H5(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function v5(e,t){let i;while(typeof(i=this.refs[t])=="string")t=i;return i||this.schemas[t]||cs.call(this,e,t)}function cs(e,t){let i=this.opts.uriResolver.parse(t),n=(0,st._getFullPath)(this.opts.uriResolver,i),r=(0,st.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===r)return qg.call(this,i,e);let o=(0,st.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=cs.call(this,e,s);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return qg.call(this,i,a)}if(typeof(s===null||s===void 0?void 0:s.schema)!=="object")return;if(!s.validate)el.call(this,s);if(o===(0,st.normalizeId)(t)){let{schema:a}=s,{schemaId:g}=this.opts,l=a[g];if(l)r=(0,st.resolveUrl)(this.opts.uriResolver,r,l);return new wr({schema:a,schemaId:g,root:e,baseId:r})}return qg.call(this,i,s)}Me.resolveSchema=cs;var k5=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qg(e,{baseId:t,schema:i,root:n}){var r;if(((r=e.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof i==="boolean")return;let g=i[(0,qm.unescapeFragment)(a)];if(g===void 0)return;i=g;let l=typeof i==="object"&&i[this.opts.schemaId];if(!k5.has(a)&&l)t=(0,st.resolveUrl)(this.opts.uriResolver,t,l)}let o;if(typeof i!="boolean"&&i.$ref&&!(0,qm.schemaHasRulesButRef)(i,this.RULES)){let a=(0,st.resolveUrl)(this.opts.uriResolver,t,i.$ref);o=cs.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new wr({schema:i,schemaId:s,root:n,baseId:t}),o.schema!==o.root.schema)return o;return}});var tp=f(function(Dj,P5){P5.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var il=f(function(_j,op){var N5=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),np=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function tl(e){let t="",i=0,n=0;for(n=0;n<e.length;n++){if(i=e[n].charCodeAt(0),i===48)continue;if(!(i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(i=e[n].charCodeAt(0),!(i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102))return"";t+=e[n]}return t}var x5=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ip(e){return e.length=0,!0}function Y5(e,t,i){if(e.length){let n=tl(e);if(n!=="")t.push(n);else return i.error=!0,!1;e.length=0}return!0}function S5(e){let t=0,i={error:!1,address:"",zone:""},n=[],r=[],o=!1,s=!1,a=Y5;for(let g=0;g<e.length;g++){let l=e[g];if(l==="["||l==="]")continue;if(l===":"){if(o===!0)s=!0;if(!a(r,n,i))break;if(++t>7){i.error=!0;break}if(g>0&&e[g-1]===":")o=!0;n.push(":");continue}else if(l==="%"){if(!a(r,n,i))break;a=ip}else{r.push(l);continue}}if(r.length)if(a===ip)i.zone=r.join("");else if(s)n.push(r.join(""));else n.push(tl(r));return i.address=n.join(""),i}function rp(e){if(X5(e,":")<2)return{host:e,isIPV6:!1};let t=S5(e);if(!t.error){let{address:i,address:n}=t;if(t.zone)i+="%"+t.zone,n+="%25"+t.zone;return{host:i,isIPV6:!0,escapedHost:n}}else return{host:e,isIPV6:!1}}function X5(e,t){let i=0;for(let n=0;n<e.length;n++)if(e[n]===t)i++;return i}function E5(e){let t=e,i=[],n=-1,r=0;while(r=t.length){if(r===1)if(t===".")break;else if(t==="/"){i.push("/");break}else{i.push(t);break}else if(r===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){i.push("/");break}}}else if(r===3){if(t==="/.."){if(i.length!==0)i.pop();i.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),i.length!==0)i.pop();continue}}}}if((n=t.indexOf("/",1))===-1){i.push(t);break}else i.push(t.slice(0,n)),t=t.slice(n)}return i.join("")}function T5(e,t){let i=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=i(e.scheme);if(e.userinfo!==void 0)e.userinfo=i(e.userinfo);if(e.host!==void 0)e.host=i(e.host);if(e.path!==void 0)e.path=i(e.path);if(e.query!==void 0)e.query=i(e.query);if(e.fragment!==void 0)e.fragment=i(e.fragment);return e}function J5(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let i=unescape(e.host);if(!np(i)){let n=rp(i);if(n.isIPV6===!0)i=`[${n.escapedHost}]`;else i=e.host}t.push(i)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}op.exports={nonSimpleDomain:x5,recomposeAuthority:J5,normalizeComponentEncoding:T5,removeDotSegments:E5,isIPv4:np,isUUID:N5,normalizeIPv6:rp,stringArrayToHexStripped:tl}});var dp=f(function(Qj,lp){var{isUUID:U5}=il(),O5=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,z5=["http","https","ws","wss","urn","urn:uuid"];function j5(e){return z5.indexOf(e)!==-1}function nl(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function sp(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function ap(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function D5(e){return e.secure=nl(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function _5(e){if(e.port===(nl(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,i]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}function Q5(e,t){if(!e.path)return e.error="URN can not be parsed",e;let i=e.path.match(O5);if(i){let n=t.scheme||e.scheme||"urn";e.nid=i[1].toLowerCase(),e.nss=i[2];let r=`${n}:${t.nid||e.nid}`,o=rl(r);if(e.path=void 0,o)e=o.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function K5(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let i=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),r=`${i}:${t.nid||n}`,o=rl(r);if(o)e=o.serialize(e,t);let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function L5(e,t){let i=e;if(i.uuid=i.nss,i.nss=void 0,!t.tolerant&&(!i.uuid||!U5(i.uuid)))i.error=i.error||"UUID is not valid.";return i}function M5(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var gp={scheme:"http",domainHost:!0,parse:sp,serialize:ap},$5={scheme:"https",domainHost:gp.domainHost,parse:sp,serialize:ap},us={scheme:"ws",domainHost:!0,parse:D5,serialize:_5},q5={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},ev={scheme:"urn",parse:Q5,serialize:K5,skipNormalize:!0},tv={scheme:"urn:uuid",parse:L5,serialize:M5,skipNormalize:!0},Cs={http:gp,https:$5,ws:us,wss:q5,urn:ev,"urn:uuid":tv};Object.setPrototypeOf(Cs,null);function rl(e){return e&&(Cs[e]||Cs[e.toLowerCase()])||void 0}lp.exports={wsIsSecure:nl,SCHEMES:Cs,isValidSchemeName:j5,getSchemeHandler:rl}});var up=f(function(Kj,ps){var{normalizeIPv6:iv,removeDotSegments:Hr,recomposeAuthority:nv,normalizeComponentEncoding:ms,isIPv4:rv,nonSimpleDomain:ov}=il(),{SCHEMES:sv,getSchemeHandler:Ip}=dp();function av(e,t){if(typeof e==="string")e=ht(Nt(e,t),t);else if(typeof e==="object")e=Nt(ht(e,t),t);return e}function gv(e,t,i){let n=i?Object.assign({scheme:"null"},i):{scheme:"null"},r=cp(Nt(e,n),Nt(t,n),n,!0);return n.skipEscape=!0,ht(r,n)}function cp(e,t,i,n){let r={};if(!n)e=Nt(ht(e,i),i),t=Nt(ht(t,i),i);if(i=i||{},!i.tolerant&&t.scheme)r.scheme=t.scheme,r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=Hr(t.path||""),r.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=Hr(t.path||""),r.query=t.query;else{if(!t.path)if(r.path=e.path,t.query!==void 0)r.query=t.query;else r.query=e.query;else{if(t.path[0]==="/")r.path=Hr(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)r.path="/"+t.path;else if(!e.path)r.path=t.path;else r.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;r.path=Hr(r.path)}r.query=t.query}r.userinfo=e.userinfo,r.host=e.host,r.port=e.port}r.scheme=e.scheme}return r.fragment=t.fragment,r}function lv(e,t,i){if(typeof e==="string")e=unescape(e),e=ht(ms(Nt(e,i),!0),{...i,skipEscape:!0});else if(typeof e==="object")e=ht(ms(e,!0),{...i,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ht(ms(Nt(t,i),!0),{...i,skipEscape:!0});else if(typeof t==="object")t=ht(ms(t,!0),{...i,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ht(e,t){let i={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),r=[],o=Ip(n.scheme||i.scheme);if(o&&o.serialize)o.serialize(i,n);if(i.path!==void 0)if(!n.skipEscape){if(i.path=escape(i.path),i.scheme!==void 0)i.path=i.path.split("%3A").join(":")}else i.path=unescape(i.path);if(n.reference!=="suffix"&&i.scheme)r.push(i.scheme,":");let s=nv(i);if(s!==void 0){if(n.reference!=="suffix")r.push("//");if(r.push(s),i.path&&i.path[0]!=="/")r.push("/")}if(i.path!==void 0){let a=i.path;if(!n.absolutePath&&(!o||!o.absolutePath))a=Hr(a);if(s===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);r.push(a)}if(i.query!==void 0)r.push("?",i.query);if(i.fragment!==void 0)r.push("#",i.fragment);return r.join("")}var dv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nt(e,t){let i=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1;if(i.reference==="suffix")if(i.scheme)e=i.scheme+":"+e;else e="//"+e;let o=e.match(dv);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port))n.port=o[5];if(n.host)if(rv(n.host)===!1){let g=iv(n.host);n.host=g.host.toLowerCase(),r=g.isIPV6}else r=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(i.reference&&i.reference!=="suffix"&&i.reference!==n.reference)n.error=n.error||"URI is not a "+i.reference+" reference.";let s=Ip(i.scheme||n.scheme);if(!i.unicodeSupport&&(!s||!s.unicodeSupport)){if(n.host&&(i.domainHost||s&&s.domainHost)&&r===!1&&ov(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}}if(!s||s&&!s.skipNormalize){if(e.indexOf("%")!==-1){if(n.scheme!==void 0)n.scheme=unescape(n.scheme);if(n.host!==void 0)n.host=unescape(n.host)}if(n.path)n.path=escape(unescape(n.path));if(n.fragment)n.fragment=encodeURI(decodeURIComponent(n.fragment))}if(s&&s.parse)s.parse(n,i)}else n.error=n.error||"URI can not be parsed.";return n}var ol={SCHEMES:sv,normalize:av,resolve:gv,resolveComponent:cp,equal:lv,serialize:ht,parse:Nt};ps.exports=ol;ps.exports.default=ol;ps.exports.fastUri=ol});var mp=f(function(sl){Object.defineProperty(sl,"__esModule",{value:!0});var Cp=up();Cp.code='require("ajv/dist/runtime/uri").default';sl.default=Cp});var ll=f(function(me){Object.defineProperty(me,"__esModule",{value:!0});me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=void 0;var Iv=pn();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return Iv.KeywordCxt}});var bn=N();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return bn._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return bn.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return bn.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return bn.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return bn.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return bn.CodeGen}});var cv=Gr(),hp=An(),uv=Yg(),vr=Fr(),Cv=N(),kr=Vr(),As=yr(),gl=T(),pp=tp(),mv=mp(),fp=(e,t)=>new RegExp(e,t);fp.code="new RegExp";var pv=["removeAdditional","useDefaults","coerceTypes"],Av=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bv={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Zv={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ap=200;function hv(e){var t,i,n,r,o,s,a,g,l,d,I,C,m,A,c,u,p,Z,h,W,y,V,H,Y,v;let K=e.strict,re=(t=e.code)===null||t===void 0?void 0:t.optimize,le=re===!0||re===void 0?1:re||0,je=(n=(i=e.code)===null||i===void 0?void 0:i.regExp)!==null&&n!==void 0?n:fp,_n=(r=e.uriResolver)!==null&&r!==void 0?r:mv.default;return{strictSchema:(s=(o=e.strictSchema)!==null&&o!==void 0?o:K)!==null&&s!==void 0?s:!0,strictNumbers:(g=(a=e.strictNumbers)!==null&&a!==void 0?a:K)!==null&&g!==void 0?g:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:K)!==null&&d!==void 0?d:"log",strictTuples:(C=(I=e.strictTuples)!==null&&I!==void 0?I:K)!==null&&C!==void 0?C:"log",strictRequired:(A=(m=e.strictRequired)!==null&&m!==void 0?m:K)!==null&&A!==void 0?A:!1,code:e.code?{...e.code,optimize:le,regExp:je}:{optimize:le,regExp:je},loopRequired:(c=e.loopRequired)!==null&&c!==void 0?c:Ap,loopEnum:(u=e.loopEnum)!==null&&u!==void 0?u:Ap,meta:(p=e.meta)!==null&&p!==void 0?p:!0,messages:(Z=e.messages)!==null&&Z!==void 0?Z:!0,inlineRefs:(h=e.inlineRefs)!==null&&h!==void 0?h:!0,schemaId:(W=e.schemaId)!==null&&W!==void 0?W:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(V=e.validateSchema)!==null&&V!==void 0?V:!0,validateFormats:(H=e.validateFormats)!==null&&H!==void 0?H:!0,unicodeRegExp:(Y=e.unicodeRegExp)!==null&&Y!==void 0?Y:!0,int32range:(v=e.int32range)!==null&&v!==void 0?v:!0,uriResolver:_n}}class bs{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...hv(e)};let{es5:t,lines:i}=this.opts.code;this.scope=new Cv.ValueScope({scope:{},prefixes:Av,es5:t,lines:i}),this.logger=Rv(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,uv.getRules)(),bp.call(this,bv,e,"NOT SUPPORTED"),bp.call(this,Zv,e,"DEPRECATED","warn"),this._metaOpts=Vv.call(this),e.formats)Wv.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)yv.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);fv.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:i}=this.opts,n=pp;if(i==="id")n={...pp},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[i],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let i;if(typeof e=="string"){if(i=this.getSchema(e),!i)throw Error(`no schema with key or ref "${e}"`)}else i=this.compile(e);let n=i(t);if(!("$async"in i))this.errors=i.errors;return n}compile(e,t){let i=this._addSchema(e,t);return i.validate||this._compileSchemaEnv(i)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:i}=this.opts;return n.call(this,e,t);async function n(l,d){await r.call(this,l.$schema);let I=this._addSchema(l,d);return I.validate||o.call(this,I)}async function r(l){if(l&&!this.getSchema(l))await n.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof hp.default))throw d;return s.call(this,d),await a.call(this,d.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:d}){if(this.refs[l])throw Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function a(l){let d=await g.call(this,l);if(!this.refs[l])await r.call(this,d.$schema);if(!this.refs[l])this.addSchema(d,l,t)}async function g(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=i(l))}finally{delete this._loading[l]}}}addSchema(e,t,i,n=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,i,n);return this}let r;if(typeof e==="object"){let{schemaId:o}=this.opts;if(r=e[o],r!==void 0&&typeof r!="string")throw Error(`schema ${o} must be string`)}return t=(0,kr.normalizeId)(t||r),this._checkUnique(t),this.schemas[t]=this._addSchema(e,i,t,n,!0),this}addMetaSchema(e,t,i=this.opts.validateSchema){return this.addSchema(e,t,!0,i),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let i;if(i=e.$schema,i!==void 0&&typeof i!="string")throw Error("$schema must be a string");if(i=i||this.opts.defaultMeta||this.defaultMeta(),!i)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(i,e);if(!n&&t){let r="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(r);else throw Error(r)}return n}getSchema(e){let t;while(typeof(t=Zp.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:i}=this.opts,n=new vr.SchemaEnv({schema:{},schemaId:i});if(t=vr.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Zp.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let i=e[this.opts.schemaId];if(i)i=(0,kr.normalizeId)(i),delete this.schemas[i],delete this.refs[i];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let i;if(typeof e=="string"){if(i=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=i}else if(typeof e=="object"&&t===void 0){if(t=e,i=t.keyword,Array.isArray(i)&&!i.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(wv.call(this,i,t),!t)return(0,gl.eachItem)(i,(r)=>al.call(this,r)),this;Hv.call(this,t);let n={...t,type:(0,As.getJSONTypes)(t.type),schemaType:(0,As.getJSONTypes)(t.schemaType)};return(0,gl.eachItem)(i,n.type.length===0?(r)=>al.call(this,r,n):(r)=>n.type.forEach((o)=>al.call(this,r,n,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let i of t.rules){let n=i.rules.findIndex((r)=>r.keyword===e);if(n>=0)i.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:i="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${i}${n.instancePath} ${n.message}`).reduce((n,r)=>n+t+r)}$dataMetaSchema(e,t){let i=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let r=n.split("/").slice(1),o=e;for(let s of r)o=o[s];for(let s in i){let a=i[s];if(typeof a!="object")continue;let{$data:g}=a.definition,l=o[s];if(g&&l)o[s]=Wp(l)}}return e}_removeAllSchemas(e,t){for(let i in e){let n=e[i];if(!t||t.test(i)){if(typeof n=="string")delete e[i];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[i]}}}_addSchema(e,t,i,n=this.opts.validateSchema,r=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof e=="object")o=e[s];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;i=(0,kr.normalizeId)(o||i);let g=kr.getSchemaRefs.call(this,e,i);if(a=new vr.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:i,localRefs:g}),this._cache.set(a.schema,a),r&&!i.startsWith("#")){if(i)this._checkUnique(i);this.refs[i]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else vr.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{vr.compileSchema.call(this,e)}finally{this.opts=t}}}bs.ValidationError=cv.default;bs.MissingRefError=hp.default;me.default=bs;function bp(e,t,i,n="error"){for(let r in e){let o=r;if(o in t)this.logger[n](`${i}: option ${r}. ${e[o]}`)}}function Zp(e){return e=(0,kr.normalizeId)(e),this.schemas[e]||this.refs[e]}function fv(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Wv(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function yv(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let i=e[t];if(!i.keyword)i.keyword=t;this.addKeyword(i)}}function Vv(){let e={...this.opts};for(let t of pv)delete e[t];return e}var Bv={log(){},warn(){},error(){}};function Rv(e){if(e===!1)return Bv;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var Gv=/^[a-z_$][a-z0-9_$:-]*$/i;function wv(e,t){let{RULES:i}=this;if((0,gl.eachItem)(e,(n)=>{if(i.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!Gv.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function al(e,t,i){var n;let r=t===null||t===void 0?void 0:t.post;if(i&&r)throw Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=r?o.post:o.rules.find(({type:g})=>g===i);if(!s)s={type:i,rules:[]},o.rules.push(s);if(o.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,As.getJSONTypes)(t.type),schemaType:(0,As.getJSONTypes)(t.schemaType)}};if(t.before)Fv.call(this,s,a,t.before);else s.rules.push(a);o.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((g)=>this.addKeyword(g))}function Fv(e,t,i){let n=e.rules.findIndex((r)=>r.keyword===i);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${i} is not defined`)}function Hv(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Wp(t);e.validateSchema=this.compile(t,!0)}var vv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Wp(e){return{anyOf:[e,vv]}}});var yp=f(function(dl){Object.defineProperty(dl,"__esModule",{value:!0});var kv={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};dl.default=kv});var fs=f(function(yi){Object.defineProperty(yi,"__esModule",{value:!0});yi.callRef=yi.getValidate=void 0;var Pv=An(),Vp=Le(),Xe=N(),Zn=Ke(),Bp=Fr(),Zs=T(),Nv={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:i,it:n}=e,{baseId:r,schemaEnv:o,validateName:s,opts:a,self:g}=n,{root:l}=o;if((i==="#"||i==="#/")&&r===l.baseId)return I();let d=Bp.resolveRef.call(g,l,r,i);if(d===void 0)throw new Pv.default(n.opts.uriResolver,r,i);if(d instanceof Bp.SchemaEnv)return C(d);return m(d);function I(){if(o===l)return hs(e,s,o,o.$async);let A=t.scopeValue("root",{ref:l});return hs(e,Xe._`${A}.validate`,l,l.$async)}function C(A){let c=Rp(e,A);hs(e,c,A,A.$async)}function m(A){let c=t.scopeValue("schema",a.code.source===!0?{ref:A,code:(0,Xe.stringify)(A)}:{ref:A}),u=t.name("valid"),p=e.subschema({schema:A,dataTypes:[],schemaPath:Xe.nil,topSchemaRef:c,errSchemaPath:i},u);e.mergeEvaluated(p),e.ok(u)}}};function Rp(e,t){let{gen:i}=e;return t.validate?i.scopeValue("validate",{ref:t.validate}):Xe._`${i.scopeValue("wrapper",{ref:t})}.validate`}yi.getValidate=Rp;function hs(e,t,i,n){let{gen:r,it:o}=e,{allErrors:s,schemaEnv:a,opts:g}=o,l=g.passContext?Zn.default.this:Xe.nil;if(n)d();else I();function d(){if(!a.$async)throw Error("async schema referenced by sync schema");let A=r.let("valid");r.try(()=>{if(r.code(Xe._`await ${(0,Vp.callValidateCode)(e,t,l)}`),m(t),!s)r.assign(A,!0)},(c)=>{if(r.if(Xe._`!(${c} instanceof ${o.ValidationError})`,()=>r.throw(c)),C(c),!s)r.assign(A,!1)}),e.ok(A)}function I(){e.result((0,Vp.callValidateCode)(e,t,l),()=>m(t),()=>C(t))}function C(A){let c=Xe._`${A}.errors`;r.assign(Zn.default.vErrors,Xe._`${Zn.default.vErrors} === null ? ${c} : ${Zn.default.vErrors}.concat(${c})`),r.assign(Zn.default.errors,Xe._`${Zn.default.vErrors}.length`)}function m(A){var c;if(!o.opts.unevaluated)return;let u=(c=i===null||i===void 0?void 0:i.validate)===null||c===void 0?void 0:c.evaluated;if(o.props!==!0)if(u&&!u.dynamicProps){if(u.props!==void 0)o.props=Zs.mergeEvaluated.props(r,u.props,o.props)}else{let p=r.var("props",Xe._`${A}.evaluated.props`);o.props=Zs.mergeEvaluated.props(r,p,o.props,Xe.Name)}if(o.items!==!0)if(u&&!u.dynamicItems){if(u.items!==void 0)o.items=Zs.mergeEvaluated.items(r,u.items,o.items)}else{let p=r.var("items",Xe._`${A}.evaluated.items`);o.items=Zs.mergeEvaluated.items(r,p,o.items,Xe.Name)}}}yi.callRef=hs;yi.default=Nv});var cl=f(function(Il){Object.defineProperty(Il,"__esModule",{value:!0});var xv=yp(),Yv=fs(),Sv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xv.default,Yv.default];Il.default=Sv});var Gp=f(function(ul){Object.defineProperty(ul,"__esModule",{value:!0});var Ws=N(),Mt=Ws.operators,ys={maximum:{okStr:"<=",ok:Mt.LTE,fail:Mt.GT},minimum:{okStr:">=",ok:Mt.GTE,fail:Mt.LT},exclusiveMaximum:{okStr:"<",ok:Mt.LT,fail:Mt.GTE},exclusiveMinimum:{okStr:">",ok:Mt.GT,fail:Mt.LTE}},Xv={message:({keyword:e,schemaCode:t})=>Ws.str`must be ${ys[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ws._`{comparison: ${ys[e].okStr}, limit: ${t}}`},Ev={keyword:Object.keys(ys),type:"number",schemaType:"number",$data:!0,error:Xv,code(e){let{keyword:t,data:i,schemaCode:n}=e;e.fail$data(Ws._`${i} ${ys[t].fail} ${n} || isNaN(${i})`)}};ul.default=Ev});var wp=f(function(Cl){Object.defineProperty(Cl,"__esModule",{value:!0});var Pr=N(),Tv={message:({schemaCode:e})=>Pr.str`must be multiple of ${e}`,params:({schemaCode:e})=>Pr._`{multipleOf: ${e}}`},Jv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Tv,code(e){let{gen:t,data:i,schemaCode:n,it:r}=e,o=r.opts.multipleOfPrecision,s=t.let("res"),a=o?Pr._`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:Pr._`${s} !== parseInt(${s})`;e.fail$data(Pr._`(${n} === 0 || (${s} = ${i}/${n}, ${a}))`)}};Cl.default=Jv});var Hp=f(function(ml){Object.defineProperty(ml,"__esModule",{value:!0});function Fp(e){let t=e.length,i=0,n=0,r;while(n<t)if(i++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t){if(r=e.charCodeAt(n),(r&64512)===56320)n++}return i}ml.default=Fp;Fp.code='require("ajv/dist/runtime/ucs2length").default'});var vp=f(function(pl){Object.defineProperty(pl,"__esModule",{value:!0});var Vi=N(),Uv=T(),Ov=Hp(),zv={message({keyword:e,schemaCode:t}){let i=e==="maxLength"?"more":"fewer";return Vi.str`must NOT have ${i} than ${t} characters`},params:({schemaCode:e})=>Vi._`{limit: ${e}}`},jv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:zv,code(e){let{keyword:t,data:i,schemaCode:n,it:r}=e,o=t==="maxLength"?Vi.operators.GT:Vi.operators.LT,s=r.opts.unicode===!1?Vi._`${i}.length`:Vi._`${(0,Uv.useFunc)(e.gen,Ov.default)}(${i})`;e.fail$data(Vi._`${s} ${o} ${n}`)}};pl.default=jv});var kp=f(function(Al){Object.defineProperty(Al,"__esModule",{value:!0});var Dv=Le(),Vs=N(),_v={message:({schemaCode:e})=>Vs.str`must match pattern "${e}"`,params:({schemaCode:e})=>Vs._`{pattern: ${e}}`},Qv={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_v,code(e){let{data:t,$data:i,schema:n,schemaCode:r,it:o}=e,s=o.opts.unicodeRegExp?"u":"",a=i?Vs._`(new RegExp(${r}, ${s}))`:(0,Dv.usePattern)(e,n);e.fail$data(Vs._`!${a}.test(${t})`)}};Al.default=Qv});var Pp=f(function(bl){Object.defineProperty(bl,"__esModule",{value:!0});var Nr=N(),Kv={message({keyword:e,schemaCode:t}){let i=e==="maxProperties"?"more":"fewer";return Nr.str`must NOT have ${i} than ${t} properties`},params:({schemaCode:e})=>Nr._`{limit: ${e}}`},Lv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Kv,code(e){let{keyword:t,data:i,schemaCode:n}=e,r=t==="maxProperties"?Nr.operators.GT:Nr.operators.LT;e.fail$data(Nr._`Object.keys(${i}).length ${r} ${n}`)}};bl.default=Lv});var Np=f(function(Zl){Object.defineProperty(Zl,"__esModule",{value:!0});var xr=Le(),Yr=N(),Mv=T(),$v={message:({params:{missingProperty:e}})=>Yr.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Yr._`{missingProperty: ${e}}`},qv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:$v,code(e){let{gen:t,schema:i,schemaCode:n,data:r,$data:o,it:s}=e,{opts:a}=s;if(!o&&i.length===0)return;let g=i.length>=a.loopRequired;if(s.allErrors)l();else d();if(a.strictRequired){let m=e.parentSchema.properties,{definedProperties:A}=e.it;for(let c of i)if((m===null||m===void 0?void 0:m[c])===void 0&&!A.has(c)){let u=s.schemaEnv.baseId+s.errSchemaPath,p=`required property "${c}" is not defined at "${u}" (strictRequired)`;(0,Mv.checkStrictMode)(s,p,s.opts.strictRequired)}}function l(){if(g||o)e.block$data(Yr.nil,I);else for(let m of i)(0,xr.checkReportMissingProp)(e,m)}function d(){let m=t.let("missing");if(g||o){let A=t.let("valid",!0);e.block$data(A,()=>C(m,A)),e.ok(A)}else t.if((0,xr.checkMissingProp)(e,i,m)),(0,xr.reportMissingProp)(e,m),t.else()}function I(){t.forOf("prop",n,(m)=>{e.setParams({missingProperty:m}),t.if((0,xr.noPropertyInData)(t,r,m,a.ownProperties),()=>e.error())})}function C(m,A){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(A,(0,xr.propertyInData)(t,r,m,a.ownProperties)),t.if((0,Yr.not)(A),()=>{e.error(),t.break()})},Yr.nil)}}};Zl.default=qv});var xp=f(function(hl){Object.defineProperty(hl,"__esModule",{value:!0});var Sr=N(),ek={message({keyword:e,schemaCode:t}){let i=e==="maxItems"?"more":"fewer";return Sr.str`must NOT have ${i} than ${t} items`},params:({schemaCode:e})=>Sr._`{limit: ${e}}`},tk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ek,code(e){let{keyword:t,data:i,schemaCode:n}=e,r=t==="maxItems"?Sr.operators.GT:Sr.operators.LT;e.fail$data(Sr._`${i}.length ${r} ${n}`)}};hl.default=tk});var Bs=f(function(fl){Object.defineProperty(fl,"__esModule",{value:!0});var Yp=zg();Yp.code='require("ajv/dist/runtime/equal").default';fl.default=Yp});var Sp=f(function(yl){Object.defineProperty(yl,"__esModule",{value:!0});var Wl=yr(),pe=N(),ik=T(),nk=Bs(),rk={message:({params:{i:e,j:t}})=>pe.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>pe._`{i: ${e}, j: ${t}}`},ok={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rk,code(e){let{gen:t,data:i,$data:n,schema:r,parentSchema:o,schemaCode:s,it:a}=e;if(!n&&!r)return;let g=t.let("valid"),l=o.items?(0,Wl.getSchemaTypes)(o.items):[];e.block$data(g,d,pe._`${s} === false`),e.ok(g);function d(){let A=t.let("i",pe._`${i}.length`),c=t.let("j");e.setParams({i:A,j:c}),t.assign(g,!0),t.if(pe._`${A} > 1`,()=>(I()?C:m)(A,c))}function I(){return l.length>0&&!l.some((A)=>A==="object"||A==="array")}function C(A,c){let u=t.name("item"),p=(0,Wl.checkDataTypes)(l,u,a.opts.strictNumbers,Wl.DataType.Wrong),Z=t.const("indices",pe._`{}`);t.for(pe._`;${A}--;`,()=>{if(t.let(u,pe._`${i}[${A}]`),t.if(p,pe._`continue`),l.length>1)t.if(pe._`typeof ${u} == "string"`,pe._`${u} += "_"`);t.if(pe._`typeof ${Z}[${u}] == "number"`,()=>{t.assign(c,pe._`${Z}[${u}]`),e.error(),t.assign(g,!1).break()}).code(pe._`${Z}[${u}] = ${A}`)})}function m(A,c){let u=(0,ik.useFunc)(t,nk.default),p=t.name("outer");t.label(p).for(pe._`;${A}--;`,()=>t.for(pe._`${c} = ${A}; ${c}--;`,()=>t.if(pe._`${u}(${i}[${A}], ${i}[${c}])`,()=>{e.error(),t.assign(g,!1).break(p)})))}}};yl.default=ok});var Xp=f(function(Bl){Object.defineProperty(Bl,"__esModule",{value:!0});var Vl=N(),sk=T(),ak=Bs(),gk={message:"must be equal to constant",params:({schemaCode:e})=>Vl._`{allowedValue: ${e}}`},lk={keyword:"const",$data:!0,error:gk,code(e){let{gen:t,data:i,$data:n,schemaCode:r,schema:o}=e;if(n||o&&typeof o=="object")e.fail$data(Vl._`!${(0,sk.useFunc)(t,ak.default)}(${i}, ${r})`);else e.fail(Vl._`${o} !== ${i}`)}};Bl.default=lk});var Ep=f(function(Rl){Object.defineProperty(Rl,"__esModule",{value:!0});var Xr=N(),dk=T(),Ik=Bs(),ck={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Xr._`{allowedValues: ${e}}`},uk={keyword:"enum",schemaType:"array",$data:!0,error:ck,code(e){let{gen:t,data:i,$data:n,schema:r,schemaCode:o,it:s}=e;if(!n&&r.length===0)throw Error("enum must have non-empty array");let a=r.length>=s.opts.loopEnum,g,l=()=>g!==null&&g!==void 0?g:g=(0,dk.useFunc)(t,Ik.default),d;if(a||n)d=t.let("valid"),e.block$data(d,I);else{if(!Array.isArray(r))throw Error("ajv implementation error");let m=t.const("vSchema",o);d=(0,Xr.or)(...r.map((A,c)=>C(m,c)))}e.pass(d);function I(){t.assign(d,!1),t.forOf("v",o,(m)=>t.if(Xr._`${l()}(${i}, ${m})`,()=>t.assign(d,!0).break()))}function C(m,A){let c=r[A];return typeof c==="object"&&c!==null?Xr._`${l()}(${i}, ${m}[${A}])`:Xr._`${i} === ${c}`}}};Rl.default=uk});var wl=f(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var Ck=Gp(),mk=wp(),pk=vp(),Ak=kp(),bk=Pp(),Zk=Np(),hk=xp(),fk=Sp(),Wk=Xp(),yk=Ep(),Vk=[Ck.default,mk.default,pk.default,Ak.default,bk.default,Zk.default,hk.default,fk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Wk.default,yk.default];Gl.default=Vk});var Hl=f(function(Er){Object.defineProperty(Er,"__esModule",{value:!0});Er.validateAdditionalItems=void 0;var Bi=N(),Fl=T(),Bk={message:({params:{len:e}})=>Bi.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Bi._`{limit: ${e}}`},Rk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Bk,code(e){let{parentSchema:t,it:i}=e,{items:n}=t;if(!Array.isArray(n)){(0,Fl.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}Tp(e,n)}};function Tp(e,t){let{gen:i,schema:n,data:r,keyword:o,it:s}=e;s.items=!0;let a=i.const("len",Bi._`${r}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(Bi._`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Fl.alwaysValidSchema)(s,n)){let l=i.var("valid",Bi._`${a} <= ${t.length}`);i.if((0,Bi.not)(l),()=>g(l)),e.ok(l)}function g(l){i.forRange("i",t.length,a,(d)=>{if(e.subschema({keyword:o,dataProp:d,dataPropType:Fl.Type.Num},l),!s.allErrors)i.if((0,Bi.not)(l),()=>i.break())})}}Er.validateAdditionalItems=Tp;Er.default=Rk});var vl=f(function(Tr){Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateTuple=void 0;var Jp=N(),Rs=T(),Gk=Le(),wk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return Up(e,"additionalItems",t);if(i.items=!0,(0,Rs.alwaysValidSchema)(i,t))return;e.ok((0,Gk.validateArray)(e))}};function Up(e,t,i=e.schema){let{gen:n,parentSchema:r,data:o,keyword:s,it:a}=e;if(d(r),a.opts.unevaluated&&i.length&&a.items!==!0)a.items=Rs.mergeEvaluated.items(n,i.length,a.items);let g=n.name("valid"),l=n.const("len",Jp._`${o}.length`);i.forEach((I,C)=>{if((0,Rs.alwaysValidSchema)(a,I))return;n.if(Jp._`${l} > ${C}`,()=>e.subschema({keyword:s,schemaProp:C,dataProp:C},g)),e.ok(g)});function d(I){let{opts:C,errSchemaPath:m}=a,A=i.length,c=A===I.minItems&&(A===I.maxItems||I[t]===!1);if(C.strictTuples&&!c){let u=`"${s}" is ${A}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Rs.checkStrictMode)(a,u,C.strictTuples)}}}Tr.validateTuple=Up;Tr.default=wk});var Op=f(function(kl){Object.defineProperty(kl,"__esModule",{value:!0});var Fk=vl(),Hk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,Fk.validateTuple)(e,"items")};kl.default=Hk});var jp=f(function(Pl){Object.defineProperty(Pl,"__esModule",{value:!0});var zp=N(),vk=T(),kk=Le(),Pk=Hl(),Nk={message:({params:{len:e}})=>zp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>zp._`{limit: ${e}}`},xk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Nk,code(e){let{schema:t,parentSchema:i,it:n}=e,{prefixItems:r}=i;if(n.items=!0,(0,vk.alwaysValidSchema)(n,t))return;if(r)(0,Pk.validateAdditionalItems)(e,r);else e.ok((0,kk.validateArray)(e))}};Pl.default=xk});var Dp=f(function(Nl){Object.defineProperty(Nl,"__esModule",{value:!0});var $e=N(),Gs=T(),Yk={message:({params:{min:e,max:t}})=>t===void 0?$e.str`must contain at least ${e} valid item(s)`:$e.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?$e._`{minContains: ${e}}`:$e._`{minContains: ${e}, maxContains: ${t}}`},Sk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Yk,code(e){let{gen:t,schema:i,parentSchema:n,data:r,it:o}=e,s,a,{minContains:g,maxContains:l}=n;if(o.opts.next)s=g===void 0?1:g,a=l;else s=1;let d=t.const("len",$e._`${r}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Gs.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Gs.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Gs.alwaysValidSchema)(o,i)){let c=$e._`${d} >= ${s}`;if(a!==void 0)c=$e._`${c} && ${d} <= ${a}`;e.pass(c);return}o.items=!0;let I=t.name("valid");if(a===void 0&&s===1)m(I,()=>t.if(I,()=>t.break()));else if(s===0){if(t.let(I,!0),a!==void 0)t.if($e._`${r}.length > 0`,C)}else t.let(I,!1),C();e.result(I,()=>e.reset());function C(){let c=t.name("_valid"),u=t.let("count",0);m(c,()=>t.if(c,()=>A(u)))}function m(c,u){t.forRange("i",0,d,(p)=>{e.subschema({keyword:"contains",dataProp:p,dataPropType:Gs.Type.Num,compositeRule:!0},c),u()})}function A(c){if(t.code($e._`${c}++`),a===void 0)t.if($e._`${c} >= ${s}`,()=>t.assign(I,!0).break());else if(t.if($e._`${c} > ${a}`,()=>t.assign(I,!1).break()),s===1)t.assign(I,!0);else t.if($e._`${c} >= ${s}`,()=>t.assign(I,!0))}}};Nl.default=Sk});var ws=f(function(ft){Object.defineProperty(ft,"__esModule",{value:!0});ft.validateSchemaDeps=ft.validatePropertyDeps=ft.error=void 0;var xl=N(),Xk=T(),Jr=Le();ft.error={message:({params:{property:e,depsCount:t,deps:i}})=>{let n=t===1?"property":"properties";return xl.str`must have ${n} ${i} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:i,missingProperty:n}})=>xl._`{property: ${e},
|
|
7
|
+
|| ${s} === "boolean" || ${r} === null`).assign(a,x._`[${r}]`)}}}function ZH({gen:e,parentData:t,parentDataProperty:i},n){e.if(x._`${t} !== undefined`,()=>e.assign(x._`${t}[${i}]`,n))}function Xg(e,t,i,n=un.Correct){let r=n===un.Correct?x.operators.EQ:x.operators.NEQ,o;switch(e){case"null":return x._`${t} ${r} null`;case"array":o=x._`Array.isArray(${t})`;break;case"object":o=x._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s(x._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return x._`typeof ${t} ${r} ${e}`}return n===un.Correct?o:(0,x.not)(o);function s(a=x.nil){return(0,x.and)(x._`typeof ${t} == "number"`,a,i?x._`isFinite(${t})`:x.nil)}}Ve.checkDataType=Xg;function Eg(e,t,i,n){if(e.length===1)return Xg(e[0],t,i,n);let r,o=(0,Zm.toHash)(e);if(o.array&&o.object){let s=x._`typeof ${t} != "object"`;r=o.null?s:x._`!${t} || ${s}`,delete o.null,delete o.array,delete o.object}else r=x.nil;if(o.number)delete o.integer;for(let s in o)r=(0,x.and)(r,Xg(s,t,i,n));return r}Ve.checkDataTypes=Eg;var hH={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?x._`{type: ${e}}`:x._`{type: ${t}}`};function Tg(e){let t=fH(e);(0,CH.reportError)(t,hH)}Ve.reportTypeError=Tg;function fH(e){let{gen:t,data:i,schema:n}=e,r=(0,Zm.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:i,schema:n.type,schemaCode:r,schemaValue:r,parentSchema:n,params:{},it:e}}});var ym=f(function(ls){Object.defineProperty(ls,"__esModule",{value:!0});ls.assignDefaults=void 0;var Cn=N(),WH=T();function yH(e,t){let{properties:i,items:n}=e.schema;if(t==="object"&&i)for(let r in i)Wm(e,r,i[r].default);else if(t==="array"&&Array.isArray(n))n.forEach((r,o)=>Wm(e,o,r.default))}ls.assignDefaults=yH;function Wm(e,t,i){let{gen:n,compositeRule:r,data:o,opts:s}=e;if(i===void 0)return;let a=Cn._`${o}${(0,Cn.getProperty)(t)}`;if(r){(0,WH.checkStrictMode)(e,`default is ignored for: ${a}`);return}let g=Cn._`${a} === undefined`;if(s.useDefaults==="empty")g=Cn._`${g} || ${a} === null || ${a} === ""`;n.if(g,Cn._`${a} = ${(0,Cn.stringify)(i)}`)}});var Le=f(function(_){Object.defineProperty(_,"__esModule",{value:!0});_.validateUnion=_.validateArray=_.usePattern=_.callValidateCode=_.schemaProperties=_.allSchemaProperties=_.noPropertyInData=_.propertyInData=_.isOwnProperty=_.hasPropFunc=_.reportMissingProp=_.checkMissingProp=_.checkReportMissingProp=void 0;var L=N(),Jg=T(),_t=Ke(),VH=T();function BH(e,t){let{gen:i,data:n,it:r}=e;i.if(Og(i,n,t,r.opts.ownProperties),()=>{e.setParams({missingProperty:L._`${t}`},!0),e.error()})}_.checkReportMissingProp=BH;function RH({gen:e,data:t,it:{opts:i}},n,r){return(0,L.or)(...n.map((o)=>(0,L.and)(Og(e,t,o,i.ownProperties),L._`${r} = ${o}`)))}_.checkMissingProp=RH;function GH(e,t){e.setParams({missingProperty:t},!0),e.error()}_.reportMissingProp=GH;function Vm(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:L._`Object.prototype.hasOwnProperty`})}_.hasPropFunc=Vm;function Ug(e,t,i){return L._`${Vm(e)}.call(${t}, ${i})`}_.isOwnProperty=Ug;function wH(e,t,i,n){let r=L._`${t}${(0,L.getProperty)(i)} !== undefined`;return n?L._`${r} && ${Ug(e,t,i)}`:r}_.propertyInData=wH;function Og(e,t,i,n){let r=L._`${t}${(0,L.getProperty)(i)} === undefined`;return n?(0,L.or)(r,(0,L.not)(Ug(e,t,i))):r}_.noPropertyInData=Og;function Bm(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}_.allSchemaProperties=Bm;function FH(e,t){return Bm(t).filter((i)=>!(0,Jg.alwaysValidSchema)(e,t[i]))}_.schemaProperties=FH;function HH({schemaCode:e,data:t,it:{gen:i,topSchemaRef:n,schemaPath:r,errorPath:o},it:s},a,g,l){let d=l?L._`${e}, ${t}, ${n}${r}`:t,I=[[_t.default.instancePath,(0,L.strConcat)(_t.default.instancePath,o)],[_t.default.parentData,s.parentData],[_t.default.parentDataProperty,s.parentDataProperty],[_t.default.rootData,_t.default.rootData]];if(s.opts.dynamicRef)I.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let C=L._`${d}, ${i.object(...I)}`;return g!==L.nil?L._`${a}.call(${g}, ${C})`:L._`${a}(${C})`}_.callValidateCode=HH;var vH=L._`new RegExp`;function kH({gen:e,it:{opts:t}},i){let n=t.unicodeRegExp?"u":"",{regExp:r}=t.code,o=r(i,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:L._`${r.code==="new RegExp"?vH:(0,VH.useFunc)(e,r)}(${i}, ${n})`})}_.usePattern=kH;function PH(e){let{gen:t,data:i,keyword:n,it:r}=e,o=t.name("valid");if(r.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(o,!0),s(()=>t.break()),o;function s(a){let g=t.const("len",L._`${i}.length`);t.forRange("i",0,g,(l)=>{e.subschema({keyword:n,dataProp:l,dataPropType:Jg.Type.Num},o),t.if((0,L.not)(o),a)})}}_.validateArray=PH;function NH(e){let{gen:t,schema:i,keyword:n,it:r}=e;if(!Array.isArray(i))throw Error("ajv implementation error");if(i.some((g)=>(0,Jg.alwaysValidSchema)(r,g))&&!r.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>i.forEach((g,l)=>{let d=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);if(t.assign(s,L._`${s} || ${a}`),!e.mergeValidEvaluated(d,a))t.if((0,L.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}_.validateUnion=NH});var wm=f(function(bt){Object.defineProperty(bt,"__esModule",{value:!0});bt.validateKeywordUsage=bt.validSchemaType=bt.funcKeywordCode=bt.macroKeywordCode=void 0;var Fe=N(),fi=Ke(),xH=Le(),YH=Wr();function SH(e,t){let{gen:i,keyword:n,schema:r,parentSchema:o,it:s}=e,a=t.macro.call(s.self,r,o,s),g=Gm(i,n,a);if(s.opts.validateSchema!==!1)s.self.validateSchema(a,!0);let l=i.name("valid");e.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:g,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}bt.macroKeywordCode=SH;function XH(e,t){var i;let{gen:n,keyword:r,schema:o,parentSchema:s,$data:a,it:g}=e;TH(g,t);let l=!a&&t.compile?t.compile.call(g.self,o,s,g):t.validate,d=Gm(n,r,l),I=n.let("valid");e.block$data(I,C),e.ok((i=t.valid)!==null&&i!==void 0?i:I);function C(){if(t.errors===!1){if(c(),t.modifying)Rm(e);u(()=>e.error())}else{let p=t.async?m():A();if(t.modifying)Rm(e);u(()=>EH(e,p))}}function m(){let p=n.let("ruleErrs",null);return n.try(()=>c(Fe._`await `),(Z)=>n.assign(I,!1).if(Fe._`${Z} instanceof ${g.ValidationError}`,()=>n.assign(p,Fe._`${Z}.errors`),()=>n.throw(Z))),p}function A(){let p=Fe._`${d}.errors`;return n.assign(p,null),c(Fe.nil),p}function c(p=t.async?Fe._`await `:Fe.nil){let Z=g.opts.passContext?fi.default.this:fi.default.self,h=!(("compile"in t)&&!a||t.schema===!1);n.assign(I,Fe._`${p}${(0,xH.callValidateCode)(e,d,Z,h)}`,t.modifying)}function u(p){var Z;n.if((0,Fe.not)((Z=t.valid)!==null&&Z!==void 0?Z:I),p)}}bt.funcKeywordCode=XH;function Rm(e){let{gen:t,data:i,it:n}=e;t.if(n.parentData,()=>t.assign(i,Fe._`${n.parentData}[${n.parentDataProperty}]`))}function EH(e,t){let{gen:i}=e;i.if(Fe._`Array.isArray(${t})`,()=>{i.assign(fi.default.vErrors,Fe._`${fi.default.vErrors} === null ? ${t} : ${fi.default.vErrors}.concat(${t})`).assign(fi.default.errors,Fe._`${fi.default.vErrors}.length`),(0,YH.extendErrors)(e)},()=>e.error())}function TH({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function Gm(e,t,i){if(i===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof i=="function"?{ref:i}:{ref:i,code:(0,Fe.stringify)(i)})}function JH(e,t,i=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||i&&typeof e>"u")}bt.validSchemaType=JH;function UH({schema:e,opts:t,self:i,errSchemaPath:n},r,o){if(Array.isArray(r.keyword)?!r.keyword.includes(o):r.keyword!==o)throw Error("ajv implementation error");let s=r.dependencies;if(s===null||s===void 0?void 0:s.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(r.validateSchema){if(!r.validateSchema(e[o])){let g=`keyword "${o}" value is invalid at path "${n}": `+i.errorsText(r.validateSchema.errors);if(t.validateSchema==="log")i.logger.error(g);else throw Error(g)}}}bt.validateKeywordUsage=UH});var Hm=f(function(Qt){Object.defineProperty(Qt,"__esModule",{value:!0});Qt.extendSubschemaMode=Qt.extendSubschemaData=Qt.getSubschema=void 0;var Zt=N(),Fm=T();function OH(e,{keyword:t,schemaProp:i,schema:n,schemaPath:r,errSchemaPath:o,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return i===void 0?{schema:a,schemaPath:Zt._`${e.schemaPath}${(0,Zt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[i],schemaPath:Zt._`${e.schemaPath}${(0,Zt.getProperty)(t)}${(0,Zt.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Fm.escapeFragment)(i)}`}}if(n!==void 0){if(r===void 0||o===void 0||s===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:r,topSchemaRef:s,errSchemaPath:o}}throw Error('either "keyword" or "schema" must be passed')}Qt.getSubschema=OH;function zH(e,t,{dataProp:i,dataPropType:n,data:r,dataTypes:o,propertyName:s}){if(r!==void 0&&i!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(i!==void 0){let{errorPath:l,dataPathArr:d,opts:I}=t,C=a.let("data",Zt._`${t.data}${(0,Zt.getProperty)(i)}`,!0);g(C),e.errorPath=Zt.str`${l}${(0,Fm.getErrorPath)(i,n,I.jsPropertySyntax)}`,e.parentDataProperty=Zt._`${i}`,e.dataPathArr=[...d,e.parentDataProperty]}if(r!==void 0){let l=r instanceof Zt.Name?r:a.let("data",r,!0);if(g(l),s!==void 0)e.propertyName=s}if(o)e.dataTypes=o;function g(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Qt.extendSubschemaData=zH;function jH(e,{jtdDiscriminator:t,jtdMetadata:i,compositeRule:n,createErrors:r,allErrors:o}){if(n!==void 0)e.compositeRule=n;if(r!==void 0)e.createErrors=r;if(o!==void 0)e.allErrors=o;e.jtdDiscriminator=t,e.jtdMetadata=i}Qt.extendSubschemaMode=jH});var zg=f(function(Tj,vm){vm.exports=function e(t,i){if(t===i)return!0;if(t&&i&&typeof t=="object"&&typeof i=="object"){if(t.constructor!==i.constructor)return!1;var n,r,o;if(Array.isArray(t)){if(n=t.length,n!=i.length)return!1;for(r=n;r--!==0;)if(!e(t[r],i[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(i).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(i,o[r]))return!1;for(r=n;r--!==0;){var s=o[r];if(!e(t[s],i[s]))return!1}return!0}return t!==t&&i!==i}});var Pm=f(function(Jj,km){var Kt=km.exports=function(e,t,i){if(typeof t=="function")i=t,t={};i=t.cb||i;var n=typeof i=="function"?i:i.pre||function(){},r=i.post||function(){};ds(t,n,r,e,"",e)};Kt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Kt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Kt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Kt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ds(e,t,i,n,r,o,s,a,g,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,r,o,s,a,g,l);for(var d in n){var I=n[d];if(Array.isArray(I)){if(d in Kt.arrayKeywords)for(var C=0;C<I.length;C++)ds(e,t,i,I[C],r+"/"+d+"/"+C,o,r,d,n,C)}else if(d in Kt.propsKeywords){if(I&&typeof I=="object")for(var m in I)ds(e,t,i,I[m],r+"/"+d+"/"+DH(m),o,r,d,n,m)}else if(d in Kt.keywords||e.allKeys&&!(d in Kt.skipKeywords))ds(e,t,i,I,r+"/"+d,o,r,d,n)}i(n,r,o,s,a,g,l)}}function DH(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Vr=f(function(Se){Object.defineProperty(Se,"__esModule",{value:!0});Se.getSchemaRefs=Se.resolveUrl=Se.normalizeId=Se._getFullPath=Se.getFullPath=Se.inlineRef=void 0;var _H=T(),QH=zg(),KH=Pm(),LH=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function MH(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!jg(e);if(!t)return!1;return Nm(e)<=t}Se.inlineRef=MH;var $H=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jg(e){for(let t in e){if($H.has(t))return!0;let i=e[t];if(Array.isArray(i)&&i.some(jg))return!0;if(typeof i=="object"&&jg(i))return!0}return!1}function Nm(e){let t=0;for(let i in e){if(i==="$ref")return 1/0;if(t++,LH.has(i))continue;if(typeof e[i]=="object")(0,_H.eachItem)(e[i],(n)=>t+=Nm(n));if(t===1/0)return 1/0}return t}function xm(e,t="",i){if(i!==!1)t=mn(t);let n=e.parse(t);return Ym(e,n)}Se.getFullPath=xm;function Ym(e,t){return e.serialize(t).split("#")[0]+"#"}Se._getFullPath=Ym;var qH=/#\/?$/;function mn(e){return e?e.replace(qH,""):""}Se.normalizeId=mn;function e5(e,t,i){return i=mn(i),e.resolve(t,i)}Se.resolveUrl=e5;var t5=/^[a-z_][-a-z0-9._]*$/i;function i5(e,t){if(typeof e=="boolean")return{};let{schemaId:i,uriResolver:n}=this.opts,r=mn(e[i]||t),o={"":r},s=xm(n,r,!1),a={},g=new Set;return KH(e,{allKeys:!0},(I,C,m,A)=>{if(A===void 0)return;let c=s+C,u=o[A];if(typeof I[i]=="string")u=p.call(this,I[i]);Z.call(this,I.$anchor),Z.call(this,I.$dynamicAnchor),o[C]=u;function p(h){let W=this.opts.uriResolver.resolve;if(h=mn(u?W(u,h):h),g.has(h))throw d(h);g.add(h);let y=this.refs[h];if(typeof y=="string")y=this.refs[y];if(typeof y=="object")l(I,y.schema,h);else if(h!==mn(c))if(h[0]==="#")l(I,a[h],h),a[h]=I;else this.refs[h]=c;return h}function Z(h){if(typeof h=="string"){if(!t5.test(h))throw Error(`invalid anchor "${h}"`);p.call(this,`#${h}`)}}}),a;function l(I,C,m){if(C!==void 0&&!QH(I,C))throw d(m)}function d(I){return Error(`reference "${I}" resolves to more than one schema`)}}Se.getSchemaRefs=i5});var pn=f(function(Lt){Object.defineProperty(Lt,"__esModule",{value:!0});Lt.getData=Lt.KeywordCxt=Lt.validateFunctionCode=void 0;var Jm=pm(),Sm=yr(),_g=Sg(),Is=yr(),n5=ym(),Rr=wm(),Dg=Hm(),G=N(),k=Ke(),r5=Vr(),Pt=T(),Br=Wr();function o5(e){if(zm(e)){if(jm(e),Om(e)){g5(e);return}}Um(e,()=>(0,Jm.topBoolOrEmptySchema)(e))}Lt.validateFunctionCode=o5;function Um({gen:e,validateName:t,schema:i,schemaEnv:n,opts:r},o){if(r.code.es5)e.func(t,G._`${k.default.data}, ${k.default.valCxt}`,n.$async,()=>{e.code(G._`"use strict"; ${Xm(i,r)}`),a5(e,r),e.code(o)});else e.func(t,G._`${k.default.data}, ${s5(r)}`,n.$async,()=>e.code(Xm(i,r)).code(o))}function s5(e){return G._`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${e.dynamicRef?G._`, ${k.default.dynamicAnchors}={}`:G.nil}}={}`}function a5(e,t){e.if(k.default.valCxt,()=>{if(e.var(k.default.instancePath,G._`${k.default.valCxt}.${k.default.instancePath}`),e.var(k.default.parentData,G._`${k.default.valCxt}.${k.default.parentData}`),e.var(k.default.parentDataProperty,G._`${k.default.valCxt}.${k.default.parentDataProperty}`),e.var(k.default.rootData,G._`${k.default.valCxt}.${k.default.rootData}`),t.dynamicRef)e.var(k.default.dynamicAnchors,G._`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{if(e.var(k.default.instancePath,G._`""`),e.var(k.default.parentData,G._`undefined`),e.var(k.default.parentDataProperty,G._`undefined`),e.var(k.default.rootData,k.default.data),t.dynamicRef)e.var(k.default.dynamicAnchors,G._`{}`)})}function g5(e){let{schema:t,opts:i,gen:n}=e;Um(e,()=>{if(i.$comment&&t.$comment)_m(e);if(u5(e),n.let(k.default.vErrors,null),n.let(k.default.errors,0),i.unevaluated)l5(e);Dm(e),p5(e)});return}function l5(e){let{gen:t,validateName:i}=e;e.evaluated=t.const("evaluated",G._`${i}.evaluated`),t.if(G._`${e.evaluated}.dynamicProps`,()=>t.assign(G._`${e.evaluated}.props`,G._`undefined`)),t.if(G._`${e.evaluated}.dynamicItems`,()=>t.assign(G._`${e.evaluated}.items`,G._`undefined`))}function Xm(e,t){let i=typeof e=="object"&&e[t.schemaId];return i&&(t.code.source||t.code.process)?G._`/*# sourceURL=${i} */`:G.nil}function d5(e,t){if(zm(e)){if(jm(e),Om(e)){I5(e,t);return}}(0,Jm.boolOrEmptySchema)(e,t)}function Om({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let i in e)if(t.RULES.all[i])return!0;return!1}function zm(e){return typeof e.schema!="boolean"}function I5(e,t){let{schema:i,gen:n,opts:r}=e;if(r.$comment&&i.$comment)_m(e);C5(e),m5(e);let o=n.const("_errs",k.default.errors);Dm(e,o),n.var(t,G._`${o} === ${k.default.errors}`)}function jm(e){(0,Pt.checkUnknownRules)(e),c5(e)}function Dm(e,t){if(e.opts.jtd)return Em(e,[],!1,t);let i=(0,Sm.getSchemaTypes)(e.schema),n=(0,Sm.coerceAndCheckDataType)(e,i);Em(e,i,!n,t)}function c5(e){let{schema:t,errSchemaPath:i,opts:n,self:r}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&(0,Pt.schemaHasRulesButRef)(t,r.RULES))r.logger.warn(`$ref: keywords ignored in schema at path "${i}"`)}function u5(e){let{schema:t,opts:i}=e;if(t.default!==void 0&&i.useDefaults&&i.strictSchema)(0,Pt.checkStrictMode)(e,"default is ignored in the schema root")}function C5(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,r5.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function m5(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function _m({gen:e,schemaEnv:t,schema:i,errSchemaPath:n,opts:r}){let o=i.$comment;if(r.$comment===!0)e.code(G._`${k.default.self}.logger.log(${o})`);else if(typeof r.$comment=="function"){let s=G.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(G._`${k.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function p5(e){let{gen:t,schemaEnv:i,validateName:n,ValidationError:r,opts:o}=e;if(i.$async)t.if(G._`${k.default.errors} === 0`,()=>t.return(k.default.data),()=>t.throw(G._`new ${r}(${k.default.vErrors})`));else{if(t.assign(G._`${n}.errors`,k.default.vErrors),o.unevaluated)A5(e);t.return(G._`${k.default.errors} === 0`)}}function A5({gen:e,evaluated:t,props:i,items:n}){if(i instanceof G.Name)e.assign(G._`${t}.props`,i);if(n instanceof G.Name)e.assign(G._`${t}.items`,n)}function Em(e,t,i,n){let{gen:r,schema:o,data:s,allErrors:a,opts:g,self:l}=e,{RULES:d}=l;if(o.$ref&&(g.ignoreKeywordsWithRef||!(0,Pt.schemaHasRulesButRef)(o,d))){r.block(()=>Km(e,"$ref",d.all.$ref.definition));return}if(!g.jtd)b5(e,t);r.block(()=>{for(let C of d.rules)I(C);I(d.post)});function I(C){if(!(0,_g.shouldUseGroup)(o,C))return;if(C.type){if(r.if((0,Is.checkDataType)(C.type,s,g.strictNumbers)),Tm(e,C),t.length===1&&t[0]===C.type&&i)r.else(),(0,Is.reportTypeError)(e);r.endIf()}else Tm(e,C);if(!a)r.if(G._`${k.default.errors} === ${n||0}`)}}function Tm(e,t){let{gen:i,schema:n,opts:{useDefaults:r}}=e;if(r)(0,n5.assignDefaults)(e,t.type);i.block(()=>{for(let o of t.rules)if((0,_g.shouldUseRule)(n,o))Km(e,o.keyword,o.definition,t.type)})}function b5(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(Z5(e,t),!e.opts.allowUnionTypes)h5(e,t);f5(e,e.dataTypes)}function Z5(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((i)=>{if(!Qm(e.dataTypes,i))Qg(e,`type "${i}" not allowed by context "${e.dataTypes.join(",")}"`)}),y5(e,t)}function h5(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Qg(e,"use allowUnionTypes to allow union type keyword")}function f5(e,t){let i=e.self.RULES.all;for(let n in i){let r=i[n];if(typeof r=="object"&&(0,_g.shouldUseRule)(e.schema,r)){let{type:o}=r.definition;if(o.length&&!o.some((s)=>W5(t,s)))Qg(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function W5(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Qm(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y5(e,t){let i=[];for(let n of e.dataTypes)if(Qm(t,n))i.push(n);else if(t.includes("integer")&&n==="number")i.push("integer");e.dataTypes=i}function Qg(e,t){let i=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${i}" (strictTypes)`,(0,Pt.checkStrictMode)(e,t,e.opts.strictTypes)}class Kg{constructor(e,t,i){if((0,Rr.validateKeywordUsage)(e,t,i),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=i,this.data=e.data,this.schema=e.schema[i],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Pt.schemaRefOrVal)(e,this.schema,i,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Lm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Rr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${i} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",k.default.errors)}result(e,t,i){this.failResult((0,G.not)(e),t,i)}failResult(e,t,i){if(this.gen.if(e),i)i();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,G.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(G._`${t} !== undefined && (${(0,G.or)(this.invalid$data(),e)})`)}error(e,t,i){if(t){this.setParams(t),this._error(e,i),this.setParams({});return}this._error(e,i)}_error(e,t){(e?Br.reportExtraError:Br.reportError)(this,this.def.error,t)}$dataError(){(0,Br.reportError)(this,this.def.$dataError||Br.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Br.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,i=G.nil){this.gen.block(()=>{this.check$data(e,i),t()})}check$data(e=G.nil,t=G.nil){if(!this.$data)return;let{gen:i,schemaCode:n,schemaType:r,def:o}=this;if(i.if((0,G.or)(G._`${n} === undefined`,t)),e!==G.nil)i.assign(e,!0);if(r.length||o.validateSchema){if(i.elseIf(this.invalid$data()),this.$dataError(),e!==G.nil)i.assign(e,!1)}i.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:i,def:n,it:r}=this;return(0,G.or)(o(),s());function o(){if(i.length){if(!(t instanceof G.Name))throw Error("ajv implementation error");let a=Array.isArray(i)?i:[i];return G._`${(0,Is.checkDataTypes)(a,t,r.opts.strictNumbers,Is.DataType.Wrong)}`}return G.nil}function s(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return G._`!${a}(${t})`}return G.nil}}subschema(e,t){let i=(0,Dg.getSubschema)(this.it,e);(0,Dg.extendSubschemaData)(i,this.it,e),(0,Dg.extendSubschemaMode)(i,e);let n={...this.it,...i,items:void 0,props:void 0};return d5(n,t),n}mergeEvaluated(e,t){let{it:i,gen:n}=this;if(!i.opts.unevaluated)return;if(i.props!==!0&&e.props!==void 0)i.props=Pt.mergeEvaluated.props(n,e.props,i.props,t);if(i.items!==!0&&e.items!==void 0)i.items=Pt.mergeEvaluated.items(n,e.items,i.items,t)}mergeValidEvaluated(e,t){let{it:i,gen:n}=this;if(i.opts.unevaluated&&(i.props!==!0||i.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,G.Name)),!0}}Lt.KeywordCxt=Kg;function Km(e,t,i,n){let r=new Kg(e,i,t);if("code"in i)i.code(r,n);else if(r.$data&&i.validate)(0,Rr.funcKeywordCode)(r,i);else if("macro"in i)(0,Rr.macroKeywordCode)(r,i);else if(i.compile||i.validate)(0,Rr.funcKeywordCode)(r,i)}var V5=/^\/(?:[^~]|~0|~1)*$/,B5=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Lm(e,{dataLevel:t,dataNames:i,dataPathArr:n}){let r,o;if(e==="")return k.default.rootData;if(e[0]==="/"){if(!V5.test(e))throw Error(`Invalid JSON-pointer: ${e}`);r=e,o=k.default.rootData}else{let l=B5.exec(e);if(!l)throw Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(r=l[2],r==="#"){if(d>=t)throw Error(g("property/index",d));return n[t-d]}if(d>t)throw Error(g("data",d));if(o=i[t-d],!r)return o}let s=o,a=r.split("/");for(let l of a)if(l)o=G._`${o}${(0,G.getProperty)((0,Pt.unescapeJsonPointer)(l))}`,s=G._`${s} && ${o}`;return s;function g(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Lt.getData=Lm});var Gr=f(function(Lg){Object.defineProperty(Lg,"__esModule",{value:!0});class Mm extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Lg.default=Mm});var An=f(function($g){Object.defineProperty($g,"__esModule",{value:!0});var Mg=Vr();class $m extends Error{constructor(e,t,i,n){super(n||`can't resolve reference ${i} from id ${t}`);this.missingRef=(0,Mg.resolveUrl)(e,t,i),this.missingSchema=(0,Mg.normalizeId)((0,Mg.getFullPath)(e,this.missingRef))}}$g.default=$m});var Fr=f(function(Me){Object.defineProperty(Me,"__esModule",{value:!0});Me.resolveSchema=Me.getCompilingSchema=Me.resolveRef=Me.compileSchema=Me.SchemaEnv=void 0;var ot=N(),R5=Gr(),Wi=Ke(),st=Vr(),qm=T(),G5=pn();class wr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let i;if(typeof e.schema=="object")i=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,st.normalizeId)(i===null||i===void 0?void 0:i[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=i===null||i===void 0?void 0:i.$async,this.refs={}}}Me.SchemaEnv=wr;function el(e){let t=ep.call(this,e);if(t)return t;let i=(0,st.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:r}=this.opts.code,{ownProperties:o}=this.opts,s=new ot.CodeGen(this.scope,{es5:n,lines:r,ownProperties:o}),a;if(e.$async)a=s.scopeValue("Error",{ref:R5.default,code:ot._`require("ajv/dist/runtime/validation_error").default`});let g=s.scopeName("validate");e.validateName=g;let l={gen:s,allErrors:this.opts.allErrors,data:Wi.default.data,parentData:Wi.default.parentData,parentDataProperty:Wi.default.parentDataProperty,dataNames:[Wi.default.data],dataPathArr:[ot.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,ot.stringify)(e.schema)}:{ref:e.schema}),validateName:g,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:i,baseId:e.baseId||i,schemaPath:ot.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ot._`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,G5.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let I=s.toString();if(d=`${s.scopeRefs(Wi.default.scope)}return ${I}`,this.opts.code.process)d=this.opts.code.process(d,e);let m=Function(`${Wi.default.self}`,`${Wi.default.scope}`,d)(this,this.scope.get());if(this.scope.value(g,{ref:m}),m.errors=null,m.schema=e.schema,m.schemaEnv=e,e.$async)m.$async=!0;if(this.opts.code.source===!0)m.source={validateName:g,validateCode:I,scopeValues:s._values};if(this.opts.unevaluated){let{props:A,items:c}=l;if(m.evaluated={props:A instanceof ot.Name?void 0:A,items:c instanceof ot.Name?void 0:c,dynamicProps:A instanceof ot.Name,dynamicItems:c instanceof ot.Name},m.source)m.source.evaluated=(0,ot.stringify)(m.evaluated)}return e.validate=m,e}catch(I){if(delete e.validate,delete e.validateName,d)this.logger.error("Error compiling schema, function code:",d);throw I}finally{this._compilations.delete(e)}}Me.compileSchema=el;function w5(e,t,i){var n;i=(0,st.resolveUrl)(this.opts.uriResolver,t,i);let r=e.refs[i];if(r)return r;let o=v5.call(this,e,i);if(o===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[i],{schemaId:a}=this.opts;if(s)o=new wr({schema:s,schemaId:a,root:e,baseId:t})}if(o===void 0)return;return e.refs[i]=F5.call(this,o)}Me.resolveRef=w5;function F5(e){if((0,st.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:el.call(this,e)}function ep(e){for(let t of this._compilations)if(H5(t,e))return t}Me.getCompilingSchema=ep;function H5(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function v5(e,t){let i;while(typeof(i=this.refs[t])=="string")t=i;return i||this.schemas[t]||cs.call(this,e,t)}function cs(e,t){let i=this.opts.uriResolver.parse(t),n=(0,st._getFullPath)(this.opts.uriResolver,i),r=(0,st.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===r)return qg.call(this,i,e);let o=(0,st.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=cs.call(this,e,s);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return qg.call(this,i,a)}if(typeof(s===null||s===void 0?void 0:s.schema)!=="object")return;if(!s.validate)el.call(this,s);if(o===(0,st.normalizeId)(t)){let{schema:a}=s,{schemaId:g}=this.opts,l=a[g];if(l)r=(0,st.resolveUrl)(this.opts.uriResolver,r,l);return new wr({schema:a,schemaId:g,root:e,baseId:r})}return qg.call(this,i,s)}Me.resolveSchema=cs;var k5=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qg(e,{baseId:t,schema:i,root:n}){var r;if(((r=e.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof i==="boolean")return;let g=i[(0,qm.unescapeFragment)(a)];if(g===void 0)return;i=g;let l=typeof i==="object"&&i[this.opts.schemaId];if(!k5.has(a)&&l)t=(0,st.resolveUrl)(this.opts.uriResolver,t,l)}let o;if(typeof i!="boolean"&&i.$ref&&!(0,qm.schemaHasRulesButRef)(i,this.RULES)){let a=(0,st.resolveUrl)(this.opts.uriResolver,t,i.$ref);o=cs.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new wr({schema:i,schemaId:s,root:n,baseId:t}),o.schema!==o.root.schema)return o;return}});var tp=f(function(_j,P5){P5.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var il=f(function(Qj,op){var N5=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),np=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function tl(e){let t="",i=0,n=0;for(n=0;n<e.length;n++){if(i=e[n].charCodeAt(0),i===48)continue;if(!(i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(i=e[n].charCodeAt(0),!(i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102))return"";t+=e[n]}return t}var x5=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ip(e){return e.length=0,!0}function Y5(e,t,i){if(e.length){let n=tl(e);if(n!=="")t.push(n);else return i.error=!0,!1;e.length=0}return!0}function S5(e){let t=0,i={error:!1,address:"",zone:""},n=[],r=[],o=!1,s=!1,a=Y5;for(let g=0;g<e.length;g++){let l=e[g];if(l==="["||l==="]")continue;if(l===":"){if(o===!0)s=!0;if(!a(r,n,i))break;if(++t>7){i.error=!0;break}if(g>0&&e[g-1]===":")o=!0;n.push(":");continue}else if(l==="%"){if(!a(r,n,i))break;a=ip}else{r.push(l);continue}}if(r.length)if(a===ip)i.zone=r.join("");else if(s)n.push(r.join(""));else n.push(tl(r));return i.address=n.join(""),i}function rp(e){if(X5(e,":")<2)return{host:e,isIPV6:!1};let t=S5(e);if(!t.error){let{address:i,address:n}=t;if(t.zone)i+="%"+t.zone,n+="%25"+t.zone;return{host:i,isIPV6:!0,escapedHost:n}}else return{host:e,isIPV6:!1}}function X5(e,t){let i=0;for(let n=0;n<e.length;n++)if(e[n]===t)i++;return i}function E5(e){let t=e,i=[],n=-1,r=0;while(r=t.length){if(r===1)if(t===".")break;else if(t==="/"){i.push("/");break}else{i.push(t);break}else if(r===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){i.push("/");break}}}else if(r===3){if(t==="/.."){if(i.length!==0)i.pop();i.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),i.length!==0)i.pop();continue}}}}if((n=t.indexOf("/",1))===-1){i.push(t);break}else i.push(t.slice(0,n)),t=t.slice(n)}return i.join("")}function T5(e,t){let i=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=i(e.scheme);if(e.userinfo!==void 0)e.userinfo=i(e.userinfo);if(e.host!==void 0)e.host=i(e.host);if(e.path!==void 0)e.path=i(e.path);if(e.query!==void 0)e.query=i(e.query);if(e.fragment!==void 0)e.fragment=i(e.fragment);return e}function J5(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let i=unescape(e.host);if(!np(i)){let n=rp(i);if(n.isIPV6===!0)i=`[${n.escapedHost}]`;else i=e.host}t.push(i)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}op.exports={nonSimpleDomain:x5,recomposeAuthority:J5,normalizeComponentEncoding:T5,removeDotSegments:E5,isIPv4:np,isUUID:N5,normalizeIPv6:rp,stringArrayToHexStripped:tl}});var dp=f(function(Kj,lp){var{isUUID:U5}=il(),O5=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,z5=["http","https","ws","wss","urn","urn:uuid"];function j5(e){return z5.indexOf(e)!==-1}function nl(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function sp(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function ap(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function D5(e){return e.secure=nl(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function _5(e){if(e.port===(nl(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,i]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}function Q5(e,t){if(!e.path)return e.error="URN can not be parsed",e;let i=e.path.match(O5);if(i){let n=t.scheme||e.scheme||"urn";e.nid=i[1].toLowerCase(),e.nss=i[2];let r=`${n}:${t.nid||e.nid}`,o=rl(r);if(e.path=void 0,o)e=o.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function K5(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let i=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),r=`${i}:${t.nid||n}`,o=rl(r);if(o)e=o.serialize(e,t);let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function L5(e,t){let i=e;if(i.uuid=i.nss,i.nss=void 0,!t.tolerant&&(!i.uuid||!U5(i.uuid)))i.error=i.error||"UUID is not valid.";return i}function M5(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var gp={scheme:"http",domainHost:!0,parse:sp,serialize:ap},$5={scheme:"https",domainHost:gp.domainHost,parse:sp,serialize:ap},us={scheme:"ws",domainHost:!0,parse:D5,serialize:_5},q5={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},ev={scheme:"urn",parse:Q5,serialize:K5,skipNormalize:!0},tv={scheme:"urn:uuid",parse:L5,serialize:M5,skipNormalize:!0},Cs={http:gp,https:$5,ws:us,wss:q5,urn:ev,"urn:uuid":tv};Object.setPrototypeOf(Cs,null);function rl(e){return e&&(Cs[e]||Cs[e.toLowerCase()])||void 0}lp.exports={wsIsSecure:nl,SCHEMES:Cs,isValidSchemeName:j5,getSchemeHandler:rl}});var up=f(function(Lj,ps){var{normalizeIPv6:iv,removeDotSegments:Hr,recomposeAuthority:nv,normalizeComponentEncoding:ms,isIPv4:rv,nonSimpleDomain:ov}=il(),{SCHEMES:sv,getSchemeHandler:Ip}=dp();function av(e,t){if(typeof e==="string")e=ht(Nt(e,t),t);else if(typeof e==="object")e=Nt(ht(e,t),t);return e}function gv(e,t,i){let n=i?Object.assign({scheme:"null"},i):{scheme:"null"},r=cp(Nt(e,n),Nt(t,n),n,!0);return n.skipEscape=!0,ht(r,n)}function cp(e,t,i,n){let r={};if(!n)e=Nt(ht(e,i),i),t=Nt(ht(t,i),i);if(i=i||{},!i.tolerant&&t.scheme)r.scheme=t.scheme,r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=Hr(t.path||""),r.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=Hr(t.path||""),r.query=t.query;else{if(!t.path)if(r.path=e.path,t.query!==void 0)r.query=t.query;else r.query=e.query;else{if(t.path[0]==="/")r.path=Hr(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)r.path="/"+t.path;else if(!e.path)r.path=t.path;else r.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;r.path=Hr(r.path)}r.query=t.query}r.userinfo=e.userinfo,r.host=e.host,r.port=e.port}r.scheme=e.scheme}return r.fragment=t.fragment,r}function lv(e,t,i){if(typeof e==="string")e=unescape(e),e=ht(ms(Nt(e,i),!0),{...i,skipEscape:!0});else if(typeof e==="object")e=ht(ms(e,!0),{...i,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ht(ms(Nt(t,i),!0),{...i,skipEscape:!0});else if(typeof t==="object")t=ht(ms(t,!0),{...i,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ht(e,t){let i={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),r=[],o=Ip(n.scheme||i.scheme);if(o&&o.serialize)o.serialize(i,n);if(i.path!==void 0)if(!n.skipEscape){if(i.path=escape(i.path),i.scheme!==void 0)i.path=i.path.split("%3A").join(":")}else i.path=unescape(i.path);if(n.reference!=="suffix"&&i.scheme)r.push(i.scheme,":");let s=nv(i);if(s!==void 0){if(n.reference!=="suffix")r.push("//");if(r.push(s),i.path&&i.path[0]!=="/")r.push("/")}if(i.path!==void 0){let a=i.path;if(!n.absolutePath&&(!o||!o.absolutePath))a=Hr(a);if(s===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);r.push(a)}if(i.query!==void 0)r.push("?",i.query);if(i.fragment!==void 0)r.push("#",i.fragment);return r.join("")}var dv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nt(e,t){let i=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1;if(i.reference==="suffix")if(i.scheme)e=i.scheme+":"+e;else e="//"+e;let o=e.match(dv);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port))n.port=o[5];if(n.host)if(rv(n.host)===!1){let g=iv(n.host);n.host=g.host.toLowerCase(),r=g.isIPV6}else r=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(i.reference&&i.reference!=="suffix"&&i.reference!==n.reference)n.error=n.error||"URI is not a "+i.reference+" reference.";let s=Ip(i.scheme||n.scheme);if(!i.unicodeSupport&&(!s||!s.unicodeSupport)){if(n.host&&(i.domainHost||s&&s.domainHost)&&r===!1&&ov(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}}if(!s||s&&!s.skipNormalize){if(e.indexOf("%")!==-1){if(n.scheme!==void 0)n.scheme=unescape(n.scheme);if(n.host!==void 0)n.host=unescape(n.host)}if(n.path)n.path=escape(unescape(n.path));if(n.fragment)n.fragment=encodeURI(decodeURIComponent(n.fragment))}if(s&&s.parse)s.parse(n,i)}else n.error=n.error||"URI can not be parsed.";return n}var ol={SCHEMES:sv,normalize:av,resolve:gv,resolveComponent:cp,equal:lv,serialize:ht,parse:Nt};ps.exports=ol;ps.exports.default=ol;ps.exports.fastUri=ol});var mp=f(function(sl){Object.defineProperty(sl,"__esModule",{value:!0});var Cp=up();Cp.code='require("ajv/dist/runtime/uri").default';sl.default=Cp});var ll=f(function(me){Object.defineProperty(me,"__esModule",{value:!0});me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=void 0;var Iv=pn();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return Iv.KeywordCxt}});var bn=N();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return bn._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return bn.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return bn.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return bn.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return bn.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return bn.CodeGen}});var cv=Gr(),hp=An(),uv=Yg(),vr=Fr(),Cv=N(),kr=Vr(),As=yr(),gl=T(),pp=tp(),mv=mp(),fp=(e,t)=>new RegExp(e,t);fp.code="new RegExp";var pv=["removeAdditional","useDefaults","coerceTypes"],Av=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bv={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Zv={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ap=200;function hv(e){var t,i,n,r,o,s,a,g,l,d,I,C,m,A,c,u,p,Z,h,W,y,V,H,Y,v;let K=e.strict,re=(t=e.code)===null||t===void 0?void 0:t.optimize,le=re===!0||re===void 0?1:re||0,je=(n=(i=e.code)===null||i===void 0?void 0:i.regExp)!==null&&n!==void 0?n:fp,_n=(r=e.uriResolver)!==null&&r!==void 0?r:mv.default;return{strictSchema:(s=(o=e.strictSchema)!==null&&o!==void 0?o:K)!==null&&s!==void 0?s:!0,strictNumbers:(g=(a=e.strictNumbers)!==null&&a!==void 0?a:K)!==null&&g!==void 0?g:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:K)!==null&&d!==void 0?d:"log",strictTuples:(C=(I=e.strictTuples)!==null&&I!==void 0?I:K)!==null&&C!==void 0?C:"log",strictRequired:(A=(m=e.strictRequired)!==null&&m!==void 0?m:K)!==null&&A!==void 0?A:!1,code:e.code?{...e.code,optimize:le,regExp:je}:{optimize:le,regExp:je},loopRequired:(c=e.loopRequired)!==null&&c!==void 0?c:Ap,loopEnum:(u=e.loopEnum)!==null&&u!==void 0?u:Ap,meta:(p=e.meta)!==null&&p!==void 0?p:!0,messages:(Z=e.messages)!==null&&Z!==void 0?Z:!0,inlineRefs:(h=e.inlineRefs)!==null&&h!==void 0?h:!0,schemaId:(W=e.schemaId)!==null&&W!==void 0?W:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(V=e.validateSchema)!==null&&V!==void 0?V:!0,validateFormats:(H=e.validateFormats)!==null&&H!==void 0?H:!0,unicodeRegExp:(Y=e.unicodeRegExp)!==null&&Y!==void 0?Y:!0,int32range:(v=e.int32range)!==null&&v!==void 0?v:!0,uriResolver:_n}}class bs{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...hv(e)};let{es5:t,lines:i}=this.opts.code;this.scope=new Cv.ValueScope({scope:{},prefixes:Av,es5:t,lines:i}),this.logger=Rv(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,uv.getRules)(),bp.call(this,bv,e,"NOT SUPPORTED"),bp.call(this,Zv,e,"DEPRECATED","warn"),this._metaOpts=Vv.call(this),e.formats)Wv.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)yv.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);fv.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:i}=this.opts,n=pp;if(i==="id")n={...pp},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[i],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let i;if(typeof e=="string"){if(i=this.getSchema(e),!i)throw Error(`no schema with key or ref "${e}"`)}else i=this.compile(e);let n=i(t);if(!("$async"in i))this.errors=i.errors;return n}compile(e,t){let i=this._addSchema(e,t);return i.validate||this._compileSchemaEnv(i)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:i}=this.opts;return n.call(this,e,t);async function n(l,d){await r.call(this,l.$schema);let I=this._addSchema(l,d);return I.validate||o.call(this,I)}async function r(l){if(l&&!this.getSchema(l))await n.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof hp.default))throw d;return s.call(this,d),await a.call(this,d.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:d}){if(this.refs[l])throw Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function a(l){let d=await g.call(this,l);if(!this.refs[l])await r.call(this,d.$schema);if(!this.refs[l])this.addSchema(d,l,t)}async function g(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=i(l))}finally{delete this._loading[l]}}}addSchema(e,t,i,n=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,i,n);return this}let r;if(typeof e==="object"){let{schemaId:o}=this.opts;if(r=e[o],r!==void 0&&typeof r!="string")throw Error(`schema ${o} must be string`)}return t=(0,kr.normalizeId)(t||r),this._checkUnique(t),this.schemas[t]=this._addSchema(e,i,t,n,!0),this}addMetaSchema(e,t,i=this.opts.validateSchema){return this.addSchema(e,t,!0,i),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let i;if(i=e.$schema,i!==void 0&&typeof i!="string")throw Error("$schema must be a string");if(i=i||this.opts.defaultMeta||this.defaultMeta(),!i)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(i,e);if(!n&&t){let r="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(r);else throw Error(r)}return n}getSchema(e){let t;while(typeof(t=Zp.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:i}=this.opts,n=new vr.SchemaEnv({schema:{},schemaId:i});if(t=vr.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Zp.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let i=e[this.opts.schemaId];if(i)i=(0,kr.normalizeId)(i),delete this.schemas[i],delete this.refs[i];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let i;if(typeof e=="string"){if(i=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=i}else if(typeof e=="object"&&t===void 0){if(t=e,i=t.keyword,Array.isArray(i)&&!i.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(wv.call(this,i,t),!t)return(0,gl.eachItem)(i,(r)=>al.call(this,r)),this;Hv.call(this,t);let n={...t,type:(0,As.getJSONTypes)(t.type),schemaType:(0,As.getJSONTypes)(t.schemaType)};return(0,gl.eachItem)(i,n.type.length===0?(r)=>al.call(this,r,n):(r)=>n.type.forEach((o)=>al.call(this,r,n,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let i of t.rules){let n=i.rules.findIndex((r)=>r.keyword===e);if(n>=0)i.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:i="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${i}${n.instancePath} ${n.message}`).reduce((n,r)=>n+t+r)}$dataMetaSchema(e,t){let i=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let r=n.split("/").slice(1),o=e;for(let s of r)o=o[s];for(let s in i){let a=i[s];if(typeof a!="object")continue;let{$data:g}=a.definition,l=o[s];if(g&&l)o[s]=Wp(l)}}return e}_removeAllSchemas(e,t){for(let i in e){let n=e[i];if(!t||t.test(i)){if(typeof n=="string")delete e[i];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[i]}}}_addSchema(e,t,i,n=this.opts.validateSchema,r=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof e=="object")o=e[s];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;i=(0,kr.normalizeId)(o||i);let g=kr.getSchemaRefs.call(this,e,i);if(a=new vr.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:i,localRefs:g}),this._cache.set(a.schema,a),r&&!i.startsWith("#")){if(i)this._checkUnique(i);this.refs[i]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else vr.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{vr.compileSchema.call(this,e)}finally{this.opts=t}}}bs.ValidationError=cv.default;bs.MissingRefError=hp.default;me.default=bs;function bp(e,t,i,n="error"){for(let r in e){let o=r;if(o in t)this.logger[n](`${i}: option ${r}. ${e[o]}`)}}function Zp(e){return e=(0,kr.normalizeId)(e),this.schemas[e]||this.refs[e]}function fv(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Wv(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function yv(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let i=e[t];if(!i.keyword)i.keyword=t;this.addKeyword(i)}}function Vv(){let e={...this.opts};for(let t of pv)delete e[t];return e}var Bv={log(){},warn(){},error(){}};function Rv(e){if(e===!1)return Bv;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var Gv=/^[a-z_$][a-z0-9_$:-]*$/i;function wv(e,t){let{RULES:i}=this;if((0,gl.eachItem)(e,(n)=>{if(i.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!Gv.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function al(e,t,i){var n;let r=t===null||t===void 0?void 0:t.post;if(i&&r)throw Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=r?o.post:o.rules.find(({type:g})=>g===i);if(!s)s={type:i,rules:[]},o.rules.push(s);if(o.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,As.getJSONTypes)(t.type),schemaType:(0,As.getJSONTypes)(t.schemaType)}};if(t.before)Fv.call(this,s,a,t.before);else s.rules.push(a);o.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((g)=>this.addKeyword(g))}function Fv(e,t,i){let n=e.rules.findIndex((r)=>r.keyword===i);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${i} is not defined`)}function Hv(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Wp(t);e.validateSchema=this.compile(t,!0)}var vv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Wp(e){return{anyOf:[e,vv]}}});var yp=f(function(dl){Object.defineProperty(dl,"__esModule",{value:!0});var kv={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};dl.default=kv});var fs=f(function(yi){Object.defineProperty(yi,"__esModule",{value:!0});yi.callRef=yi.getValidate=void 0;var Pv=An(),Vp=Le(),Xe=N(),Zn=Ke(),Bp=Fr(),Zs=T(),Nv={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:i,it:n}=e,{baseId:r,schemaEnv:o,validateName:s,opts:a,self:g}=n,{root:l}=o;if((i==="#"||i==="#/")&&r===l.baseId)return I();let d=Bp.resolveRef.call(g,l,r,i);if(d===void 0)throw new Pv.default(n.opts.uriResolver,r,i);if(d instanceof Bp.SchemaEnv)return C(d);return m(d);function I(){if(o===l)return hs(e,s,o,o.$async);let A=t.scopeValue("root",{ref:l});return hs(e,Xe._`${A}.validate`,l,l.$async)}function C(A){let c=Rp(e,A);hs(e,c,A,A.$async)}function m(A){let c=t.scopeValue("schema",a.code.source===!0?{ref:A,code:(0,Xe.stringify)(A)}:{ref:A}),u=t.name("valid"),p=e.subschema({schema:A,dataTypes:[],schemaPath:Xe.nil,topSchemaRef:c,errSchemaPath:i},u);e.mergeEvaluated(p),e.ok(u)}}};function Rp(e,t){let{gen:i}=e;return t.validate?i.scopeValue("validate",{ref:t.validate}):Xe._`${i.scopeValue("wrapper",{ref:t})}.validate`}yi.getValidate=Rp;function hs(e,t,i,n){let{gen:r,it:o}=e,{allErrors:s,schemaEnv:a,opts:g}=o,l=g.passContext?Zn.default.this:Xe.nil;if(n)d();else I();function d(){if(!a.$async)throw Error("async schema referenced by sync schema");let A=r.let("valid");r.try(()=>{if(r.code(Xe._`await ${(0,Vp.callValidateCode)(e,t,l)}`),m(t),!s)r.assign(A,!0)},(c)=>{if(r.if(Xe._`!(${c} instanceof ${o.ValidationError})`,()=>r.throw(c)),C(c),!s)r.assign(A,!1)}),e.ok(A)}function I(){e.result((0,Vp.callValidateCode)(e,t,l),()=>m(t),()=>C(t))}function C(A){let c=Xe._`${A}.errors`;r.assign(Zn.default.vErrors,Xe._`${Zn.default.vErrors} === null ? ${c} : ${Zn.default.vErrors}.concat(${c})`),r.assign(Zn.default.errors,Xe._`${Zn.default.vErrors}.length`)}function m(A){var c;if(!o.opts.unevaluated)return;let u=(c=i===null||i===void 0?void 0:i.validate)===null||c===void 0?void 0:c.evaluated;if(o.props!==!0)if(u&&!u.dynamicProps){if(u.props!==void 0)o.props=Zs.mergeEvaluated.props(r,u.props,o.props)}else{let p=r.var("props",Xe._`${A}.evaluated.props`);o.props=Zs.mergeEvaluated.props(r,p,o.props,Xe.Name)}if(o.items!==!0)if(u&&!u.dynamicItems){if(u.items!==void 0)o.items=Zs.mergeEvaluated.items(r,u.items,o.items)}else{let p=r.var("items",Xe._`${A}.evaluated.items`);o.items=Zs.mergeEvaluated.items(r,p,o.items,Xe.Name)}}}yi.callRef=hs;yi.default=Nv});var cl=f(function(Il){Object.defineProperty(Il,"__esModule",{value:!0});var xv=yp(),Yv=fs(),Sv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xv.default,Yv.default];Il.default=Sv});var Gp=f(function(ul){Object.defineProperty(ul,"__esModule",{value:!0});var Ws=N(),Mt=Ws.operators,ys={maximum:{okStr:"<=",ok:Mt.LTE,fail:Mt.GT},minimum:{okStr:">=",ok:Mt.GTE,fail:Mt.LT},exclusiveMaximum:{okStr:"<",ok:Mt.LT,fail:Mt.GTE},exclusiveMinimum:{okStr:">",ok:Mt.GT,fail:Mt.LTE}},Xv={message:({keyword:e,schemaCode:t})=>Ws.str`must be ${ys[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ws._`{comparison: ${ys[e].okStr}, limit: ${t}}`},Ev={keyword:Object.keys(ys),type:"number",schemaType:"number",$data:!0,error:Xv,code(e){let{keyword:t,data:i,schemaCode:n}=e;e.fail$data(Ws._`${i} ${ys[t].fail} ${n} || isNaN(${i})`)}};ul.default=Ev});var wp=f(function(Cl){Object.defineProperty(Cl,"__esModule",{value:!0});var Pr=N(),Tv={message:({schemaCode:e})=>Pr.str`must be multiple of ${e}`,params:({schemaCode:e})=>Pr._`{multipleOf: ${e}}`},Jv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Tv,code(e){let{gen:t,data:i,schemaCode:n,it:r}=e,o=r.opts.multipleOfPrecision,s=t.let("res"),a=o?Pr._`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:Pr._`${s} !== parseInt(${s})`;e.fail$data(Pr._`(${n} === 0 || (${s} = ${i}/${n}, ${a}))`)}};Cl.default=Jv});var Hp=f(function(ml){Object.defineProperty(ml,"__esModule",{value:!0});function Fp(e){let t=e.length,i=0,n=0,r;while(n<t)if(i++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t){if(r=e.charCodeAt(n),(r&64512)===56320)n++}return i}ml.default=Fp;Fp.code='require("ajv/dist/runtime/ucs2length").default'});var vp=f(function(pl){Object.defineProperty(pl,"__esModule",{value:!0});var Vi=N(),Uv=T(),Ov=Hp(),zv={message({keyword:e,schemaCode:t}){let i=e==="maxLength"?"more":"fewer";return Vi.str`must NOT have ${i} than ${t} characters`},params:({schemaCode:e})=>Vi._`{limit: ${e}}`},jv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:zv,code(e){let{keyword:t,data:i,schemaCode:n,it:r}=e,o=t==="maxLength"?Vi.operators.GT:Vi.operators.LT,s=r.opts.unicode===!1?Vi._`${i}.length`:Vi._`${(0,Uv.useFunc)(e.gen,Ov.default)}(${i})`;e.fail$data(Vi._`${s} ${o} ${n}`)}};pl.default=jv});var kp=f(function(Al){Object.defineProperty(Al,"__esModule",{value:!0});var Dv=Le(),Vs=N(),_v={message:({schemaCode:e})=>Vs.str`must match pattern "${e}"`,params:({schemaCode:e})=>Vs._`{pattern: ${e}}`},Qv={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_v,code(e){let{data:t,$data:i,schema:n,schemaCode:r,it:o}=e,s=o.opts.unicodeRegExp?"u":"",a=i?Vs._`(new RegExp(${r}, ${s}))`:(0,Dv.usePattern)(e,n);e.fail$data(Vs._`!${a}.test(${t})`)}};Al.default=Qv});var Pp=f(function(bl){Object.defineProperty(bl,"__esModule",{value:!0});var Nr=N(),Kv={message({keyword:e,schemaCode:t}){let i=e==="maxProperties"?"more":"fewer";return Nr.str`must NOT have ${i} than ${t} properties`},params:({schemaCode:e})=>Nr._`{limit: ${e}}`},Lv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Kv,code(e){let{keyword:t,data:i,schemaCode:n}=e,r=t==="maxProperties"?Nr.operators.GT:Nr.operators.LT;e.fail$data(Nr._`Object.keys(${i}).length ${r} ${n}`)}};bl.default=Lv});var Np=f(function(Zl){Object.defineProperty(Zl,"__esModule",{value:!0});var xr=Le(),Yr=N(),Mv=T(),$v={message:({params:{missingProperty:e}})=>Yr.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Yr._`{missingProperty: ${e}}`},qv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:$v,code(e){let{gen:t,schema:i,schemaCode:n,data:r,$data:o,it:s}=e,{opts:a}=s;if(!o&&i.length===0)return;let g=i.length>=a.loopRequired;if(s.allErrors)l();else d();if(a.strictRequired){let m=e.parentSchema.properties,{definedProperties:A}=e.it;for(let c of i)if((m===null||m===void 0?void 0:m[c])===void 0&&!A.has(c)){let u=s.schemaEnv.baseId+s.errSchemaPath,p=`required property "${c}" is not defined at "${u}" (strictRequired)`;(0,Mv.checkStrictMode)(s,p,s.opts.strictRequired)}}function l(){if(g||o)e.block$data(Yr.nil,I);else for(let m of i)(0,xr.checkReportMissingProp)(e,m)}function d(){let m=t.let("missing");if(g||o){let A=t.let("valid",!0);e.block$data(A,()=>C(m,A)),e.ok(A)}else t.if((0,xr.checkMissingProp)(e,i,m)),(0,xr.reportMissingProp)(e,m),t.else()}function I(){t.forOf("prop",n,(m)=>{e.setParams({missingProperty:m}),t.if((0,xr.noPropertyInData)(t,r,m,a.ownProperties),()=>e.error())})}function C(m,A){e.setParams({missingProperty:m}),t.forOf(m,n,()=>{t.assign(A,(0,xr.propertyInData)(t,r,m,a.ownProperties)),t.if((0,Yr.not)(A),()=>{e.error(),t.break()})},Yr.nil)}}};Zl.default=qv});var xp=f(function(hl){Object.defineProperty(hl,"__esModule",{value:!0});var Sr=N(),ek={message({keyword:e,schemaCode:t}){let i=e==="maxItems"?"more":"fewer";return Sr.str`must NOT have ${i} than ${t} items`},params:({schemaCode:e})=>Sr._`{limit: ${e}}`},tk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ek,code(e){let{keyword:t,data:i,schemaCode:n}=e,r=t==="maxItems"?Sr.operators.GT:Sr.operators.LT;e.fail$data(Sr._`${i}.length ${r} ${n}`)}};hl.default=tk});var Bs=f(function(fl){Object.defineProperty(fl,"__esModule",{value:!0});var Yp=zg();Yp.code='require("ajv/dist/runtime/equal").default';fl.default=Yp});var Sp=f(function(yl){Object.defineProperty(yl,"__esModule",{value:!0});var Wl=yr(),pe=N(),ik=T(),nk=Bs(),rk={message:({params:{i:e,j:t}})=>pe.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>pe._`{i: ${e}, j: ${t}}`},ok={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rk,code(e){let{gen:t,data:i,$data:n,schema:r,parentSchema:o,schemaCode:s,it:a}=e;if(!n&&!r)return;let g=t.let("valid"),l=o.items?(0,Wl.getSchemaTypes)(o.items):[];e.block$data(g,d,pe._`${s} === false`),e.ok(g);function d(){let A=t.let("i",pe._`${i}.length`),c=t.let("j");e.setParams({i:A,j:c}),t.assign(g,!0),t.if(pe._`${A} > 1`,()=>(I()?C:m)(A,c))}function I(){return l.length>0&&!l.some((A)=>A==="object"||A==="array")}function C(A,c){let u=t.name("item"),p=(0,Wl.checkDataTypes)(l,u,a.opts.strictNumbers,Wl.DataType.Wrong),Z=t.const("indices",pe._`{}`);t.for(pe._`;${A}--;`,()=>{if(t.let(u,pe._`${i}[${A}]`),t.if(p,pe._`continue`),l.length>1)t.if(pe._`typeof ${u} == "string"`,pe._`${u} += "_"`);t.if(pe._`typeof ${Z}[${u}] == "number"`,()=>{t.assign(c,pe._`${Z}[${u}]`),e.error(),t.assign(g,!1).break()}).code(pe._`${Z}[${u}] = ${A}`)})}function m(A,c){let u=(0,ik.useFunc)(t,nk.default),p=t.name("outer");t.label(p).for(pe._`;${A}--;`,()=>t.for(pe._`${c} = ${A}; ${c}--;`,()=>t.if(pe._`${u}(${i}[${A}], ${i}[${c}])`,()=>{e.error(),t.assign(g,!1).break(p)})))}}};yl.default=ok});var Xp=f(function(Bl){Object.defineProperty(Bl,"__esModule",{value:!0});var Vl=N(),sk=T(),ak=Bs(),gk={message:"must be equal to constant",params:({schemaCode:e})=>Vl._`{allowedValue: ${e}}`},lk={keyword:"const",$data:!0,error:gk,code(e){let{gen:t,data:i,$data:n,schemaCode:r,schema:o}=e;if(n||o&&typeof o=="object")e.fail$data(Vl._`!${(0,sk.useFunc)(t,ak.default)}(${i}, ${r})`);else e.fail(Vl._`${o} !== ${i}`)}};Bl.default=lk});var Ep=f(function(Rl){Object.defineProperty(Rl,"__esModule",{value:!0});var Xr=N(),dk=T(),Ik=Bs(),ck={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Xr._`{allowedValues: ${e}}`},uk={keyword:"enum",schemaType:"array",$data:!0,error:ck,code(e){let{gen:t,data:i,$data:n,schema:r,schemaCode:o,it:s}=e;if(!n&&r.length===0)throw Error("enum must have non-empty array");let a=r.length>=s.opts.loopEnum,g,l=()=>g!==null&&g!==void 0?g:g=(0,dk.useFunc)(t,Ik.default),d;if(a||n)d=t.let("valid"),e.block$data(d,I);else{if(!Array.isArray(r))throw Error("ajv implementation error");let m=t.const("vSchema",o);d=(0,Xr.or)(...r.map((A,c)=>C(m,c)))}e.pass(d);function I(){t.assign(d,!1),t.forOf("v",o,(m)=>t.if(Xr._`${l()}(${i}, ${m})`,()=>t.assign(d,!0).break()))}function C(m,A){let c=r[A];return typeof c==="object"&&c!==null?Xr._`${l()}(${i}, ${m}[${A}])`:Xr._`${i} === ${c}`}}};Rl.default=uk});var wl=f(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var Ck=Gp(),mk=wp(),pk=vp(),Ak=kp(),bk=Pp(),Zk=Np(),hk=xp(),fk=Sp(),Wk=Xp(),yk=Ep(),Vk=[Ck.default,mk.default,pk.default,Ak.default,bk.default,Zk.default,hk.default,fk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Wk.default,yk.default];Gl.default=Vk});var Hl=f(function(Er){Object.defineProperty(Er,"__esModule",{value:!0});Er.validateAdditionalItems=void 0;var Bi=N(),Fl=T(),Bk={message:({params:{len:e}})=>Bi.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Bi._`{limit: ${e}}`},Rk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Bk,code(e){let{parentSchema:t,it:i}=e,{items:n}=t;if(!Array.isArray(n)){(0,Fl.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}Tp(e,n)}};function Tp(e,t){let{gen:i,schema:n,data:r,keyword:o,it:s}=e;s.items=!0;let a=i.const("len",Bi._`${r}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(Bi._`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Fl.alwaysValidSchema)(s,n)){let l=i.var("valid",Bi._`${a} <= ${t.length}`);i.if((0,Bi.not)(l),()=>g(l)),e.ok(l)}function g(l){i.forRange("i",t.length,a,(d)=>{if(e.subschema({keyword:o,dataProp:d,dataPropType:Fl.Type.Num},l),!s.allErrors)i.if((0,Bi.not)(l),()=>i.break())})}}Er.validateAdditionalItems=Tp;Er.default=Rk});var vl=f(function(Tr){Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateTuple=void 0;var Jp=N(),Rs=T(),Gk=Le(),wk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return Up(e,"additionalItems",t);if(i.items=!0,(0,Rs.alwaysValidSchema)(i,t))return;e.ok((0,Gk.validateArray)(e))}};function Up(e,t,i=e.schema){let{gen:n,parentSchema:r,data:o,keyword:s,it:a}=e;if(d(r),a.opts.unevaluated&&i.length&&a.items!==!0)a.items=Rs.mergeEvaluated.items(n,i.length,a.items);let g=n.name("valid"),l=n.const("len",Jp._`${o}.length`);i.forEach((I,C)=>{if((0,Rs.alwaysValidSchema)(a,I))return;n.if(Jp._`${l} > ${C}`,()=>e.subschema({keyword:s,schemaProp:C,dataProp:C},g)),e.ok(g)});function d(I){let{opts:C,errSchemaPath:m}=a,A=i.length,c=A===I.minItems&&(A===I.maxItems||I[t]===!1);if(C.strictTuples&&!c){let u=`"${s}" is ${A}-tuple, but minItems or maxItems/${t} are not specified or different at path "${m}"`;(0,Rs.checkStrictMode)(a,u,C.strictTuples)}}}Tr.validateTuple=Up;Tr.default=wk});var Op=f(function(kl){Object.defineProperty(kl,"__esModule",{value:!0});var Fk=vl(),Hk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,Fk.validateTuple)(e,"items")};kl.default=Hk});var jp=f(function(Pl){Object.defineProperty(Pl,"__esModule",{value:!0});var zp=N(),vk=T(),kk=Le(),Pk=Hl(),Nk={message:({params:{len:e}})=>zp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>zp._`{limit: ${e}}`},xk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Nk,code(e){let{schema:t,parentSchema:i,it:n}=e,{prefixItems:r}=i;if(n.items=!0,(0,vk.alwaysValidSchema)(n,t))return;if(r)(0,Pk.validateAdditionalItems)(e,r);else e.ok((0,kk.validateArray)(e))}};Pl.default=xk});var Dp=f(function(Nl){Object.defineProperty(Nl,"__esModule",{value:!0});var $e=N(),Gs=T(),Yk={message:({params:{min:e,max:t}})=>t===void 0?$e.str`must contain at least ${e} valid item(s)`:$e.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?$e._`{minContains: ${e}}`:$e._`{minContains: ${e}, maxContains: ${t}}`},Sk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Yk,code(e){let{gen:t,schema:i,parentSchema:n,data:r,it:o}=e,s,a,{minContains:g,maxContains:l}=n;if(o.opts.next)s=g===void 0?1:g,a=l;else s=1;let d=t.const("len",$e._`${r}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Gs.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Gs.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Gs.alwaysValidSchema)(o,i)){let c=$e._`${d} >= ${s}`;if(a!==void 0)c=$e._`${c} && ${d} <= ${a}`;e.pass(c);return}o.items=!0;let I=t.name("valid");if(a===void 0&&s===1)m(I,()=>t.if(I,()=>t.break()));else if(s===0){if(t.let(I,!0),a!==void 0)t.if($e._`${r}.length > 0`,C)}else t.let(I,!1),C();e.result(I,()=>e.reset());function C(){let c=t.name("_valid"),u=t.let("count",0);m(c,()=>t.if(c,()=>A(u)))}function m(c,u){t.forRange("i",0,d,(p)=>{e.subschema({keyword:"contains",dataProp:p,dataPropType:Gs.Type.Num,compositeRule:!0},c),u()})}function A(c){if(t.code($e._`${c}++`),a===void 0)t.if($e._`${c} >= ${s}`,()=>t.assign(I,!0).break());else if(t.if($e._`${c} > ${a}`,()=>t.assign(I,!1).break()),s===1)t.assign(I,!0);else t.if($e._`${c} >= ${s}`,()=>t.assign(I,!0))}}};Nl.default=Sk});var ws=f(function(ft){Object.defineProperty(ft,"__esModule",{value:!0});ft.validateSchemaDeps=ft.validatePropertyDeps=ft.error=void 0;var xl=N(),Xk=T(),Jr=Le();ft.error={message:({params:{property:e,depsCount:t,deps:i}})=>{let n=t===1?"property":"properties";return xl.str`must have ${n} ${i} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:i,missingProperty:n}})=>xl._`{property: ${e},
|
|
8
8
|
missingProperty: ${n},
|
|
9
9
|
depsCount: ${t},
|
|
10
|
-
deps: ${i}}`};var Ek={keyword:"dependencies",type:"object",schemaType:"object",error:ft.error,code(e){let[t,i]=Tk(e);_p(e,t),Qp(e,i)}};function Tk({schema:e}){let t={},i={};for(let n in e){if(n==="__proto__")continue;let r=Array.isArray(e[n])?t:i;r[n]=e[n]}return[t,i]}function _p(e,t=e.schema){let{gen:i,data:n,it:r}=e;if(Object.keys(t).length===0)return;let o=i.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let g=(0,Jr.propertyInData)(i,n,s,r.opts.ownProperties);if(e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),r.allErrors)i.if(g,()=>{for(let l of a)(0,Jr.checkReportMissingProp)(e,l)});else i.if(xl._`${g} && (${(0,Jr.checkMissingProp)(e,a,o)})`),(0,Jr.reportMissingProp)(e,o),i.else()}}ft.validatePropertyDeps=_p;function Qp(e,t=e.schema){let{gen:i,data:n,keyword:r,it:o}=e,s=i.name("valid");for(let a in t){if((0,Xk.alwaysValidSchema)(o,t[a]))continue;i.if((0,Jr.propertyInData)(i,n,a,o.opts.ownProperties),()=>{let g=e.subschema({keyword:r,schemaProp:a},s);e.mergeValidEvaluated(g,s)},()=>i.var(s,!0)),e.ok(s)}}ft.validateSchemaDeps=Qp;ft.default=Ek});var Lp=f(function(Yl){Object.defineProperty(Yl,"__esModule",{value:!0});var Kp=N(),Jk=T(),Uk={message:"property name must be valid",params:({params:e})=>Kp._`{propertyName: ${e.propertyName}}`},Ok={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Uk,code(e){let{gen:t,schema:i,data:n,it:r}=e;if((0,Jk.alwaysValidSchema)(r,i))return;let o=t.name("valid");t.forIn("key",n,(s)=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,Kp.not)(o),()=>{if(e.error(!0),!r.allErrors)t.break()})}),e.ok(o)}};Yl.default=Ok});var Xl=f(function(Sl){Object.defineProperty(Sl,"__esModule",{value:!0});var Fs=Le(),at=N(),zk=Ke(),Hs=T(),jk={message:"must NOT have additional properties",params:({params:e})=>at._`{additionalProperty: ${e.additionalProperty}}`},Dk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jk,code(e){let{gen:t,schema:i,parentSchema:n,data:r,errsCount:o,it:s}=e;if(!o)throw Error("ajv implementation error");let{allErrors:a,opts:g}=s;if(s.props=!0,g.removeAdditional!=="all"&&(0,Hs.alwaysValidSchema)(s,i))return;let l=(0,Fs.allSchemaProperties)(n.properties),d=(0,Fs.allSchemaProperties)(n.patternProperties);I(),e.ok(at._`${o} === ${zk.default.errors}`);function I(){t.forIn("key",r,(u)=>{if(!l.length&&!d.length)A(u);else t.if(C(u),()=>A(u))})}function C(u){let p;if(l.length>8){let Z=(0,Hs.schemaRefOrVal)(s,n.properties,"properties");p=(0,Fs.isOwnProperty)(t,Z,u)}else if(l.length)p=(0,at.or)(...l.map((Z)=>at._`${u} === ${Z}`));else p=at.nil;if(d.length)p=(0,at.or)(p,...d.map((Z)=>at._`${(0,Fs.usePattern)(e,Z)}.test(${u})`));return(0,at.not)(p)}function m(u){t.code(at._`delete ${r}[${u}]`)}function A(u){if(g.removeAdditional==="all"||g.removeAdditional&&i===!1){m(u);return}if(i===!1){if(e.setParams({additionalProperty:u}),e.error(),!a)t.break();return}if(typeof i=="object"&&!(0,Hs.alwaysValidSchema)(s,i)){let p=t.name("valid");if(g.removeAdditional==="failing")c(u,p,!1),t.if((0,at.not)(p),()=>{e.reset(),m(u)});else if(c(u,p),!a)t.if((0,at.not)(p),()=>t.break())}}function c(u,p,Z){let h={keyword:"additionalProperties",dataProp:u,dataPropType:Hs.Type.Str};if(Z===!1)Object.assign(h,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(h,p)}}};Sl.default=Dk});var qp=f(function(Tl){Object.defineProperty(Tl,"__esModule",{value:!0});var _k=pn(),Mp=Le(),El=T(),$p=Xl(),Qk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:i,parentSchema:n,data:r,it:o}=e;if(o.opts.removeAdditional==="all"&&n.additionalProperties===void 0)$p.default.code(new _k.KeywordCxt(o,$p.default,"additionalProperties"));let s=(0,Mp.allSchemaProperties)(i);for(let I of s)o.definedProperties.add(I);if(o.opts.unevaluated&&s.length&&o.props!==!0)o.props=El.mergeEvaluated.props(t,(0,El.toHash)(s),o.props);let a=s.filter((I)=>!(0,El.alwaysValidSchema)(o,i[I]));if(a.length===0)return;let g=t.name("valid");for(let I of a){if(l(I))d(I);else{if(t.if((0,Mp.propertyInData)(t,r,I,o.opts.ownProperties)),d(I),!o.allErrors)t.else().var(g,!0);t.endIf()}e.it.definedProperties.add(I),e.ok(g)}function l(I){return o.opts.useDefaults&&!o.compositeRule&&i[I].default!==void 0}function d(I){e.subschema({keyword:"properties",schemaProp:I,dataProp:I},g)}}};Tl.default=Qk});var nA=f(function(Jl){Object.defineProperty(Jl,"__esModule",{value:!0});var eA=Le(),vs=N(),tA=T(),iA=T(),Kk={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:i,data:n,parentSchema:r,it:o}=e,{opts:s}=o,a=(0,eA.allSchemaProperties)(i),g=a.filter((c)=>(0,tA.alwaysValidSchema)(o,i[c]));if(a.length===0||g.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&r.properties,d=t.name("valid");if(o.props!==!0&&!(o.props instanceof vs.Name))o.props=(0,iA.evaluatedPropsToName)(t,o.props);let{props:I}=o;C();function C(){for(let c of a){if(l)m(c);if(o.allErrors)A(c);else t.var(d,!0),A(c),t.if(d)}}function m(c){for(let u in l)if(new RegExp(c).test(u))(0,tA.checkStrictMode)(o,`property ${u} matches pattern ${c} (use allowMatchingProperties)`)}function A(c){t.forIn("key",n,(u)=>{t.if(vs._`${(0,eA.usePattern)(e,c)}.test(${u})`,()=>{let p=g.includes(c);if(!p)e.subschema({keyword:"patternProperties",schemaProp:c,dataProp:u,dataPropType:iA.Type.Str},d);if(o.opts.unevaluated&&I!==!0)t.assign(vs._`${I}[${u}]`,!0);else if(!p&&!o.allErrors)t.if((0,vs.not)(d),()=>t.break())})})}}};Jl.default=Kk});var rA=f(function(Ul){Object.defineProperty(Ul,"__esModule",{value:!0});var Lk=T(),Mk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:i,it:n}=e;if((0,Lk.alwaysValidSchema)(n,i)){e.fail();return}let r=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),e.failResult(r,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ul.default=Mk});var oA=f(function(Ol){Object.defineProperty(Ol,"__esModule",{value:!0});var $k=Le(),qk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$k.validateUnion,error:{message:"must match a schema in anyOf"}};Ol.default=qk});var sA=f(function(zl){Object.defineProperty(zl,"__esModule",{value:!0});var ks=N(),e1=T(),t1={message:"must match exactly one schema in oneOf",params:({params:e})=>ks._`{passingSchemas: ${e.passing}}`},i1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:t1,code(e){let{gen:t,schema:i,parentSchema:n,it:r}=e;if(!Array.isArray(i))throw Error("ajv implementation error");if(r.opts.discriminator&&n.discriminator)return;let o=i,s=t.let("valid",!1),a=t.let("passing",null),g=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((d,I)=>{let C;if((0,e1.alwaysValidSchema)(r,d))t.var(g,!0);else C=e.subschema({keyword:"oneOf",schemaProp:I,compositeRule:!0},g);if(I>0)t.if(ks._`${g} && ${s}`).assign(s,!1).assign(a,ks._`[${a}, ${I}]`).else();t.if(g,()=>{if(t.assign(s,!0),t.assign(a,I),C)e.mergeEvaluated(C,ks.Name)})})}}};zl.default=i1});var aA=f(function(jl){Object.defineProperty(jl,"__esModule",{value:!0});var n1=T(),r1={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:i,it:n}=e;if(!Array.isArray(i))throw Error("ajv implementation error");let r=t.name("valid");i.forEach((o,s)=>{if((0,n1.alwaysValidSchema)(n,o))return;let a=e.subschema({keyword:"allOf",schemaProp:s},r);e.ok(r),e.mergeEvaluated(a)})}};jl.default=r1});var dA=f(function(Dl){Object.defineProperty(Dl,"__esModule",{value:!0});var Ps=N(),lA=T(),o1={message:({params:e})=>Ps.str`must match "${e.ifClause}" schema`,params:({params:e})=>Ps._`{failingKeyword: ${e.ifClause}}`},s1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:o1,code(e){let{gen:t,parentSchema:i,it:n}=e;if(i.then===void 0&&i.else===void 0)(0,lA.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let r=gA(n,"then"),o=gA(n,"else");if(!r&&!o)return;let s=t.let("valid",!0),a=t.name("_valid");if(g(),e.reset(),r&&o){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else if(r)t.if(a,l("then"));else t.if((0,Ps.not)(a),l("else"));e.pass(s,()=>e.error(!0));function g(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,I){return()=>{let C=e.subschema({keyword:d},a);if(t.assign(s,a),e.mergeValidEvaluated(C,s),I)t.assign(I,Ps._`${d}`);else e.setParams({ifClause:d})}}}};function gA(e,t){let i=e.schema[t];return i!==void 0&&!(0,lA.alwaysValidSchema)(e,i)}Dl.default=s1});var IA=f(function(_l){Object.defineProperty(_l,"__esModule",{value:!0});var a1=T(),g1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:i}){if(t.if===void 0)(0,a1.checkStrictMode)(i,`"${e}" without "if" is ignored`)}};_l.default=g1});var Kl=f(function(Ql){Object.defineProperty(Ql,"__esModule",{value:!0});var l1=Hl(),d1=Op(),I1=vl(),c1=jp(),u1=Dp(),C1=ws(),m1=Lp(),p1=Xl(),A1=qp(),b1=nA(),Z1=rA(),h1=oA(),f1=sA(),W1=aA(),y1=dA(),V1=IA();function B1(e=!1){let t=[Z1.default,h1.default,f1.default,W1.default,y1.default,V1.default,m1.default,p1.default,C1.default,A1.default,b1.default];if(e)t.push(d1.default,c1.default);else t.push(l1.default,I1.default);return t.push(u1.default),t}Ql.default=B1});var Ml=f(function(Ur){Object.defineProperty(Ur,"__esModule",{value:!0});Ur.dynamicAnchor=void 0;var Ll=N(),R1=Ke(),cA=Fr(),G1=fs(),w1={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>uA(e,e.schema)};function uA(e,t){let{gen:i,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let r=Ll._`${R1.default.dynamicAnchors}${(0,Ll.getProperty)(t)}`,o=n.errSchemaPath==="#"?n.validateName:F1(e);i.if(Ll._`!${r}`,()=>i.assign(r,o))}Ur.dynamicAnchor=uA;function F1(e){let{schemaEnv:t,schema:i,self:n}=e.it,{root:r,baseId:o,localRefs:s,meta:a}=t.root,{schemaId:g}=n.opts,l=new cA.SchemaEnv({schema:i,schemaId:g,root:r,baseId:o,localRefs:s,meta:a});return cA.compileSchema.call(n,l),(0,G1.getValidate)(e,l)}Ur.default=w1});var $l=f(function(Or){Object.defineProperty(Or,"__esModule",{value:!0});Or.dynamicRef=void 0;var CA=N(),H1=Ke(),mA=fs(),v1={keyword:"$dynamicRef",schemaType:"string",code:(e)=>pA(e,e.schema)};function pA(e,t){let{gen:i,keyword:n,it:r}=e;if(t[0]!=="#")throw Error(`"${n}" only supports hash fragment reference`);let o=t.slice(1);if(r.allErrors)s();else{let g=i.let("valid",!1);s(g),e.ok(g)}function s(g){if(r.schemaEnv.root.dynamicAnchors[o]){let l=i.let("_v",CA._`${H1.default.dynamicAnchors}${(0,CA.getProperty)(o)}`);i.if(l,a(l,g),a(r.validateName,g))}else a(r.validateName,g)()}function a(g,l){return l?()=>i.block(()=>{(0,mA.callRef)(e,g),i.let(l,!0)}):()=>(0,mA.callRef)(e,g)}}Or.dynamicRef=pA;Or.default=v1});var AA=f(function(ql){Object.defineProperty(ql,"__esModule",{value:!0});var k1=Ml(),P1=T(),N1={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,k1.dynamicAnchor)(e,"");else(0,P1.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};ql.default=N1});var bA=f(function(ed){Object.defineProperty(ed,"__esModule",{value:!0});var x1=$l(),Y1={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,x1.dynamicRef)(e,e.schema)};ed.default=Y1});var ZA=f(function(td){Object.defineProperty(td,"__esModule",{value:!0});var S1=Ml(),X1=$l(),E1=AA(),T1=bA(),J1=[S1.default,X1.default,E1.default,T1.default];td.default=J1});var fA=f(function(id){Object.defineProperty(id,"__esModule",{value:!0});var hA=ws(),U1={keyword:"dependentRequired",type:"object",schemaType:"object",error:hA.error,code:(e)=>(0,hA.validatePropertyDeps)(e)};id.default=U1});var WA=f(function(nd){Object.defineProperty(nd,"__esModule",{value:!0});var O1=ws(),z1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,O1.validateSchemaDeps)(e)};nd.default=z1});var yA=f(function(rd){Object.defineProperty(rd,"__esModule",{value:!0});var j1=T(),D1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:i}){if(t.contains===void 0)(0,j1.checkStrictMode)(i,`"${e}" without "contains" is ignored`)}};rd.default=D1});var VA=f(function(od){Object.defineProperty(od,"__esModule",{value:!0});var _1=fA(),Q1=WA(),K1=yA(),L1=[_1.default,Q1.default,K1.default];od.default=L1});var RA=f(function(sd){Object.defineProperty(sd,"__esModule",{value:!0});var $t=N(),BA=T(),M1=Ke(),$1={message:"must NOT have unevaluated properties",params:({params:e})=>$t._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},q1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:$1,code(e){let{gen:t,schema:i,data:n,errsCount:r,it:o}=e;if(!r)throw Error("ajv implementation error");let{allErrors:s,props:a}=o;if(a instanceof $t.Name)t.if($t._`${a} !== true`,()=>t.forIn("key",n,(I)=>t.if(l(a,I),()=>g(I))));else if(a!==!0)t.forIn("key",n,(I)=>a===void 0?g(I):t.if(d(a,I),()=>g(I)));o.props=!0,e.ok($t._`${r} === ${M1.default.errors}`);function g(I){if(i===!1){if(e.setParams({unevaluatedProperty:I}),e.error(),!s)t.break();return}if(!(0,BA.alwaysValidSchema)(o,i)){let C=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:I,dataPropType:BA.Type.Str},C),!s)t.if((0,$t.not)(C),()=>t.break())}}function l(I,C){return $t._`!${I} || !${I}[${C}]`}function d(I,C){let m=[];for(let A in I)if(I[A]===!0)m.push($t._`${C} !== ${A}`);return(0,$t.and)(...m)}}};sd.default=q1});var wA=f(function(ad){Object.defineProperty(ad,"__esModule",{value:!0});var Ri=N(),GA=T(),eP={message:({params:{len:e}})=>Ri.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ri._`{limit: ${e}}`},tP={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:eP,code(e){let{gen:t,schema:i,data:n,it:r}=e,o=r.items||0;if(o===!0)return;let s=t.const("len",Ri._`${n}.length`);if(i===!1)e.setParams({len:o}),e.fail(Ri._`${s} > ${o}`);else if(typeof i=="object"&&!(0,GA.alwaysValidSchema)(r,i)){let g=t.var("valid",Ri._`${s} <= ${o}`);t.if((0,Ri.not)(g),()=>a(g,o)),e.ok(g)}r.items=!0;function a(g,l){t.forRange("i",l,s,(d)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:GA.Type.Num},g),!r.allErrors)t.if((0,Ri.not)(g),()=>t.break())})}}};ad.default=tP});var FA=f(function(gd){Object.defineProperty(gd,"__esModule",{value:!0});var iP=RA(),nP=wA(),rP=[iP.default,nP.default];gd.default=rP});var HA=f(function(ld){Object.defineProperty(ld,"__esModule",{value:!0});var se=N(),oP={message:({schemaCode:e})=>se.str`must match format "${e}"`,params:({schemaCode:e})=>se._`{format: ${e}}`},sP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oP,code(e,t){let{gen:i,data:n,$data:r,schema:o,schemaCode:s,it:a}=e,{opts:g,errSchemaPath:l,schemaEnv:d,self:I}=a;if(!g.validateFormats)return;if(r)C();else m();function C(){let A=i.scopeValue("formats",{ref:I.formats,code:g.code.formats}),c=i.const("fDef",se._`${A}[${s}]`),u=i.let("fType"),p=i.let("format");i.if(se._`typeof ${c} == "object" && !(${c} instanceof RegExp)`,()=>i.assign(u,se._`${c}.type || "string"`).assign(p,se._`${c}.validate`),()=>i.assign(u,se._`"string"`).assign(p,c)),e.fail$data((0,se.or)(Z(),h()));function Z(){if(g.strictSchema===!1)return se.nil;return se._`${s} && !${p}`}function h(){let W=d.$async?se._`(${c}.async ? await ${p}(${n}) : ${p}(${n}))`:se._`${p}(${n})`,y=se._`(typeof ${p} == "function" ? ${W} : ${p}.test(${n}))`;return se._`${p} && ${p} !== true && ${u} === ${t} && !${y}`}}function m(){let A=I.formats[o];if(!A){Z();return}if(A===!0)return;let[c,u,p]=h(A);if(c===t)e.pass(W());function Z(){if(g.strictSchema===!1){I.logger.warn(y());return}throw Error(y());function y(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function h(y){let V=y instanceof RegExp?(0,se.regexpCode)(y):g.code.formats?se._`${g.code.formats}${(0,se.getProperty)(o)}`:void 0,H=i.scopeValue("formats",{key:o,ref:y,code:V});if(typeof y=="object"&&!(y instanceof RegExp))return[y.type||"string",y.validate,se._`${H}.validate`];return["string",y,H]}function W(){if(typeof A=="object"&&!(A instanceof RegExp)&&A.async){if(!d.$async)throw Error("async format in sync schema");return se._`await ${p}(${n})`}return typeof u=="function"?se._`${p}(${n})`:se._`${p}.test(${n})`}}}};ld.default=sP});var Id=f(function(dd){Object.defineProperty(dd,"__esModule",{value:!0});var aP=HA(),gP=[aP.default];dd.default=gP});var cd=f(function(hn){Object.defineProperty(hn,"__esModule",{value:!0});hn.contentVocabulary=hn.metadataVocabulary=void 0;hn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];hn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kA=f(function(ud){Object.defineProperty(ud,"__esModule",{value:!0});var lP=cl(),dP=wl(),IP=Kl(),cP=ZA(),uP=VA(),CP=FA(),mP=Id(),vA=cd(),pP=[cP.default,lP.default,dP.default,(0,IP.default)(!0),mP.default,vA.metadataVocabulary,vA.contentVocabulary,uP.default,CP.default];ud.default=pP});var NA=f(function(Ns){Object.defineProperty(Ns,"__esModule",{value:!0});Ns.DiscrError=void 0;var PA;(function(e){e.Tag="tag",e.Mapping="mapping"})(PA||(Ns.DiscrError=PA={}))});var pd=f(function(md){Object.defineProperty(md,"__esModule",{value:!0});var fn=N(),Cd=NA(),xA=Fr(),AP=An(),bP=T(),ZP={message:({params:{discrError:e,tagName:t}})=>e===Cd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:i}})=>fn._`{error: ${e}, tag: ${i}, tagValue: ${t}}`},hP={keyword:"discriminator",type:"object",schemaType:"object",error:ZP,code(e){let{gen:t,data:i,schema:n,parentSchema:r,it:o}=e,{oneOf:s}=r;if(!o.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!s)throw Error("discriminator: requires oneOf keyword");let g=t.let("valid",!1),l=t.const("tag",fn._`${i}${(0,fn.getProperty)(a)}`);t.if(fn._`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:Cd.DiscrError.Tag,tag:l,tagName:a})),e.ok(g);function d(){let m=C();t.if(!1);for(let A in m)t.elseIf(fn._`${l} === ${A}`),t.assign(g,I(m[A]));t.else(),e.error(!1,{discrError:Cd.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function I(m){let A=t.name("valid"),c=e.subschema({keyword:"oneOf",schemaProp:m},A);return e.mergeEvaluated(c,fn.Name),A}function C(){var m;let A={},c=p(r),u=!0;for(let W=0;W<s.length;W++){let y=s[W];if((y===null||y===void 0?void 0:y.$ref)&&!(0,bP.schemaHasRulesButRef)(y,o.self.RULES)){let H=y.$ref;if(y=xA.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,H),y instanceof xA.SchemaEnv)y=y.schema;if(y===void 0)throw new AP.default(o.opts.uriResolver,o.baseId,H)}let V=(m=y===null||y===void 0?void 0:y.properties)===null||m===void 0?void 0:m[a];if(typeof V!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);u=u&&(c||p(y)),Z(V,W)}if(!u)throw Error(`discriminator: "${a}" must be required`);return A;function p({required:W}){return Array.isArray(W)&&W.includes(a)}function Z(W,y){if(W.const)h(W.const,y);else if(W.enum)for(let V of W.enum)h(V,y);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function h(W,y){if(typeof W!="string"||W in A)throw Error(`discriminator: "${a}" values must be unique strings`);A[W]=y}}}};md.default=hP});var YA=f(function(K9,fP){fP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var SA=f(function(L9,WP){WP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var XA=f(function(M9,yP){yP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var EA=f(function($9,VP){VP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var TA=f(function(q9,BP){BP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var JA=f(function(eD,RP){RP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var UA=f(function(tD,GP){GP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var OA=f(function(iD,wP){wP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var zA=f(function(Ad){Object.defineProperty(Ad,"__esModule",{value:!0});var FP=YA(),HP=SA(),vP=XA(),kP=EA(),PP=TA(),NP=JA(),xP=UA(),YP=OA(),SP=["/properties"];function XP(e){return[FP,HP,vP,kP,PP,t(this,NP),xP,t(this,YP)].forEach((i)=>this.addMetaSchema(i,void 0,!1)),this;function t(i,n){return e?i.$dataMetaSchema(n,SP):n}}Ad.default=XP});var hd=f(function(M,Zd){Object.defineProperty(M,"__esModule",{value:!0});M.MissingRefError=M.ValidationError=M.CodeGen=M.Name=M.nil=M.stringify=M.str=M._=M.KeywordCxt=M.Ajv2020=void 0;var EP=ll(),TP=kA(),JP=pd(),UP=zA(),bd="https://json-schema.org/draft/2020-12/schema";class zr extends EP.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),TP.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(JP.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;UP.default.call(this,e),this.refs["http://json-schema.org/schema"]=bd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bd)?bd:void 0)}}M.Ajv2020=zr;Zd.exports=M=zr;Zd.exports.Ajv2020=zr;Object.defineProperty(M,"__esModule",{value:!0});M.default=zr;var OP=pn();Object.defineProperty(M,"KeywordCxt",{enumerable:!0,get:function(){return OP.KeywordCxt}});var Wn=N();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Wn._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Wn.str}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Wn.stringify}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Wn.nil}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Wn.Name}});Object.defineProperty(M,"CodeGen",{enumerable:!0,get:function(){return Wn.CodeGen}});var zP=Gr();Object.defineProperty(M,"ValidationError",{enumerable:!0,get:function(){return zP.default}});var jP=An();Object.defineProperty(M,"MissingRefError",{enumerable:!0,get:function(){return jP.default}})});var $A=f(function(yt){Object.defineProperty(yt,"__esModule",{value:!0});yt.formatNames=yt.fastFormats=yt.fullFormats=void 0;function Wt(e,t){return{validate:e,compare:t}}yt.fullFormats={date:Wt(QA,Vd),time:Wt(Wd(!0),Bd),"date-time":Wt(jA(!0),LA),"iso-time":Wt(Wd(),KA),"iso-date-time":Wt(jA(),MA),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:r2,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$P,int32:{type:"number",validate:t2},int64:{type:"number",validate:i2},float:{type:"number",validate:_A},double:{type:"number",validate:_A},password:!0,binary:!0};yt.fastFormats={...yt.fullFormats,date:Wt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vd),time:Wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bd),"date-time":Wt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,LA),"iso-time":Wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,KA),"iso-date-time":Wt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,MA),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};yt.formatNames=Object.keys(yt.fullFormats);function DP(e){return e%4===0&&(e%100!==0||e%400===0)}var _P=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function QA(e){let t=_P.exec(e);if(!t)return!1;let i=+t[1],n=+t[2],r=+t[3];return n>=1&&n<=12&&r>=1&&r<=(n===2&&DP(i)?29:QP[n])}function Vd(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var fd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Wd(e){return function(i){let n=fd.exec(i);if(!n)return!1;let r=+n[1],o=+n[2],s=+n[3],a=n[4],g=n[5]==="-"?-1:1,l=+(n[6]||0),d=+(n[7]||0);if(l>23||d>59||e&&!a)return!1;if(r<=23&&o<=59&&s<60)return!0;let I=o-d*g,C=r-l*g-(I<0?1:0);return(C===23||C===-1)&&(I===59||I===-1)&&s<61}}function Bd(e,t){if(!(e&&t))return;let i=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(!(i&&n))return;return i-n}function KA(e,t){if(!(e&&t))return;let i=fd.exec(e),n=fd.exec(t);if(!(i&&n))return;if(e=i[1]+i[2]+i[3],t=n[1]+n[2]+n[3],e>t)return 1;if(e<t)return-1;return 0}var yd=/t|\s/i;function jA(e){let t=Wd(e);return function(n){let r=n.split(yd);return r.length===2&&QA(r[0])&&t(r[1])}}function LA(e,t){if(!(e&&t))return;let i=new Date(e).valueOf(),n=new Date(t).valueOf();if(!(i&&n))return;return i-n}function MA(e,t){if(!(e&&t))return;let[i,n]=e.split(yd),[r,o]=t.split(yd),s=Vd(i,r);if(s===void 0)return;return s||Bd(n,o)}var KP=/\/|:/,LP=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function MP(e){return KP.test(e)&&LP.test(e)}var DA=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $P(e){return DA.lastIndex=0,DA.test(e)}var qP=-2147483648,e2=2147483647;function t2(e){return Number.isInteger(e)&&e<=e2&&e>=qP}function i2(e){return Number.isInteger(e)}function _A(){return!0}var n2=/[^\\]\\Z/;function r2(e){if(n2.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var eb=f(function(Rd){Object.defineProperty(Rd,"__esModule",{value:!0});var o2=cl(),s2=wl(),a2=Kl(),g2=Id(),qA=cd(),l2=[o2.default,s2.default,(0,a2.default)(),g2.default,qA.metadataVocabulary,qA.contentVocabulary];Rd.default=l2});var tb=f(function(sD,d2){d2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var nb=f(function(q,Gd){Object.defineProperty(q,"__esModule",{value:!0});q.MissingRefError=q.ValidationError=q.CodeGen=q.Name=q.nil=q.stringify=q.str=q._=q.KeywordCxt=q.Ajv=void 0;var I2=ll(),c2=eb(),u2=pd(),ib=tb(),C2=["/properties"],xs="http://json-schema.org/draft-07/schema";class jr extends I2.default{_addVocabularies(){if(super._addVocabularies(),c2.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(u2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ib,C2):ib;this.addMetaSchema(e,xs,!1),this.refs["http://json-schema.org/schema"]=xs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xs)?xs:void 0)}}q.Ajv=jr;Gd.exports=q=jr;Gd.exports.Ajv=jr;Object.defineProperty(q,"__esModule",{value:!0});q.default=jr;var m2=pn();Object.defineProperty(q,"KeywordCxt",{enumerable:!0,get:function(){return m2.KeywordCxt}});var yn=N();Object.defineProperty(q,"_",{enumerable:!0,get:function(){return yn._}});Object.defineProperty(q,"str",{enumerable:!0,get:function(){return yn.str}});Object.defineProperty(q,"stringify",{enumerable:!0,get:function(){return yn.stringify}});Object.defineProperty(q,"nil",{enumerable:!0,get:function(){return yn.nil}});Object.defineProperty(q,"Name",{enumerable:!0,get:function(){return yn.Name}});Object.defineProperty(q,"CodeGen",{enumerable:!0,get:function(){return yn.CodeGen}});var p2=Gr();Object.defineProperty(q,"ValidationError",{enumerable:!0,get:function(){return p2.default}});var A2=An();Object.defineProperty(q,"MissingRefError",{enumerable:!0,get:function(){return A2.default}})});var rb=f(function(Vn){Object.defineProperty(Vn,"__esModule",{value:!0});Vn.formatLimitDefinition=void 0;var b2=nb(),gt=N(),qt=gt.operators,Ys={formatMaximum:{okStr:"<=",ok:qt.LTE,fail:qt.GT},formatMinimum:{okStr:">=",ok:qt.GTE,fail:qt.LT},formatExclusiveMaximum:{okStr:"<",ok:qt.LT,fail:qt.GTE},formatExclusiveMinimum:{okStr:">",ok:qt.GT,fail:qt.LTE}},Z2={message:({keyword:e,schemaCode:t})=>gt.str`should be ${Ys[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>gt._`{comparison: ${Ys[e].okStr}, limit: ${t}}`};Vn.formatLimitDefinition={keyword:Object.keys(Ys),type:"string",schemaType:"string",$data:!0,error:Z2,code(e){let{gen:t,data:i,schemaCode:n,keyword:r,it:o}=e,{opts:s,self:a}=o;if(!s.validateFormats)return;let g=new b2.KeywordCxt(o,a.RULES.all.format.definition,"format");if(g.$data)l();else d();function l(){let C=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),m=t.const("fmt",gt._`${C}[${g.schemaCode}]`);e.fail$data((0,gt.or)(gt._`typeof ${m} != "object"`,gt._`${m} instanceof RegExp`,gt._`typeof ${m}.compare != "function"`,I(m)))}function d(){let C=g.schema,m=a.formats[C];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw Error(`"${r}": format "${C}" does not define "compare" function`);let A=t.scopeValue("formats",{key:C,ref:m,code:s.code.formats?gt._`${s.code.formats}${(0,gt.getProperty)(C)}`:void 0});e.fail$data(I(A))}function I(C){return gt._`${C}.compare(${i}, ${n}) ${Ys[r].fail} 0`}},dependencies:["format"]};var h2=(e)=>(e.addKeyword(Vn.formatLimitDefinition),e);Vn.default=h2});var gb=f(function(Dr,ab){Object.defineProperty(Dr,"__esModule",{value:!0});var Bn=$A(),f2=rb(),wd=N(),ob=new wd.Name("fullFormats"),W2=new wd.Name("fastFormats"),Fd=(e,t={keywords:!0})=>{if(Array.isArray(t))return sb(e,t,Bn.fullFormats,ob),e;let[i,n]=t.mode==="fast"?[Bn.fastFormats,W2]:[Bn.fullFormats,ob],r=t.formats||Bn.formatNames;if(sb(e,r,i,n),t.keywords)(0,f2.default)(e);return e};Fd.get=(e,t="full")=>{let n=(t==="fast"?Bn.fastFormats:Bn.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function sb(e,t,i,n){var r,o;(r=(o=e.opts.code).formats)!==null&&r!==void 0||(o.formats=wd._`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,i[s])}ab.exports=Dr=Fd;Object.defineProperty(Dr,"__esModule",{value:!0});Dr.default=Fd});var Qf=f(function(I_,_f){_f.exports=nX;function iX(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(i){if(!e[i])e[i]=t[i]}),e}function nX(e){let t=iX(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let i=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(i)&&i!==0)return i}return t.defaultWidth}});var uW=f(function(B_,cW){var bX=require("stream");class IW extends bX{#i=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#i!==null)return this.#i;return this.#t("isTTY",!1)}set isTTY(e){this.#i=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}cW.exports=IW});class Gt extends Error{constructor(e,t,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class Ze extends Gt{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Ao{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new Ze(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function bo(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Rc=require("events"),ho=Pe(require("child_process")),It=Pe(require("path")),Kn=Pe(require("fs")),j=Pe(require("process")),Gc=require("util");var Wc=require("util");class Zo{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((n)=>!n._hidden),i=e._getHelpCommand();if(i&&!i._hidden)t.push(i);if(this.sortSubcommands)t.sort((n,r)=>n.name().localeCompare(r.name()));return t}compareOptions(e,t){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);if(!n&&!r)t.push(i);else if(i.long&&!r)t.push(e.createOption(i.long,i.description));else if(i.short&&!n)t.push(e.createOption(i.short,i.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter((r)=>!r.hidden);t.push(...n)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((i)=>bo(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}formatItemList(e,t,i){if(t.length===0)return[];return[i.styleTitle(e),...t,""]}groupItems(e,t,i){let n=new Map;return e.forEach((r)=>{let o=i(r);if(!n.has(o))n.set(o,[])}),t.forEach((r)=>{let o=i(r);if(!n.has(o))n.set(o,[]);n.get(o).push(r)}),n}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function r(d,I){return t.formatItem(d,i,I,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],s=t.commandDescription(e);if(s.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(s),n),""]);let a=t.visibleArguments(e).map((d)=>r(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(d)=>d.helpGroupHeading??"Options:").forEach((d,I)=>{let C=d.map((m)=>r(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));o=o.concat(this.formatItemList(I,C,t))}),t.showGlobalOptions){let d=t.visibleGlobalOptions(e).map((I)=>r(t.styleOptionTerm(t.optionTerm(I)),t.styleOptionDescription(t.optionDescription(I))));o=o.concat(this.formatItemList("Global Options:",d,t))}return this.groupItems(e.commands,t.visibleCommands(e),(d)=>d.helpGroup()||"Commands:").forEach((d,I)=>{let C=d.map((m)=>r(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));o=o.concat(this.formatItemList(I,C,t))}),o.join(`
|
|
10
|
+
deps: ${i}}`};var Ek={keyword:"dependencies",type:"object",schemaType:"object",error:ft.error,code(e){let[t,i]=Tk(e);_p(e,t),Qp(e,i)}};function Tk({schema:e}){let t={},i={};for(let n in e){if(n==="__proto__")continue;let r=Array.isArray(e[n])?t:i;r[n]=e[n]}return[t,i]}function _p(e,t=e.schema){let{gen:i,data:n,it:r}=e;if(Object.keys(t).length===0)return;let o=i.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let g=(0,Jr.propertyInData)(i,n,s,r.opts.ownProperties);if(e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),r.allErrors)i.if(g,()=>{for(let l of a)(0,Jr.checkReportMissingProp)(e,l)});else i.if(xl._`${g} && (${(0,Jr.checkMissingProp)(e,a,o)})`),(0,Jr.reportMissingProp)(e,o),i.else()}}ft.validatePropertyDeps=_p;function Qp(e,t=e.schema){let{gen:i,data:n,keyword:r,it:o}=e,s=i.name("valid");for(let a in t){if((0,Xk.alwaysValidSchema)(o,t[a]))continue;i.if((0,Jr.propertyInData)(i,n,a,o.opts.ownProperties),()=>{let g=e.subschema({keyword:r,schemaProp:a},s);e.mergeValidEvaluated(g,s)},()=>i.var(s,!0)),e.ok(s)}}ft.validateSchemaDeps=Qp;ft.default=Ek});var Lp=f(function(Yl){Object.defineProperty(Yl,"__esModule",{value:!0});var Kp=N(),Jk=T(),Uk={message:"property name must be valid",params:({params:e})=>Kp._`{propertyName: ${e.propertyName}}`},Ok={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Uk,code(e){let{gen:t,schema:i,data:n,it:r}=e;if((0,Jk.alwaysValidSchema)(r,i))return;let o=t.name("valid");t.forIn("key",n,(s)=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,Kp.not)(o),()=>{if(e.error(!0),!r.allErrors)t.break()})}),e.ok(o)}};Yl.default=Ok});var Xl=f(function(Sl){Object.defineProperty(Sl,"__esModule",{value:!0});var Fs=Le(),at=N(),zk=Ke(),Hs=T(),jk={message:"must NOT have additional properties",params:({params:e})=>at._`{additionalProperty: ${e.additionalProperty}}`},Dk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jk,code(e){let{gen:t,schema:i,parentSchema:n,data:r,errsCount:o,it:s}=e;if(!o)throw Error("ajv implementation error");let{allErrors:a,opts:g}=s;if(s.props=!0,g.removeAdditional!=="all"&&(0,Hs.alwaysValidSchema)(s,i))return;let l=(0,Fs.allSchemaProperties)(n.properties),d=(0,Fs.allSchemaProperties)(n.patternProperties);I(),e.ok(at._`${o} === ${zk.default.errors}`);function I(){t.forIn("key",r,(u)=>{if(!l.length&&!d.length)A(u);else t.if(C(u),()=>A(u))})}function C(u){let p;if(l.length>8){let Z=(0,Hs.schemaRefOrVal)(s,n.properties,"properties");p=(0,Fs.isOwnProperty)(t,Z,u)}else if(l.length)p=(0,at.or)(...l.map((Z)=>at._`${u} === ${Z}`));else p=at.nil;if(d.length)p=(0,at.or)(p,...d.map((Z)=>at._`${(0,Fs.usePattern)(e,Z)}.test(${u})`));return(0,at.not)(p)}function m(u){t.code(at._`delete ${r}[${u}]`)}function A(u){if(g.removeAdditional==="all"||g.removeAdditional&&i===!1){m(u);return}if(i===!1){if(e.setParams({additionalProperty:u}),e.error(),!a)t.break();return}if(typeof i=="object"&&!(0,Hs.alwaysValidSchema)(s,i)){let p=t.name("valid");if(g.removeAdditional==="failing")c(u,p,!1),t.if((0,at.not)(p),()=>{e.reset(),m(u)});else if(c(u,p),!a)t.if((0,at.not)(p),()=>t.break())}}function c(u,p,Z){let h={keyword:"additionalProperties",dataProp:u,dataPropType:Hs.Type.Str};if(Z===!1)Object.assign(h,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(h,p)}}};Sl.default=Dk});var qp=f(function(Tl){Object.defineProperty(Tl,"__esModule",{value:!0});var _k=pn(),Mp=Le(),El=T(),$p=Xl(),Qk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:i,parentSchema:n,data:r,it:o}=e;if(o.opts.removeAdditional==="all"&&n.additionalProperties===void 0)$p.default.code(new _k.KeywordCxt(o,$p.default,"additionalProperties"));let s=(0,Mp.allSchemaProperties)(i);for(let I of s)o.definedProperties.add(I);if(o.opts.unevaluated&&s.length&&o.props!==!0)o.props=El.mergeEvaluated.props(t,(0,El.toHash)(s),o.props);let a=s.filter((I)=>!(0,El.alwaysValidSchema)(o,i[I]));if(a.length===0)return;let g=t.name("valid");for(let I of a){if(l(I))d(I);else{if(t.if((0,Mp.propertyInData)(t,r,I,o.opts.ownProperties)),d(I),!o.allErrors)t.else().var(g,!0);t.endIf()}e.it.definedProperties.add(I),e.ok(g)}function l(I){return o.opts.useDefaults&&!o.compositeRule&&i[I].default!==void 0}function d(I){e.subschema({keyword:"properties",schemaProp:I,dataProp:I},g)}}};Tl.default=Qk});var nA=f(function(Jl){Object.defineProperty(Jl,"__esModule",{value:!0});var eA=Le(),vs=N(),tA=T(),iA=T(),Kk={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:i,data:n,parentSchema:r,it:o}=e,{opts:s}=o,a=(0,eA.allSchemaProperties)(i),g=a.filter((c)=>(0,tA.alwaysValidSchema)(o,i[c]));if(a.length===0||g.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&r.properties,d=t.name("valid");if(o.props!==!0&&!(o.props instanceof vs.Name))o.props=(0,iA.evaluatedPropsToName)(t,o.props);let{props:I}=o;C();function C(){for(let c of a){if(l)m(c);if(o.allErrors)A(c);else t.var(d,!0),A(c),t.if(d)}}function m(c){for(let u in l)if(new RegExp(c).test(u))(0,tA.checkStrictMode)(o,`property ${u} matches pattern ${c} (use allowMatchingProperties)`)}function A(c){t.forIn("key",n,(u)=>{t.if(vs._`${(0,eA.usePattern)(e,c)}.test(${u})`,()=>{let p=g.includes(c);if(!p)e.subschema({keyword:"patternProperties",schemaProp:c,dataProp:u,dataPropType:iA.Type.Str},d);if(o.opts.unevaluated&&I!==!0)t.assign(vs._`${I}[${u}]`,!0);else if(!p&&!o.allErrors)t.if((0,vs.not)(d),()=>t.break())})})}}};Jl.default=Kk});var rA=f(function(Ul){Object.defineProperty(Ul,"__esModule",{value:!0});var Lk=T(),Mk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:i,it:n}=e;if((0,Lk.alwaysValidSchema)(n,i)){e.fail();return}let r=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),e.failResult(r,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ul.default=Mk});var oA=f(function(Ol){Object.defineProperty(Ol,"__esModule",{value:!0});var $k=Le(),qk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$k.validateUnion,error:{message:"must match a schema in anyOf"}};Ol.default=qk});var sA=f(function(zl){Object.defineProperty(zl,"__esModule",{value:!0});var ks=N(),e1=T(),t1={message:"must match exactly one schema in oneOf",params:({params:e})=>ks._`{passingSchemas: ${e.passing}}`},i1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:t1,code(e){let{gen:t,schema:i,parentSchema:n,it:r}=e;if(!Array.isArray(i))throw Error("ajv implementation error");if(r.opts.discriminator&&n.discriminator)return;let o=i,s=t.let("valid",!1),a=t.let("passing",null),g=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((d,I)=>{let C;if((0,e1.alwaysValidSchema)(r,d))t.var(g,!0);else C=e.subschema({keyword:"oneOf",schemaProp:I,compositeRule:!0},g);if(I>0)t.if(ks._`${g} && ${s}`).assign(s,!1).assign(a,ks._`[${a}, ${I}]`).else();t.if(g,()=>{if(t.assign(s,!0),t.assign(a,I),C)e.mergeEvaluated(C,ks.Name)})})}}};zl.default=i1});var aA=f(function(jl){Object.defineProperty(jl,"__esModule",{value:!0});var n1=T(),r1={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:i,it:n}=e;if(!Array.isArray(i))throw Error("ajv implementation error");let r=t.name("valid");i.forEach((o,s)=>{if((0,n1.alwaysValidSchema)(n,o))return;let a=e.subschema({keyword:"allOf",schemaProp:s},r);e.ok(r),e.mergeEvaluated(a)})}};jl.default=r1});var dA=f(function(Dl){Object.defineProperty(Dl,"__esModule",{value:!0});var Ps=N(),lA=T(),o1={message:({params:e})=>Ps.str`must match "${e.ifClause}" schema`,params:({params:e})=>Ps._`{failingKeyword: ${e.ifClause}}`},s1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:o1,code(e){let{gen:t,parentSchema:i,it:n}=e;if(i.then===void 0&&i.else===void 0)(0,lA.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let r=gA(n,"then"),o=gA(n,"else");if(!r&&!o)return;let s=t.let("valid",!0),a=t.name("_valid");if(g(),e.reset(),r&&o){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else if(r)t.if(a,l("then"));else t.if((0,Ps.not)(a),l("else"));e.pass(s,()=>e.error(!0));function g(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,I){return()=>{let C=e.subschema({keyword:d},a);if(t.assign(s,a),e.mergeValidEvaluated(C,s),I)t.assign(I,Ps._`${d}`);else e.setParams({ifClause:d})}}}};function gA(e,t){let i=e.schema[t];return i!==void 0&&!(0,lA.alwaysValidSchema)(e,i)}Dl.default=s1});var IA=f(function(_l){Object.defineProperty(_l,"__esModule",{value:!0});var a1=T(),g1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:i}){if(t.if===void 0)(0,a1.checkStrictMode)(i,`"${e}" without "if" is ignored`)}};_l.default=g1});var Kl=f(function(Ql){Object.defineProperty(Ql,"__esModule",{value:!0});var l1=Hl(),d1=Op(),I1=vl(),c1=jp(),u1=Dp(),C1=ws(),m1=Lp(),p1=Xl(),A1=qp(),b1=nA(),Z1=rA(),h1=oA(),f1=sA(),W1=aA(),y1=dA(),V1=IA();function B1(e=!1){let t=[Z1.default,h1.default,f1.default,W1.default,y1.default,V1.default,m1.default,p1.default,C1.default,A1.default,b1.default];if(e)t.push(d1.default,c1.default);else t.push(l1.default,I1.default);return t.push(u1.default),t}Ql.default=B1});var Ml=f(function(Ur){Object.defineProperty(Ur,"__esModule",{value:!0});Ur.dynamicAnchor=void 0;var Ll=N(),R1=Ke(),cA=Fr(),G1=fs(),w1={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>uA(e,e.schema)};function uA(e,t){let{gen:i,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let r=Ll._`${R1.default.dynamicAnchors}${(0,Ll.getProperty)(t)}`,o=n.errSchemaPath==="#"?n.validateName:F1(e);i.if(Ll._`!${r}`,()=>i.assign(r,o))}Ur.dynamicAnchor=uA;function F1(e){let{schemaEnv:t,schema:i,self:n}=e.it,{root:r,baseId:o,localRefs:s,meta:a}=t.root,{schemaId:g}=n.opts,l=new cA.SchemaEnv({schema:i,schemaId:g,root:r,baseId:o,localRefs:s,meta:a});return cA.compileSchema.call(n,l),(0,G1.getValidate)(e,l)}Ur.default=w1});var $l=f(function(Or){Object.defineProperty(Or,"__esModule",{value:!0});Or.dynamicRef=void 0;var CA=N(),H1=Ke(),mA=fs(),v1={keyword:"$dynamicRef",schemaType:"string",code:(e)=>pA(e,e.schema)};function pA(e,t){let{gen:i,keyword:n,it:r}=e;if(t[0]!=="#")throw Error(`"${n}" only supports hash fragment reference`);let o=t.slice(1);if(r.allErrors)s();else{let g=i.let("valid",!1);s(g),e.ok(g)}function s(g){if(r.schemaEnv.root.dynamicAnchors[o]){let l=i.let("_v",CA._`${H1.default.dynamicAnchors}${(0,CA.getProperty)(o)}`);i.if(l,a(l,g),a(r.validateName,g))}else a(r.validateName,g)()}function a(g,l){return l?()=>i.block(()=>{(0,mA.callRef)(e,g),i.let(l,!0)}):()=>(0,mA.callRef)(e,g)}}Or.dynamicRef=pA;Or.default=v1});var AA=f(function(ql){Object.defineProperty(ql,"__esModule",{value:!0});var k1=Ml(),P1=T(),N1={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,k1.dynamicAnchor)(e,"");else(0,P1.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};ql.default=N1});var bA=f(function(ed){Object.defineProperty(ed,"__esModule",{value:!0});var x1=$l(),Y1={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,x1.dynamicRef)(e,e.schema)};ed.default=Y1});var ZA=f(function(td){Object.defineProperty(td,"__esModule",{value:!0});var S1=Ml(),X1=$l(),E1=AA(),T1=bA(),J1=[S1.default,X1.default,E1.default,T1.default];td.default=J1});var fA=f(function(id){Object.defineProperty(id,"__esModule",{value:!0});var hA=ws(),U1={keyword:"dependentRequired",type:"object",schemaType:"object",error:hA.error,code:(e)=>(0,hA.validatePropertyDeps)(e)};id.default=U1});var WA=f(function(nd){Object.defineProperty(nd,"__esModule",{value:!0});var O1=ws(),z1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,O1.validateSchemaDeps)(e)};nd.default=z1});var yA=f(function(rd){Object.defineProperty(rd,"__esModule",{value:!0});var j1=T(),D1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:i}){if(t.contains===void 0)(0,j1.checkStrictMode)(i,`"${e}" without "contains" is ignored`)}};rd.default=D1});var VA=f(function(od){Object.defineProperty(od,"__esModule",{value:!0});var _1=fA(),Q1=WA(),K1=yA(),L1=[_1.default,Q1.default,K1.default];od.default=L1});var RA=f(function(sd){Object.defineProperty(sd,"__esModule",{value:!0});var $t=N(),BA=T(),M1=Ke(),$1={message:"must NOT have unevaluated properties",params:({params:e})=>$t._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},q1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:$1,code(e){let{gen:t,schema:i,data:n,errsCount:r,it:o}=e;if(!r)throw Error("ajv implementation error");let{allErrors:s,props:a}=o;if(a instanceof $t.Name)t.if($t._`${a} !== true`,()=>t.forIn("key",n,(I)=>t.if(l(a,I),()=>g(I))));else if(a!==!0)t.forIn("key",n,(I)=>a===void 0?g(I):t.if(d(a,I),()=>g(I)));o.props=!0,e.ok($t._`${r} === ${M1.default.errors}`);function g(I){if(i===!1){if(e.setParams({unevaluatedProperty:I}),e.error(),!s)t.break();return}if(!(0,BA.alwaysValidSchema)(o,i)){let C=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:I,dataPropType:BA.Type.Str},C),!s)t.if((0,$t.not)(C),()=>t.break())}}function l(I,C){return $t._`!${I} || !${I}[${C}]`}function d(I,C){let m=[];for(let A in I)if(I[A]===!0)m.push($t._`${C} !== ${A}`);return(0,$t.and)(...m)}}};sd.default=q1});var wA=f(function(ad){Object.defineProperty(ad,"__esModule",{value:!0});var Ri=N(),GA=T(),eP={message:({params:{len:e}})=>Ri.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ri._`{limit: ${e}}`},tP={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:eP,code(e){let{gen:t,schema:i,data:n,it:r}=e,o=r.items||0;if(o===!0)return;let s=t.const("len",Ri._`${n}.length`);if(i===!1)e.setParams({len:o}),e.fail(Ri._`${s} > ${o}`);else if(typeof i=="object"&&!(0,GA.alwaysValidSchema)(r,i)){let g=t.var("valid",Ri._`${s} <= ${o}`);t.if((0,Ri.not)(g),()=>a(g,o)),e.ok(g)}r.items=!0;function a(g,l){t.forRange("i",l,s,(d)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:GA.Type.Num},g),!r.allErrors)t.if((0,Ri.not)(g),()=>t.break())})}}};ad.default=tP});var FA=f(function(gd){Object.defineProperty(gd,"__esModule",{value:!0});var iP=RA(),nP=wA(),rP=[iP.default,nP.default];gd.default=rP});var HA=f(function(ld){Object.defineProperty(ld,"__esModule",{value:!0});var se=N(),oP={message:({schemaCode:e})=>se.str`must match format "${e}"`,params:({schemaCode:e})=>se._`{format: ${e}}`},sP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oP,code(e,t){let{gen:i,data:n,$data:r,schema:o,schemaCode:s,it:a}=e,{opts:g,errSchemaPath:l,schemaEnv:d,self:I}=a;if(!g.validateFormats)return;if(r)C();else m();function C(){let A=i.scopeValue("formats",{ref:I.formats,code:g.code.formats}),c=i.const("fDef",se._`${A}[${s}]`),u=i.let("fType"),p=i.let("format");i.if(se._`typeof ${c} == "object" && !(${c} instanceof RegExp)`,()=>i.assign(u,se._`${c}.type || "string"`).assign(p,se._`${c}.validate`),()=>i.assign(u,se._`"string"`).assign(p,c)),e.fail$data((0,se.or)(Z(),h()));function Z(){if(g.strictSchema===!1)return se.nil;return se._`${s} && !${p}`}function h(){let W=d.$async?se._`(${c}.async ? await ${p}(${n}) : ${p}(${n}))`:se._`${p}(${n})`,y=se._`(typeof ${p} == "function" ? ${W} : ${p}.test(${n}))`;return se._`${p} && ${p} !== true && ${u} === ${t} && !${y}`}}function m(){let A=I.formats[o];if(!A){Z();return}if(A===!0)return;let[c,u,p]=h(A);if(c===t)e.pass(W());function Z(){if(g.strictSchema===!1){I.logger.warn(y());return}throw Error(y());function y(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function h(y){let V=y instanceof RegExp?(0,se.regexpCode)(y):g.code.formats?se._`${g.code.formats}${(0,se.getProperty)(o)}`:void 0,H=i.scopeValue("formats",{key:o,ref:y,code:V});if(typeof y=="object"&&!(y instanceof RegExp))return[y.type||"string",y.validate,se._`${H}.validate`];return["string",y,H]}function W(){if(typeof A=="object"&&!(A instanceof RegExp)&&A.async){if(!d.$async)throw Error("async format in sync schema");return se._`await ${p}(${n})`}return typeof u=="function"?se._`${p}(${n})`:se._`${p}.test(${n})`}}}};ld.default=sP});var Id=f(function(dd){Object.defineProperty(dd,"__esModule",{value:!0});var aP=HA(),gP=[aP.default];dd.default=gP});var cd=f(function(hn){Object.defineProperty(hn,"__esModule",{value:!0});hn.contentVocabulary=hn.metadataVocabulary=void 0;hn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];hn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kA=f(function(ud){Object.defineProperty(ud,"__esModule",{value:!0});var lP=cl(),dP=wl(),IP=Kl(),cP=ZA(),uP=VA(),CP=FA(),mP=Id(),vA=cd(),pP=[cP.default,lP.default,dP.default,(0,IP.default)(!0),mP.default,vA.metadataVocabulary,vA.contentVocabulary,uP.default,CP.default];ud.default=pP});var NA=f(function(Ns){Object.defineProperty(Ns,"__esModule",{value:!0});Ns.DiscrError=void 0;var PA;(function(e){e.Tag="tag",e.Mapping="mapping"})(PA||(Ns.DiscrError=PA={}))});var pd=f(function(md){Object.defineProperty(md,"__esModule",{value:!0});var fn=N(),Cd=NA(),xA=Fr(),AP=An(),bP=T(),ZP={message:({params:{discrError:e,tagName:t}})=>e===Cd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:i}})=>fn._`{error: ${e}, tag: ${i}, tagValue: ${t}}`},hP={keyword:"discriminator",type:"object",schemaType:"object",error:ZP,code(e){let{gen:t,data:i,schema:n,parentSchema:r,it:o}=e,{oneOf:s}=r;if(!o.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!s)throw Error("discriminator: requires oneOf keyword");let g=t.let("valid",!1),l=t.const("tag",fn._`${i}${(0,fn.getProperty)(a)}`);t.if(fn._`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:Cd.DiscrError.Tag,tag:l,tagName:a})),e.ok(g);function d(){let m=C();t.if(!1);for(let A in m)t.elseIf(fn._`${l} === ${A}`),t.assign(g,I(m[A]));t.else(),e.error(!1,{discrError:Cd.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function I(m){let A=t.name("valid"),c=e.subschema({keyword:"oneOf",schemaProp:m},A);return e.mergeEvaluated(c,fn.Name),A}function C(){var m;let A={},c=p(r),u=!0;for(let W=0;W<s.length;W++){let y=s[W];if((y===null||y===void 0?void 0:y.$ref)&&!(0,bP.schemaHasRulesButRef)(y,o.self.RULES)){let H=y.$ref;if(y=xA.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,H),y instanceof xA.SchemaEnv)y=y.schema;if(y===void 0)throw new AP.default(o.opts.uriResolver,o.baseId,H)}let V=(m=y===null||y===void 0?void 0:y.properties)===null||m===void 0?void 0:m[a];if(typeof V!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);u=u&&(c||p(y)),Z(V,W)}if(!u)throw Error(`discriminator: "${a}" must be required`);return A;function p({required:W}){return Array.isArray(W)&&W.includes(a)}function Z(W,y){if(W.const)h(W.const,y);else if(W.enum)for(let V of W.enum)h(V,y);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function h(W,y){if(typeof W!="string"||W in A)throw Error(`discriminator: "${a}" values must be unique strings`);A[W]=y}}}};md.default=hP});var YA=f(function(L9,fP){fP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var SA=f(function(M9,WP){WP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var XA=f(function($9,yP){yP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var EA=f(function(q9,VP){VP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var TA=f(function(eD,BP){BP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var JA=f(function(tD,RP){RP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var UA=f(function(iD,GP){GP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var OA=f(function(nD,wP){wP.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var zA=f(function(Ad){Object.defineProperty(Ad,"__esModule",{value:!0});var FP=YA(),HP=SA(),vP=XA(),kP=EA(),PP=TA(),NP=JA(),xP=UA(),YP=OA(),SP=["/properties"];function XP(e){return[FP,HP,vP,kP,PP,t(this,NP),xP,t(this,YP)].forEach((i)=>this.addMetaSchema(i,void 0,!1)),this;function t(i,n){return e?i.$dataMetaSchema(n,SP):n}}Ad.default=XP});var hd=f(function(M,Zd){Object.defineProperty(M,"__esModule",{value:!0});M.MissingRefError=M.ValidationError=M.CodeGen=M.Name=M.nil=M.stringify=M.str=M._=M.KeywordCxt=M.Ajv2020=void 0;var EP=ll(),TP=kA(),JP=pd(),UP=zA(),bd="https://json-schema.org/draft/2020-12/schema";class zr extends EP.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),TP.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(JP.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;UP.default.call(this,e),this.refs["http://json-schema.org/schema"]=bd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bd)?bd:void 0)}}M.Ajv2020=zr;Zd.exports=M=zr;Zd.exports.Ajv2020=zr;Object.defineProperty(M,"__esModule",{value:!0});M.default=zr;var OP=pn();Object.defineProperty(M,"KeywordCxt",{enumerable:!0,get:function(){return OP.KeywordCxt}});var Wn=N();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Wn._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Wn.str}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Wn.stringify}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Wn.nil}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Wn.Name}});Object.defineProperty(M,"CodeGen",{enumerable:!0,get:function(){return Wn.CodeGen}});var zP=Gr();Object.defineProperty(M,"ValidationError",{enumerable:!0,get:function(){return zP.default}});var jP=An();Object.defineProperty(M,"MissingRefError",{enumerable:!0,get:function(){return jP.default}})});var $A=f(function(yt){Object.defineProperty(yt,"__esModule",{value:!0});yt.formatNames=yt.fastFormats=yt.fullFormats=void 0;function Wt(e,t){return{validate:e,compare:t}}yt.fullFormats={date:Wt(QA,Vd),time:Wt(Wd(!0),Bd),"date-time":Wt(jA(!0),LA),"iso-time":Wt(Wd(),KA),"iso-date-time":Wt(jA(),MA),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:r2,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$P,int32:{type:"number",validate:t2},int64:{type:"number",validate:i2},float:{type:"number",validate:_A},double:{type:"number",validate:_A},password:!0,binary:!0};yt.fastFormats={...yt.fullFormats,date:Wt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vd),time:Wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bd),"date-time":Wt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,LA),"iso-time":Wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,KA),"iso-date-time":Wt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,MA),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};yt.formatNames=Object.keys(yt.fullFormats);function DP(e){return e%4===0&&(e%100!==0||e%400===0)}var _P=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function QA(e){let t=_P.exec(e);if(!t)return!1;let i=+t[1],n=+t[2],r=+t[3];return n>=1&&n<=12&&r>=1&&r<=(n===2&&DP(i)?29:QP[n])}function Vd(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var fd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Wd(e){return function(i){let n=fd.exec(i);if(!n)return!1;let r=+n[1],o=+n[2],s=+n[3],a=n[4],g=n[5]==="-"?-1:1,l=+(n[6]||0),d=+(n[7]||0);if(l>23||d>59||e&&!a)return!1;if(r<=23&&o<=59&&s<60)return!0;let I=o-d*g,C=r-l*g-(I<0?1:0);return(C===23||C===-1)&&(I===59||I===-1)&&s<61}}function Bd(e,t){if(!(e&&t))return;let i=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(!(i&&n))return;return i-n}function KA(e,t){if(!(e&&t))return;let i=fd.exec(e),n=fd.exec(t);if(!(i&&n))return;if(e=i[1]+i[2]+i[3],t=n[1]+n[2]+n[3],e>t)return 1;if(e<t)return-1;return 0}var yd=/t|\s/i;function jA(e){let t=Wd(e);return function(n){let r=n.split(yd);return r.length===2&&QA(r[0])&&t(r[1])}}function LA(e,t){if(!(e&&t))return;let i=new Date(e).valueOf(),n=new Date(t).valueOf();if(!(i&&n))return;return i-n}function MA(e,t){if(!(e&&t))return;let[i,n]=e.split(yd),[r,o]=t.split(yd),s=Vd(i,r);if(s===void 0)return;return s||Bd(n,o)}var KP=/\/|:/,LP=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function MP(e){return KP.test(e)&&LP.test(e)}var DA=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $P(e){return DA.lastIndex=0,DA.test(e)}var qP=-2147483648,e2=2147483647;function t2(e){return Number.isInteger(e)&&e<=e2&&e>=qP}function i2(e){return Number.isInteger(e)}function _A(){return!0}var n2=/[^\\]\\Z/;function r2(e){if(n2.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var eb=f(function(Rd){Object.defineProperty(Rd,"__esModule",{value:!0});var o2=cl(),s2=wl(),a2=Kl(),g2=Id(),qA=cd(),l2=[o2.default,s2.default,(0,a2.default)(),g2.default,qA.metadataVocabulary,qA.contentVocabulary];Rd.default=l2});var tb=f(function(aD,d2){d2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var nb=f(function(q,Gd){Object.defineProperty(q,"__esModule",{value:!0});q.MissingRefError=q.ValidationError=q.CodeGen=q.Name=q.nil=q.stringify=q.str=q._=q.KeywordCxt=q.Ajv=void 0;var I2=ll(),c2=eb(),u2=pd(),ib=tb(),C2=["/properties"],xs="http://json-schema.org/draft-07/schema";class jr extends I2.default{_addVocabularies(){if(super._addVocabularies(),c2.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(u2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ib,C2):ib;this.addMetaSchema(e,xs,!1),this.refs["http://json-schema.org/schema"]=xs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xs)?xs:void 0)}}q.Ajv=jr;Gd.exports=q=jr;Gd.exports.Ajv=jr;Object.defineProperty(q,"__esModule",{value:!0});q.default=jr;var m2=pn();Object.defineProperty(q,"KeywordCxt",{enumerable:!0,get:function(){return m2.KeywordCxt}});var yn=N();Object.defineProperty(q,"_",{enumerable:!0,get:function(){return yn._}});Object.defineProperty(q,"str",{enumerable:!0,get:function(){return yn.str}});Object.defineProperty(q,"stringify",{enumerable:!0,get:function(){return yn.stringify}});Object.defineProperty(q,"nil",{enumerable:!0,get:function(){return yn.nil}});Object.defineProperty(q,"Name",{enumerable:!0,get:function(){return yn.Name}});Object.defineProperty(q,"CodeGen",{enumerable:!0,get:function(){return yn.CodeGen}});var p2=Gr();Object.defineProperty(q,"ValidationError",{enumerable:!0,get:function(){return p2.default}});var A2=An();Object.defineProperty(q,"MissingRefError",{enumerable:!0,get:function(){return A2.default}})});var rb=f(function(Vn){Object.defineProperty(Vn,"__esModule",{value:!0});Vn.formatLimitDefinition=void 0;var b2=nb(),gt=N(),qt=gt.operators,Ys={formatMaximum:{okStr:"<=",ok:qt.LTE,fail:qt.GT},formatMinimum:{okStr:">=",ok:qt.GTE,fail:qt.LT},formatExclusiveMaximum:{okStr:"<",ok:qt.LT,fail:qt.GTE},formatExclusiveMinimum:{okStr:">",ok:qt.GT,fail:qt.LTE}},Z2={message:({keyword:e,schemaCode:t})=>gt.str`should be ${Ys[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>gt._`{comparison: ${Ys[e].okStr}, limit: ${t}}`};Vn.formatLimitDefinition={keyword:Object.keys(Ys),type:"string",schemaType:"string",$data:!0,error:Z2,code(e){let{gen:t,data:i,schemaCode:n,keyword:r,it:o}=e,{opts:s,self:a}=o;if(!s.validateFormats)return;let g=new b2.KeywordCxt(o,a.RULES.all.format.definition,"format");if(g.$data)l();else d();function l(){let C=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),m=t.const("fmt",gt._`${C}[${g.schemaCode}]`);e.fail$data((0,gt.or)(gt._`typeof ${m} != "object"`,gt._`${m} instanceof RegExp`,gt._`typeof ${m}.compare != "function"`,I(m)))}function d(){let C=g.schema,m=a.formats[C];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw Error(`"${r}": format "${C}" does not define "compare" function`);let A=t.scopeValue("formats",{key:C,ref:m,code:s.code.formats?gt._`${s.code.formats}${(0,gt.getProperty)(C)}`:void 0});e.fail$data(I(A))}function I(C){return gt._`${C}.compare(${i}, ${n}) ${Ys[r].fail} 0`}},dependencies:["format"]};var h2=(e)=>(e.addKeyword(Vn.formatLimitDefinition),e);Vn.default=h2});var gb=f(function(Dr,ab){Object.defineProperty(Dr,"__esModule",{value:!0});var Bn=$A(),f2=rb(),wd=N(),ob=new wd.Name("fullFormats"),W2=new wd.Name("fastFormats"),Fd=(e,t={keywords:!0})=>{if(Array.isArray(t))return sb(e,t,Bn.fullFormats,ob),e;let[i,n]=t.mode==="fast"?[Bn.fastFormats,W2]:[Bn.fullFormats,ob],r=t.formats||Bn.formatNames;if(sb(e,r,i,n),t.keywords)(0,f2.default)(e);return e};Fd.get=(e,t="full")=>{let n=(t==="fast"?Bn.fastFormats:Bn.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function sb(e,t,i,n){var r,o;(r=(o=e.opts.code).formats)!==null&&r!==void 0||(o.formats=wd._`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,i[s])}ab.exports=Dr=Fd;Object.defineProperty(Dr,"__esModule",{value:!0});Dr.default=Fd});var Qf=f(function(c_,_f){_f.exports=rX;function nX(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(i){if(!e[i])e[i]=t[i]}),e}function rX(e){let t=nX(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let i=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(i)&&i!==0)return i}return t.defaultWidth}});var uW=f(function(R_,cW){var ZX=require("stream");class IW extends ZX{#i=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#i!==null)return this.#i;return this.#t("isTTY",!1)}set isTTY(e){this.#i=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}cW.exports=IW});class Gt extends Error{constructor(e,t,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class Ze extends Gt{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Ao{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new Ze(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function bo(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Rc=require("events"),ho=Pe(require("child_process")),It=Pe(require("path")),Kn=Pe(require("fs")),j=Pe(require("process")),Gc=require("util");var Wc=require("util");class Zo{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((n)=>!n._hidden),i=e._getHelpCommand();if(i&&!i._hidden)t.push(i);if(this.sortSubcommands)t.sort((n,r)=>n.name().localeCompare(r.name()));return t}compareOptions(e,t){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);if(!n&&!r)t.push(i);else if(i.long&&!r)t.push(e.createOption(i.long,i.description));else if(i.short&&!n)t.push(e.createOption(i.short,i.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter((r)=>!r.hidden);t.push(...n)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((i)=>bo(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}formatItemList(e,t,i){if(t.length===0)return[];return[i.styleTitle(e),...t,""]}groupItems(e,t,i){let n=new Map;return e.forEach((r)=>{let o=i(r);if(!n.has(o))n.set(o,[])}),t.forEach((r)=>{let o=i(r);if(!n.has(o))n.set(o,[]);n.get(o).push(r)}),n}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function r(d,I){return t.formatItem(d,i,I,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],s=t.commandDescription(e);if(s.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(s),n),""]);let a=t.visibleArguments(e).map((d)=>r(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(d)=>d.helpGroupHeading??"Options:").forEach((d,I)=>{let C=d.map((m)=>r(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));o=o.concat(this.formatItemList(I,C,t))}),t.showGlobalOptions){let d=t.visibleGlobalOptions(e).map((I)=>r(t.styleOptionTerm(t.optionTerm(I)),t.styleOptionDescription(t.optionDescription(I))));o=o.concat(this.formatItemList("Global Options:",d,t))}return this.groupItems(e.commands,t.visibleCommands(e),(d)=>d.helpGroup()||"Commands:").forEach((d,I)=>{let C=d.map((m)=>r(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));o=o.concat(this.formatItemList(I,C,t))}),o.join(`
|
|
11
11
|
`)}displayWidth(e){return Wc.stripVTControlCharacters(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,n){let o=" ".repeat(2);if(!i)return o+e;let s=e.padEnd(t+e.length-n.displayWidth(e)),a=2,l=(this.helpWidth??80)-t-a-2,d;if(l<this.minWidthToWrap||n.preformatted(i))d=i;else d=n.boxWrap(i,l).replace(/\n/g,`
|
|
12
12
|
`+" ".repeat(t+a));return o+s+" ".repeat(a)+d.replace(/\n/g,`
|
|
13
13
|
${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach((o)=>{let s=o.match(n);if(s===null){r.push("");return}let a=[s.shift()],g=this.displayWidth(a[0]);s.forEach((l)=>{let d=this.displayWidth(l);if(g+d<=t){a.push(l),g+=d;return}r.push(a.join(""));let I=l.trimStart();a=[I],g=this.displayWidth(I)}),r.push(a.join(""))}),r.join(`
|
|
@@ -32,11 +32,11 @@ Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycl
|
|
|
32
32
|
`),this.outputHelp({error:!0});let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in j.default.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,j.default.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Fa(this.options),t=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=(o)=>{let s=o.attributeName(),a=this.getOptionValue(s),g=this.options.find((d)=>d.negate&&s===d.attributeName()),l=this.options.find((d)=>!d.negate&&s===d.attributeName());if(g&&(g.presetArg===void 0&&a===!1||g.presetArg!==void 0&&a===g.presetArg))return g;return l||o},n=(o)=>{let s=i(o),a=s.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${s.envVar}'`;return`option '${s.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter((s)=>s.long).map((s)=>s.long);n=n.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);t=Ha(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=e.length,r=this.parent?` for '${this.name()}'`:"",o=e.join(", "),s=`error: too many arguments${r}. Expected ${t} argument${i} but got ${n}: ${o}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((r)=>{if(n.push(r.name()),r.alias())n.push(r.alias())}),t=Ha(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
33
33
|
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((i)=>bo(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=It.default.basename(e,It.default.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=t.formatHelp(this,t);if(i.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,i,n,r;if(t)i=(s)=>this._outputConfiguration.writeErr(s),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth();else i=(s)=>this._outputConfiguration.writeOut(s),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(s)=>{if(!n)s=this._outputConfiguration.stripColor(s);return i(s)},hasColors:n,helpWidth:r}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(i.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(j.default.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
34
34
|
Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{let o;if(typeof t==="function")o=t({error:r.error,command:r.command});else o=t;if(o)r.write(`${o}
|
|
35
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Vc(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)i=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=o[1],/^\d+$/.test(o[3]))r=o[3];else n=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=o[1],n=o[3],r=o[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function Bc(){if(j.default.env.NO_COLOR||j.default.env.FORCE_COLOR==="0"||j.default.env.FORCE_COLOR==="false")return!1;if(j.default.env.FORCE_COLOR||j.default.env.CLICOLOR_FORCE!==void 0)return!0;return}var eT=new Oi;var pC=require("crypto"),mi=require("fs/promises"),_o=require("path");var zi=require("path");function Fc(){let e=IV();return async(t)=>{for(let i of t)i.module=e(i.filename);return t}}function IV(e=process.argv[1]?zi.dirname(process.argv[1]):process.cwd(),t=zi.sep==="\\"){let i=t?wc(e):e;return(n)=>{if(!n)return;let r=t?wc(n):n,{dir:o,base:s,ext:a}=zi.posix.parse(r);if(a===".js"||a===".mjs"||a===".cjs")s=s.slice(0,-1*a.length);let g=decodeURIComponent(s);if(!o)o=".";let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${g}`;if(o.startsWith(i)){let d=o.slice(i.length+1).replace(/\//g,".");return d?`${d}:${g}`:g}return g}}function wc(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var va=(e)=>{if("flags"in e){let t=Hc(e.flags),i=vc(e.flags);return{...e,featureFlags:t,featureFlagPayloads:i}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([r,o])=>[r,fo(o)])),n=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,cV(r,o,i[r])]));return{...e,featureFlags:t,featureFlagPayloads:i,flags:n}}};function cV(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 Hc=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,i])=>[t,Ln(i)]).filter(([,t])=>t!==void 0)),vc=(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?fo(n):void 0]}))},Ln=(e)=>e===void 0?void 0:e.variant??e.enabled,fo=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var uV=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Mn=(e,t=[])=>{let i={},n=(r)=>{if(e[r]!==void 0)i[r]=e[r]};return uV.forEach(n),t.forEach(n),i};var Ue=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function ka(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var mV="NativeGzipValidationError",pV=31,AV=139,bV=8,ZV=(e)=>e.length>=2&&e[0]===pV&&e[1]===AV;var $n,hV=()=>{if($n)return $n;$n=[];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;$n[e]=t>>>0}return $n},fV=(e)=>{let t=hV(),i=4294967295;for(let n=0;n<e.length;n++)i=t[(i^e[n])&255]^i>>>8;return(4294967295^i)>>>0},Wo=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=mV,t},WV=async(e,t)=>{if(e.size<18)Wo("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!ZV(i)||i[2]!==bV)Wo("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());if(n.getUint32(0,!0)!==fV(t))Wo("invalid-crc");let r=t.length>>>0;if(n.getUint32(4,!0)!==r)Wo("invalid-size")};async function gi(e,t=!0,i){try{let n=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),o=r.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async(l)=>{try{await o.abort(l)}catch{}throw l}),a=new Response(r.readable).blob(),[g]=await Promise.all([a,s]);return await WV(g,n),g}catch(n){if(i?.rethrow)throw n;if(t)console.error("Failed to gzip compress data",n);return null}}var yV=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],kc=function(e,t=[]){if(!e)return!1;let i=e.toLowerCase();return yV.concat(t).some((n)=>{let r=n.toLowerCase();return i.indexOf(r)!==-1})};function ji(e){let t=[];return JSON.stringify(e,function(i,n){if(typeof n=="bigint")return n.toString();if(typeof n=="function"||typeof n=="symbol")return;if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n})??"null"}var BV=Array.isArray,Pc=Object.prototype,uT=Pc.hasOwnProperty,yo=Pc.toString,ct=BV||function(e){return yo.call(e)==="[object Array]"};var qn=(e)=>e===Object(e)&&!ct(e);var li=(e)=>e===void 0,wt=(e)=>yo.call(e)=="[object String]",Nc=(e)=>wt(e)&&e.trim().length===0,xc=(e)=>e===null;var er=(e)=>yo.call(e)=="[object Number]"&&e===e;var Yc=(e)=>yo.call(e)==="[object Boolean]";var Sc=(e)=>e instanceof Error;function Vo(e){return e===null||typeof e!="object"}function di(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Xc(e){return di(e,"ErrorEvent")}function Di(e){return typeof Event<"u"&&RV(e,Event)}function Ec(e){return di(e,"Object")}function RV(e,t){try{return e instanceof t}catch{return!1}}function tr(e,t,i,n,r){if(t>i)n.warn("min cannot be greater than max."),t=i;if(er(e))if(e>i)return n.warn(" cannot be greater than max: "+i+". Using max value instead."),i;else{if(!(e<t))return e;return n.warn(" cannot be less than min: "+t+". Using min value instead."),t}return n.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),tr(r||i,t,i,n)}var GV=86400000,wV=1,FV=10;function Tc(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??wV,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??FV}}class Pa{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=tr(e.bucketSize,0,100,e._logger),this._refillRate=tr(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=tr(e.refillInterval,0,GV,e._logger)}_applyRefill(e,t){let i=t-e.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let r=n*this._refillRate;e.tokens=Math.min(e.tokens+r,this._bucketSize),e.lastAccess=e.lastAccess+n*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),i=String(e),n=this._buckets[i];if(n)this._applyRefill(n,t);else n={tokens:this._bucketSize,lastAccess:t},this._buckets[i]=n;if(n.tokens===0)return!0;if(n.tokens--,n.tokens===0)this._onBucketRateLimited?.(e);return n.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Ii{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Ii(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(n)||e<0||t<0||i<0||n<0||e>281474976710655||t>4095||i>1073741823||n>4294967295)throw RangeError("invalid field value");let r=new Uint8Array(16);return r[0]=e/1099511627776,r[1]=e/4294967296,r[2]=e/16777216,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new Ii(r)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let r=parseInt(t.substring(2*n,2*n+8),16);i[n+0]=r>>>24,i[n+1]=r>>>16,i[n+2]=r>>>8,i[n+3]=r}return new Ii(i)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Ii(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let i=this.bytes[t]-e.bytes[t];if(i!==0)return Math.sign(i)}return 0}}class Uc{constructor(e){this.timestamp=0,this.counter=0,this.random=e??HV()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let i=this.generateOrAbortCore(e,t);if(i===void 0)this.timestamp=0,i=this.generateOrAbortCore(e,t);return i}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Ii.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Ii.ofInner(e)}}var HV=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Jc,Oe=()=>vV().toString(),vV=()=>(Jc||(Jc=new Uc)).generate();class Na{add(e){let t=Oe(),i=++this.nextId;return this.promiseByIds[t]={id:i,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length}getPromises(e=[],t=this.nextId){let i=new Set(e);return Object.values(this.promiseByIds).filter((n)=>n.id<=t&&!i.has(n.promise)).map((n)=>n.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function kV(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Oc=(e,t,i)=>{function n(o,...s){t(()=>{let a=i[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{i.error(e,...o)},createLogger:(o)=>Oc(`${e} ${o}`,t,i)}},PV=(e)=>e();function zc(e,t=PV){return Oc(e,t,kV())}var Qi="Mobile",Ro="iOS",_i="Android",Kc="Tablet",BT=_i+" "+Kc;var xV="Apple",RT=xV+" Watch",Lc="Safari",Go="BlackBerry",Mc="Samsung",YV=Mc+"Browser",SV=Mc+" Internet",wo="Chrome",XV=wo+" OS",EV=wo+" "+Ro,$c="Internet Explorer",TV=$c+" "+Qi,Ya="Opera",GT=Ya+" Mini",qc="Edge",JV="Microsoft "+qc,Sa="Firefox",UV=Sa+" "+Ro,Xa="Nintendo",Ea="PlayStation",Bo="Xbox",OV=_i+" "+Qi,zV=Qi+" "+Lc,ir="Windows",jV=ir+" Phone";var eu="Generic",wT=eu+" "+Qi.toLowerCase(),FT=eu+" "+Kc.toLowerCase(),DV="Konqueror",_V="Oculus Browser",jc="Vivaldi",QV="Yandex",Dc="Whale",KV="DuckDuckGo",LV="Pale Moon",_c="Waterfox",Qc="Brave",MV="Google Search App",ee="(\\d+(\\.\\d+)?)",xa=new RegExp("Version/"+ee);var HT=new RegExp(Bo,"i"),vT=new RegExp(Ea+" \\w+","i"),kT=new RegExp(Xa+" \\w+","i"),$V=new RegExp(Go+"|PlayBook|BB10","i"),qV={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var PT={[TV]:[new RegExp("rv:"+ee)],[JV]:[new RegExp(qc+"?\\/"+ee)],[wo]:[new RegExp("("+wo+"|CrMo)\\/"+ee)],[EV]:[new RegExp("CriOS\\/"+ee)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ee)],[Lc]:[xa],[zV]:[xa],[Ya]:[new RegExp("("+Ya+"|OPR)\\/"+ee)],[Sa]:[new RegExp(Sa+"\\/"+ee)],[UV]:[new RegExp("FxiOS\\/"+ee)],[DV]:[new RegExp("Konqueror[:/]?"+ee,"i")],[Go]:[new RegExp(Go+" "+ee),xa],[OV]:[new RegExp("android\\s"+ee,"i")],[SV]:[new RegExp(YV+"\\/"+ee)],[_V]:[new RegExp("OculusBrowser\\/"+ee)],[jc]:[new RegExp(jc+"\\/"+ee)],[QV]:[new RegExp("YaBrowser\\/"+ee)],[Dc]:[new RegExp(Dc+"\\/"+ee)],[Qc]:[new RegExp(Qc+"\\/"+ee)],[KV]:[new RegExp("(DuckDuckGo|Ddg)\\/"+ee)],[LV]:[new RegExp("PaleMoon\\/"+ee)],[_c]:[new RegExp(_c+"\\/"+ee)],[MV]:[new RegExp("GSA\\/"+ee)],[$c]:[new RegExp("(rv:|MSIE )"+ee)],Mozilla:[new RegExp("rv:"+ee)]};var NT=[[new RegExp(Bo+"; "+Bo+" (.*?)[);]","i"),(e)=>[Bo,e&&e[1]||""]],[new RegExp(Xa,"i"),[Xa,""]],[new RegExp(Ea,"i"),[Ea,""]],[$V,[Go,""]],[new RegExp(ir,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[jV,""];if(new RegExp(Qi).test(t)&&!/IEMobile\b/.test(t))return[ir+" "+Qi,""];let i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){let n=i[1],r=qV[n]||"";if(/arm/i.test(t))r="RT";return[ir,r]}return[ir,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Ro,t.join(".")]}return[Ro,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=li(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+_i+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+_i+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[_i,t.join(".")]}return[_i,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let i=[e[1],e[2],e[3]||"0"];t[1]=i.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[XV,""]],[/Linux|debian/i,["Linux",""]]];var tu="utf8",eB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tB(e){return typeof e=="string"&&eB.test(e)}function Fo(e,t){return tB(e)?e:t()}function iu(e){return e?.replace(/\/+$/,"")}async function nu(e,t){let i=null;for(let n=0;n<t.retryCount+1;n++){if(n>0)await new Promise((r)=>setTimeout(r,t.retryDelay));try{return await e()}catch(r){if(i=r,!t.retryCheck(r))throw r}}throw i}function Ta(){return new Date().toISOString()}function he(e,t){let i=setTimeout(e,t);return i?.unref&&i?.unref(),i}var ru=(e)=>e instanceof Error;function Ja(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((i)=>({status:"fulfilled",value:i}),(i)=>({status:"rejected",reason:i}))))}var nB={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}},DT=nB.info;function Ua(e){if(Yc(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(ct(e))return{arrayValue:{values:e.map((t)=>Ua(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function nr(e){let t=[];for(let i in e){let n=e[i];if(!(xc(n)||li(n)))t.push({key:i,value:Ua(n)})}return t}var rr=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Oa(e){return String(e)+"000000"}function za(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 ou(e,t){for(let i=0;i<t.length;i++)if(e<=t[i])return i;return t.length}function ja(e,t,i){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":i}}function Da(e,t,i,n){return{resourceMetrics:[{resource:{attributes:nr(t)},scopeMetrics:[{scope:{name:i,version:n},metrics:e}]}]}}function Ho(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 su=1;class vo{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:i?.unit,attributes:i?.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:i?.unit,attributes:i?.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:i?.unit,attributes:i?.attributes})}flush(){let e=this._flushPromise,i=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===i)this._flushPromise=null});return this._flushPromise=i,i}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let i,n;try{i=t.attributes?{...t.attributes}:void 0,n=za(t.type,t.name,t.unit,i)}catch(s){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,s);return}let r=this._series.get(n);if(!r){if(!this._admitNewSeries())return;r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now()},this._series.set(n,r)}let o=this._typeByName.get(t.name);if(o===void 0)this._typeByName.set(t.name,t.type);else if(o!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(r,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(rr.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[ou(t,rr)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let i=ct(t)?t:[t],n=e;for(let r of i)try{let o=r(n);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;n=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return n}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=he(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,i=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(i.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",i.error);return}}_buildPayload(e){return Da(this._buildMetrics(e),ja(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Oa(Date.now()),i=new Map;for(let n of e.values()){let r=za(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:su,isMonotonic:!0,dataPoints:[]};else if(n.type==="gauge")o.gauge={dataPoints:[]};else o.histogram={aggregationTemporality:su,dataPoints:[]};i.set(r,o)}let s=nr(n.attributes??{}),a=Oa(n.windowStartMs);if(n.type==="count"){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,asDouble:n.total??0};o.sum.dataPoints.push(g)}else if(n.type==="gauge"){let g={attributes:s,timeUnixNano:t,asDouble:n.last??0};o.gauge.dataPoints.push(g)}else if(n.hist){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:rr};o.histogram.dataPoints.push(g)}}return Array.from(i.values())}_mergeWindowBack(e){for(let[t,i]of e){let n=this._series.get(t);if(!n){if(this._admitNewSeries())this._series.set(t,i);continue}switch(n.windowStartMs=Math.min(n.windowStartMs,i.windowStartMs),n.type){case"count":n.total=(n.total??0)+(i.total??0);break;case"gauge":break;case"histogram":if(i.hist)if(n.hist){n.hist.count+=i.hist.count,n.hist.sum+=i.hist.sum,n.hist.min=Math.min(n.hist.min,i.hist.min),n.hist.max=Math.max(n.hist.max,i.hist.max);for(let r=0;r<n.hist.bucketCounts.length;r++)n.hist.bucketCounts[r]+=i.hist.bucketCounts[r]}else n.hist=i.hist;break}}}}class _a{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((i)=>i!==t)}}emit(e,t){for(let i of this.events[e]||[])i(t);for(let i of this.events["*"]||[])i(e,t)}}var Ne={};gV(Ne,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Jo,DOMExceptionCoercer:()=>bu,EXCEPTION_STEP_INTERNAL_FIELDS:()=>or,ErrorCoercer:()=>Yo,ErrorEventCoercer:()=>Zu,ErrorPropertiesBuilder:()=>No,EventCoercer:()=>fu,ExceptionStepsBuffer:()=>Vu,ObjectCoercer:()=>Eo,PrimitiveCoercer:()=>To,PromiseRejectionEventCoercer:()=>Wu,ReduceableCache:()=>yu,StringCoercer:()=>So,chromeStackLineParser:()=>Qa,createDefaultStackParser:()=>La,createStackParser:()=>Au,geckoStackLineParser:()=>Ka,getUtf8ByteLength:()=>Bu,nodeStackLineParser:()=>uu,opera10StackLineParser:()=>du,opera11StackLineParser:()=>Iu,resolveExceptionStepsConfig:()=>Ma,reverseAndStripFrames:()=>pu,stripReservedExceptionStepFields:()=>BB,winjsStackLineParser:()=>lu});var ko,au,Po;function gu(e){let t=globalThis._posthogChunkIds;if(!t)return;let i=Object.keys(t);if(Po&&i.length===au)return Po;return au=i.length,Po=i.reduce((n,r)=>{if(!ko)ko={};let o=ko[r];if(o)n[o[0]]=o[1];else{let s=e(r);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,d=t[r];if(l&&d){n[l]=d,ko[r]=[l,d];break}}}return n},{}),Po}var aB=4;class No{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(o,s);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&ct(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let i;if(e.cause!=null)i=this.parseStacktrace(e.cause,t);let n;if(e.stack!=""&&e.stack!=null)n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:i,stack:n}}applyChunkIds(e,t){return e.map((i)=>{if(i.filename&&t)i.chunk_id=t[i.filename];return i})}applyCoercers(e,t){for(let i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let i of this.modifiers)t=await i(t);return t}convertToExceptionList(e,t){let i={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)i.stacktrace={type:"raw",frames:e.stack};let n=[i];if(e.cause!=null)n.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return n}buildParsingContext(e){return{chunkIdMap:gu(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,i=0){let n=(o,s)=>{if(!(s<=aB))return;{let a=this.buildCoercingContext(e,t,s);return this.applyCoercers(o,a)}};return{...t,syntheticException:i==0?t.syntheticException:void 0,mechanism:e,apply:(o)=>n(o,i),next:(o)=>n(o,i+1)}}}var ce="?";function ut(e,t,i,n,r){let o={platform:e,filename:t,function:i==="<anonymous>"?ce:i,in_app:!0};if(!li(n))o.lineno=n;if(!li(r))o.colno=r;return o}var xo=(e,t)=>{let i=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return i||n?[e.indexOf("@")!==-1?e.split("@")[0]:ce,i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var gB=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lB=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dB=/\((\S*)(?::(\d+))(?::(\d+))\)/,Qa=(e,t)=>{let i=gB.exec(e);if(i){let[,r,o,s]=i;return ut(t,r,ce,+o,+s)}let n=lB.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=dB.exec(n[2]);if(a)n[2]=a[1],n[3]=a[2],n[4]=a[3]}let[o,s]=xo(n[1]||ce,n[2]);return ut(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var IB=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,cB=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ka=(e,t)=>{let i=IB.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){let s=cB.exec(i[3]);if(s)i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]=""}let r=i[3],o=i[1]||ce;return[o,r]=xo(o,r),ut(t,r,o,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}};var uB=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,lu=(e,t)=>{let i=uB.exec(e);return i?ut(t,i[2],i[1]||ce,+i[3],i[4]?+i[4]:void 0):void 0};var CB=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,du=(e,t)=>{let i=CB.exec(e);return i?ut(t,i[2],i[3]||ce,+i[1]):void 0},mB=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Iu=(e,t)=>{let i=mB.exec(e);return i?ut(t,i[5],i[3]||i[4]||ce,+i[1],+i[2]):void 0};var pB=/^\s*[-]{4,}$/,AB=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,bB=/^Promise\.(?:all|any)$/,ZB=/^index \d+$/,hB="node:internal/promise",uu=(e,t)=>{let i=e.match(AB);if(i){let n,r,o,s,a;if(i[1]){o=i[1];let d=o.lastIndexOf(".");if(o[d-1]===".")d--;if(d>0){n=o.slice(0,d),r=o.slice(d+1);let I=n.indexOf(".Module");if(I>0)o=o.slice(I+1),n=n.slice(0,I)}s=void 0}if(r)s=n,a=r;if(r==="<anonymous>")a=void 0,o=void 0;if(o===void 0)a=a||ce,o=s?`${s}.${a}`:a;let g=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";if(g?.match(/\/[A-Z]:/))g=g.slice(1);if(!g&&i[5]&&!l)g=i[5];if(bB.test(o)&&ZB.test(g||""))g=hB;return{filename:g?decodeURI(g):void 0,module:void 0,function:o,lineno:cu(i[3]),colno:cu(i[4]),in_app:fB(g||"",l),platform:t}}if(e.match(pB))return{filename:e,platform:t}};function fB(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function cu(e){return parseInt(e||"",10)||void 0}var Cu=/\(error: (.*)\)/,mu=50;function pu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,mu).map((i)=>({...i,filename:i.filename||WB(t).filename,function:i.function||ce}))}function WB(e){return e[e.length-1]||{}}function La(){return Au("web:javascript",Qa,Ka)}function Au(e,...t){return(i,n=0)=>{let r=[],o=i.split(`
|
|
35
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Vc(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)i=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=o[1],/^\d+$/.test(o[3]))r=o[3];else n=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=o[1],n=o[3],r=o[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function Bc(){if(j.default.env.NO_COLOR||j.default.env.FORCE_COLOR==="0"||j.default.env.FORCE_COLOR==="false")return!1;if(j.default.env.FORCE_COLOR||j.default.env.CLICOLOR_FORCE!==void 0)return!0;return}var tT=new Oi;var pC=require("crypto"),mi=require("fs/promises"),_o=require("path");var zi=require("path");function Fc(){let e=IV();return async(t)=>{for(let i of t)i.module=e(i.filename);return t}}function IV(e=process.argv[1]?zi.dirname(process.argv[1]):process.cwd(),t=zi.sep==="\\"){let i=t?wc(e):e;return(n)=>{if(!n)return;let r=t?wc(n):n,{dir:o,base:s,ext:a}=zi.posix.parse(r);if(a===".js"||a===".mjs"||a===".cjs")s=s.slice(0,-1*a.length);let g=decodeURIComponent(s);if(!o)o=".";let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${g}`;if(o.startsWith(i)){let d=o.slice(i.length+1).replace(/\//g,".");return d?`${d}:${g}`:g}return g}}function wc(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var va=(e)=>{if("flags"in e){let t=Hc(e.flags),i=vc(e.flags);return{...e,featureFlags:t,featureFlagPayloads:i}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([r,o])=>[r,fo(o)])),n=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,cV(r,o,i[r])]));return{...e,featureFlags:t,featureFlagPayloads:i,flags:n}}};function cV(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 Hc=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,i])=>[t,Ln(i)]).filter(([,t])=>t!==void 0)),vc=(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?fo(n):void 0]}))},Ln=(e)=>e===void 0?void 0:e.variant??e.enabled,fo=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var uV=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Mn=(e,t=[])=>{let i={},n=(r)=>{if(e[r]!==void 0)i[r]=e[r]};return uV.forEach(n),t.forEach(n),i};var Ue=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function ka(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var mV="NativeGzipValidationError",pV=31,AV=139,bV=8,ZV=(e)=>e.length>=2&&e[0]===pV&&e[1]===AV;var $n,hV=()=>{if($n)return $n;$n=[];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;$n[e]=t>>>0}return $n},fV=(e)=>{let t=hV(),i=4294967295;for(let n=0;n<e.length;n++)i=t[(i^e[n])&255]^i>>>8;return(4294967295^i)>>>0},Wo=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=mV,t},WV=async(e,t)=>{if(e.size<18)Wo("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!ZV(i)||i[2]!==bV)Wo("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());if(n.getUint32(0,!0)!==fV(t))Wo("invalid-crc");let r=t.length>>>0;if(n.getUint32(4,!0)!==r)Wo("invalid-size")};async function gi(e,t=!0,i){try{let n=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),o=r.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async(l)=>{try{await o.abort(l)}catch{}throw l}),a=new Response(r.readable).blob(),[g]=await Promise.all([a,s]);return await WV(g,n),g}catch(n){if(i?.rethrow)throw n;if(t)console.error("Failed to gzip compress data",n);return null}}var yV=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],kc=function(e,t=[]){if(!e)return!1;let i=e.toLowerCase();return yV.concat(t).some((n)=>{let r=n.toLowerCase();return i.indexOf(r)!==-1})};function ji(e){let t=[];return JSON.stringify(e,function(i,n){if(typeof n=="bigint")return n.toString();if(typeof n=="function"||typeof n=="symbol")return;if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n})??"null"}var BV=Array.isArray,Pc=Object.prototype,CT=Pc.hasOwnProperty,yo=Pc.toString,ct=BV||function(e){return yo.call(e)==="[object Array]"};var qn=(e)=>e===Object(e)&&!ct(e);var li=(e)=>e===void 0,wt=(e)=>yo.call(e)=="[object String]",Nc=(e)=>wt(e)&&e.trim().length===0,xc=(e)=>e===null;var er=(e)=>yo.call(e)=="[object Number]"&&e===e;var Yc=(e)=>yo.call(e)==="[object Boolean]";var Sc=(e)=>e instanceof Error;function Vo(e){return e===null||typeof e!="object"}function di(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Xc(e){return di(e,"ErrorEvent")}function Di(e){return typeof Event<"u"&&RV(e,Event)}function Ec(e){return di(e,"Object")}function RV(e,t){try{return e instanceof t}catch{return!1}}function tr(e,t,i,n,r){if(t>i)n.warn("min cannot be greater than max."),t=i;if(er(e))if(e>i)return n.warn(" cannot be greater than max: "+i+". Using max value instead."),i;else{if(!(e<t))return e;return n.warn(" cannot be less than min: "+t+". Using min value instead."),t}return n.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),tr(r||i,t,i,n)}var GV=86400000,wV=1,FV=10;function Tc(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??wV,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??FV}}class Pa{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=tr(e.bucketSize,0,100,e._logger),this._refillRate=tr(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=tr(e.refillInterval,0,GV,e._logger)}_applyRefill(e,t){let i=t-e.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let r=n*this._refillRate;e.tokens=Math.min(e.tokens+r,this._bucketSize),e.lastAccess=e.lastAccess+n*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),i=String(e),n=this._buckets[i];if(n)this._applyRefill(n,t);else n={tokens:this._bucketSize,lastAccess:t},this._buckets[i]=n;if(n.tokens===0)return!0;if(n.tokens--,n.tokens===0)this._onBucketRateLimited?.(e);return n.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Ii{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Ii(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(n)||e<0||t<0||i<0||n<0||e>281474976710655||t>4095||i>1073741823||n>4294967295)throw RangeError("invalid field value");let r=new Uint8Array(16);return r[0]=e/1099511627776,r[1]=e/4294967296,r[2]=e/16777216,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new Ii(r)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let r=parseInt(t.substring(2*n,2*n+8),16);i[n+0]=r>>>24,i[n+1]=r>>>16,i[n+2]=r>>>8,i[n+3]=r}return new Ii(i)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Ii(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let i=this.bytes[t]-e.bytes[t];if(i!==0)return Math.sign(i)}return 0}}class Uc{constructor(e){this.timestamp=0,this.counter=0,this.random=e??HV()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let i=this.generateOrAbortCore(e,t);if(i===void 0)this.timestamp=0,i=this.generateOrAbortCore(e,t);return i}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Ii.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Ii.ofInner(e)}}var HV=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Jc,Oe=()=>vV().toString(),vV=()=>(Jc||(Jc=new Uc)).generate();class Na{add(e){let t=Oe(),i=++this.nextId;return this.promiseByIds[t]={id:i,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((i)=>i.promise),t=e.length}getPromises(e=[],t=this.nextId){let i=new Set(e);return Object.values(this.promiseByIds).filter((n)=>n.id<=t&&!i.has(n.promise)).map((n)=>n.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function kV(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Oc=(e,t,i)=>{function n(o,...s){t(()=>{let a=i[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{i.error(e,...o)},createLogger:(o)=>Oc(`${e} ${o}`,t,i)}},PV=(e)=>e();function zc(e,t=PV){return Oc(e,t,kV())}var Qi="Mobile",Ro="iOS",_i="Android",Kc="Tablet",RT=_i+" "+Kc;var xV="Apple",GT=xV+" Watch",Lc="Safari",Go="BlackBerry",Mc="Samsung",YV=Mc+"Browser",SV=Mc+" Internet",wo="Chrome",XV=wo+" OS",EV=wo+" "+Ro,$c="Internet Explorer",TV=$c+" "+Qi,Ya="Opera",wT=Ya+" Mini",qc="Edge",JV="Microsoft "+qc,Sa="Firefox",UV=Sa+" "+Ro,Xa="Nintendo",Ea="PlayStation",Bo="Xbox",OV=_i+" "+Qi,zV=Qi+" "+Lc,ir="Windows",jV=ir+" Phone";var eu="Generic",FT=eu+" "+Qi.toLowerCase(),HT=eu+" "+Kc.toLowerCase(),DV="Konqueror",_V="Oculus Browser",jc="Vivaldi",QV="Yandex",Dc="Whale",KV="DuckDuckGo",LV="Pale Moon",_c="Waterfox",Qc="Brave",MV="Google Search App",ee="(\\d+(\\.\\d+)?)",xa=new RegExp("Version/"+ee);var vT=new RegExp(Bo,"i"),kT=new RegExp(Ea+" \\w+","i"),PT=new RegExp(Xa+" \\w+","i"),$V=new RegExp(Go+"|PlayBook|BB10","i"),qV={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var NT={[TV]:[new RegExp("rv:"+ee)],[JV]:[new RegExp(qc+"?\\/"+ee)],[wo]:[new RegExp("("+wo+"|CrMo)\\/"+ee)],[EV]:[new RegExp("CriOS\\/"+ee)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ee)],[Lc]:[xa],[zV]:[xa],[Ya]:[new RegExp("("+Ya+"|OPR)\\/"+ee)],[Sa]:[new RegExp(Sa+"\\/"+ee)],[UV]:[new RegExp("FxiOS\\/"+ee)],[DV]:[new RegExp("Konqueror[:/]?"+ee,"i")],[Go]:[new RegExp(Go+" "+ee),xa],[OV]:[new RegExp("android\\s"+ee,"i")],[SV]:[new RegExp(YV+"\\/"+ee)],[_V]:[new RegExp("OculusBrowser\\/"+ee)],[jc]:[new RegExp(jc+"\\/"+ee)],[QV]:[new RegExp("YaBrowser\\/"+ee)],[Dc]:[new RegExp(Dc+"\\/"+ee)],[Qc]:[new RegExp(Qc+"\\/"+ee)],[KV]:[new RegExp("(DuckDuckGo|Ddg)\\/"+ee)],[LV]:[new RegExp("PaleMoon\\/"+ee)],[_c]:[new RegExp(_c+"\\/"+ee)],[MV]:[new RegExp("GSA\\/"+ee)],[$c]:[new RegExp("(rv:|MSIE )"+ee)],Mozilla:[new RegExp("rv:"+ee)]};var xT=[[new RegExp(Bo+"; "+Bo+" (.*?)[);]","i"),(e)=>[Bo,e&&e[1]||""]],[new RegExp(Xa,"i"),[Xa,""]],[new RegExp(Ea,"i"),[Ea,""]],[$V,[Go,""]],[new RegExp(ir,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[jV,""];if(new RegExp(Qi).test(t)&&!/IEMobile\b/.test(t))return[ir+" "+Qi,""];let i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){let n=i[1],r=qV[n]||"";if(/arm/i.test(t))r="RT";return[ir,r]}return[ir,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Ro,t.join(".")]}return[Ro,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=li(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+_i+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+_i+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[_i,t.join(".")]}return[_i,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let i=[e[1],e[2],e[3]||"0"];t[1]=i.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[XV,""]],[/Linux|debian/i,["Linux",""]]];var tu="utf8",eB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tB(e){return typeof e=="string"&&eB.test(e)}function Fo(e,t){return tB(e)?e:t()}function iu(e){return e?.replace(/\/+$/,"")}async function nu(e,t){let i=null;for(let n=0;n<t.retryCount+1;n++){if(n>0)await new Promise((r)=>setTimeout(r,t.retryDelay));try{return await e()}catch(r){if(i=r,!t.retryCheck(r))throw r}}throw i}function Ta(){return new Date().toISOString()}function he(e,t){let i=setTimeout(e,t);return i?.unref&&i?.unref(),i}var ru=(e)=>e instanceof Error;function Ja(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((i)=>({status:"fulfilled",value:i}),(i)=>({status:"rejected",reason:i}))))}var nB={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}},_T=nB.info;function Ua(e){if(Yc(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(ct(e))return{arrayValue:{values:e.map((t)=>Ua(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function nr(e){let t=[];for(let i in e){let n=e[i];if(!(xc(n)||li(n)))t.push({key:i,value:Ua(n)})}return t}var rr=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Oa(e){return String(e)+"000000"}function za(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 ou(e,t){for(let i=0;i<t.length;i++)if(e<=t[i])return i;return t.length}function ja(e,t,i){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":i}}function Da(e,t,i,n){return{resourceMetrics:[{resource:{attributes:nr(t)},scopeMetrics:[{scope:{name:i,version:n},metrics:e}]}]}}function Ho(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 su=1;class vo{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:i?.unit,attributes:i?.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:i?.unit,attributes:i?.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:i?.unit,attributes:i?.attributes})}flush(){let e=this._flushPromise,i=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===i)this._flushPromise=null});return this._flushPromise=i,i}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let i,n;try{i=t.attributes?{...t.attributes}:void 0,n=za(t.type,t.name,t.unit,i)}catch(s){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,s);return}let r=this._series.get(n);if(!r){if(!this._admitNewSeries())return;r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now()},this._series.set(n,r)}let o=this._typeByName.get(t.name);if(o===void 0)this._typeByName.set(t.name,t.type);else if(o!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(r,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(rr.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[ou(t,rr)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let i=ct(t)?t:[t],n=e;for(let r of i)try{let o=r(n);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;n=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return n}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=he(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,i=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(i.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",i.error);return}}_buildPayload(e){return Da(this._buildMetrics(e),ja(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Oa(Date.now()),i=new Map;for(let n of e.values()){let r=za(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:su,isMonotonic:!0,dataPoints:[]};else if(n.type==="gauge")o.gauge={dataPoints:[]};else o.histogram={aggregationTemporality:su,dataPoints:[]};i.set(r,o)}let s=nr(n.attributes??{}),a=Oa(n.windowStartMs);if(n.type==="count"){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,asDouble:n.total??0};o.sum.dataPoints.push(g)}else if(n.type==="gauge"){let g={attributes:s,timeUnixNano:t,asDouble:n.last??0};o.gauge.dataPoints.push(g)}else if(n.hist){let g={attributes:s,startTimeUnixNano:a,timeUnixNano:t,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:rr};o.histogram.dataPoints.push(g)}}return Array.from(i.values())}_mergeWindowBack(e){for(let[t,i]of e){let n=this._series.get(t);if(!n){if(this._admitNewSeries())this._series.set(t,i);continue}switch(n.windowStartMs=Math.min(n.windowStartMs,i.windowStartMs),n.type){case"count":n.total=(n.total??0)+(i.total??0);break;case"gauge":break;case"histogram":if(i.hist)if(n.hist){n.hist.count+=i.hist.count,n.hist.sum+=i.hist.sum,n.hist.min=Math.min(n.hist.min,i.hist.min),n.hist.max=Math.max(n.hist.max,i.hist.max);for(let r=0;r<n.hist.bucketCounts.length;r++)n.hist.bucketCounts[r]+=i.hist.bucketCounts[r]}else n.hist=i.hist;break}}}}class _a{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((i)=>i!==t)}}emit(e,t){for(let i of this.events[e]||[])i(t);for(let i of this.events["*"]||[])i(e,t)}}var Ne={};gV(Ne,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Jo,DOMExceptionCoercer:()=>bu,EXCEPTION_STEP_INTERNAL_FIELDS:()=>or,ErrorCoercer:()=>Yo,ErrorEventCoercer:()=>Zu,ErrorPropertiesBuilder:()=>No,EventCoercer:()=>fu,ExceptionStepsBuffer:()=>Vu,ObjectCoercer:()=>Eo,PrimitiveCoercer:()=>To,PromiseRejectionEventCoercer:()=>Wu,ReduceableCache:()=>yu,StringCoercer:()=>So,chromeStackLineParser:()=>Qa,createDefaultStackParser:()=>La,createStackParser:()=>Au,geckoStackLineParser:()=>Ka,getUtf8ByteLength:()=>Bu,nodeStackLineParser:()=>uu,opera10StackLineParser:()=>du,opera11StackLineParser:()=>Iu,resolveExceptionStepsConfig:()=>Ma,reverseAndStripFrames:()=>pu,stripReservedExceptionStepFields:()=>BB,winjsStackLineParser:()=>lu});var ko,au,Po;function gu(e){let t=globalThis._posthogChunkIds;if(!t)return;let i=Object.keys(t);if(Po&&i.length===au)return Po;return au=i.length,Po=i.reduce((n,r)=>{if(!ko)ko={};let o=ko[r];if(o)n[o[0]]=o[1];else{let s=e(r);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,d=t[r];if(l&&d){n[l]=d,ko[r]=[l,d];break}}}return n},{}),Po}var aB=4;class No{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(o,s);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&ct(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let i;if(e.cause!=null)i=this.parseStacktrace(e.cause,t);let n;if(e.stack!=""&&e.stack!=null)n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:i,stack:n}}applyChunkIds(e,t){return e.map((i)=>{if(i.filename&&t)i.chunk_id=t[i.filename];return i})}applyCoercers(e,t){for(let i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let i of this.modifiers)t=await i(t);return t}convertToExceptionList(e,t){let i={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)i.stacktrace={type:"raw",frames:e.stack};let n=[i];if(e.cause!=null)n.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return n}buildParsingContext(e){return{chunkIdMap:gu(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,i=0){let n=(o,s)=>{if(!(s<=aB))return;{let a=this.buildCoercingContext(e,t,s);return this.applyCoercers(o,a)}};return{...t,syntheticException:i==0?t.syntheticException:void 0,mechanism:e,apply:(o)=>n(o,i),next:(o)=>n(o,i+1)}}}var ce="?";function ut(e,t,i,n,r){let o={platform:e,filename:t,function:i==="<anonymous>"?ce:i,in_app:!0};if(!li(n))o.lineno=n;if(!li(r))o.colno=r;return o}var xo=(e,t)=>{let i=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return i||n?[e.indexOf("@")!==-1?e.split("@")[0]:ce,i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var gB=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lB=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dB=/\((\S*)(?::(\d+))(?::(\d+))\)/,Qa=(e,t)=>{let i=gB.exec(e);if(i){let[,r,o,s]=i;return ut(t,r,ce,+o,+s)}let n=lB.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=dB.exec(n[2]);if(a)n[2]=a[1],n[3]=a[2],n[4]=a[3]}let[o,s]=xo(n[1]||ce,n[2]);return ut(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var IB=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,cB=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ka=(e,t)=>{let i=IB.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){let s=cB.exec(i[3]);if(s)i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]=""}let r=i[3],o=i[1]||ce;return[o,r]=xo(o,r),ut(t,r,o,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}};var uB=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,lu=(e,t)=>{let i=uB.exec(e);return i?ut(t,i[2],i[1]||ce,+i[3],i[4]?+i[4]:void 0):void 0};var CB=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,du=(e,t)=>{let i=CB.exec(e);return i?ut(t,i[2],i[3]||ce,+i[1]):void 0},mB=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Iu=(e,t)=>{let i=mB.exec(e);return i?ut(t,i[5],i[3]||i[4]||ce,+i[1],+i[2]):void 0};var pB=/^\s*[-]{4,}$/,AB=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,bB=/^Promise\.(?:all|any)$/,ZB=/^index \d+$/,hB="node:internal/promise",uu=(e,t)=>{let i=e.match(AB);if(i){let n,r,o,s,a;if(i[1]){o=i[1];let d=o.lastIndexOf(".");if(o[d-1]===".")d--;if(d>0){n=o.slice(0,d),r=o.slice(d+1);let I=n.indexOf(".Module");if(I>0)o=o.slice(I+1),n=n.slice(0,I)}s=void 0}if(r)s=n,a=r;if(r==="<anonymous>")a=void 0,o=void 0;if(o===void 0)a=a||ce,o=s?`${s}.${a}`:a;let g=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";if(g?.match(/\/[A-Z]:/))g=g.slice(1);if(!g&&i[5]&&!l)g=i[5];if(bB.test(o)&&ZB.test(g||""))g=hB;return{filename:g?decodeURI(g):void 0,module:void 0,function:o,lineno:cu(i[3]),colno:cu(i[4]),in_app:fB(g||"",l),platform:t}}if(e.match(pB))return{filename:e,platform:t}};function fB(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function cu(e){return parseInt(e||"",10)||void 0}var Cu=/\(error: (.*)\)/,mu=50;function pu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,mu).map((i)=>({...i,filename:i.filename||WB(t).filename,function:i.function||ce}))}function WB(e){return e[e.length-1]||{}}function La(){return Au("web:javascript",Qa,Ka)}function Au(e,...t){return(i,n=0)=>{let r=[],o=i.split(`
|
|
36
36
|
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let g=Cu.test(a)?a.replace(Cu,"$1"):a;if(!g.match(/\S*Error: /)){for(let l of t){let d=l(g,e);if(d){r.push(d);break}}if(r.length>=mu)break}}return pu(r)}}class bu{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=wt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return di(e,"DOMException")}isDOMError(e){return di(e,"DOMError")}}class Yo{match(e){return Sc(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let i=e.message;if(i.error&&typeof i.error.message=="string")return String(i.error.message);return String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Zu{constructor(){}match(e){return Xc(e)&&e.error!=null}coerce(e,t){let i=t.apply(e.error);if(!i)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return i}}var yB=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class So{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(yB);if(n)t=n[1],i=n[2];return[t,i]}}var hu=["fatal","error","warning","log","info","debug"];function Xo(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 Eo{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let i=this.getErrorPropertyFromObject(e);if(i)return t.apply(i);return{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Di(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")n+=` with message: '${e.message}'`;return n}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),i=Xo(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return wt(e)&&!Nc(e)&&hu.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(ru(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class fu{match(e){return Di(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Xo(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class To{match(e){return Vo(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Wu{match(e){return di(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Di(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);if(Vo(i))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class yu{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 or={MESSAGE:"$message",TIMESTAMP:"$timestamp"},VB=new Set([or.MESSAGE,or.TIMESTAMP]),Jo={enabled:!0,max_bytes:32768};function Ma(e){if(!e)return{...Jo};return{enabled:e.enabled??Jo.enabled,max_bytes:RB(e.max_bytes,Jo.max_bytes)}}function BB(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,r)=>{if(VB.has(r))return t.push(r),n;return n[r]=e[r],n},{}),droppedKeys:t}}class Vu{constructor(e){this._entries=[],this._totalBytes=0,this._config=Ma(e)}setConfig(e){this._config=Ma(e),this._trimToMaxBytes()}add(e){let t=GB(e);if(!t)return;let i=Bu(t.json);if(i>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function RB(e,t){if(!er(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function GB(e){let t;try{t=ji(e)}catch{return}try{let i=JSON.parse(t);if(!qn(i))return;let n=i,r=n[or.MESSAGE],o=n[or.TIMESTAMP];if(!wt(r)||r.trim().length===0)return;if(!wt(o)&&!er(o))return;return{step:n,json:t}}catch{return}}function Bu(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let n=0;n<t.length;n++)if(t[n]==="%")i+=1,n+=2;else i+=1;return i}class Et extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class ci extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var wu=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function Ru(e){if(e instanceof Et){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function wB(e){return typeof e=="object"&&(e instanceof Et||Fu(e))}function Fu(e){return e instanceof ci}function FB(e){if(e instanceof Et)return e.status===502||e.status===504;if(!(e instanceof ci))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Ki(e){return typeof e=="object"&&e instanceof Et&&e.status===413}function sr(e){if(e instanceof Et)return e.status===408||e.status===429||e.status>=500;return Fu(e)}function Gu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var $a="default";class Uo{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new No([new Yo,new Eo,new So,new To],La())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Na,this._events=new _a,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=zc("[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=iu(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:sr},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=!ka()||(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(Ue.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ue.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ue.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};if(wu(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=Mn(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(e,t,i){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,i)}captureStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",r,n)})}async captureStatelessImmediate(e,t,i,n){let r=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",r,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",r,n)})}async aliasStatelessImmediate(e,t,i,n){let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",r,n)}groupIdentifyStateless(e,t,i,n,r,o){this.wrap(()=>{let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,r,o){let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});await this.sendImmediate("capture",s,n)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((n)=>n.json()).catch((n)=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(e,t={},i={},n={},r={},o=!1){await this._initPromise;let s=o?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,g={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)g.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)g.evaluation_contexts=this.evaluationContexts;let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(g)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:FB},this.featureFlagsRequestTimeoutMs).then((d)=>d.json()).then((d)=>({success:!0,response:va(d)})).catch((d)=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof Et)return{type:"api_error",statusCode:e.status};if(e instanceof ci){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,r,o);if(s===void 0)return{response:void 0,requestId:void 0};let a=Ln(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,r,o,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,r,o,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},r,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},r,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,r,o);if(!s)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}}async getFeatureFlagDetailsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s={geoip_disable:r??this.disableGeoip};if(o)s.flag_keys_to_evaluate=o;let a=await this.getFlags(e,t,i,n,s);if(!a.success)return;let g=a.response;if(g.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(g.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:g?.requestId,quotaLimited:g.quotaLimited};return g}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(e,t).then((r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);this._logger.error(s),this._events.emit("error",Error(o));return}return r.json()}).catch((r)=>{this._logger.error("Surveys API could not be loaded",r),this._events.emit("error",r)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ue.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ue.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ue.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return $a}persistedQueueKeyForRoute(e){return Ue.Queue}getActiveQueueRoutes(){return[$a]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let r=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),o=this.getPersistedProperty(r)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:n}),this.setPersistedProperty(r,o),this._events.emit(e,n),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=he(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(r){this._events.emit("error",r)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=Gu(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=Fo(r.uuid,Oe),r}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:Ta(),uuid:Fo(t?.uuid,Oe)};if(t?.disableGeoip??this.disableGeoip){if(!Gu(i.properties))i.properties={};i.properties.$geoip_disable=!0}if(i.distinctId)i.distinct_id=i.distinctId,delete i.distinctId;return i}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await Ru(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((r)=>!!r),n=0;while(!0){let r=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(r.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${r.length} pending promise(s) before flushing`);await Promise.all(r.map((o)=>o.catch(()=>{}))),n++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,n])}).then(()=>Ja([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),Ja([n]).then(()=>{if(this.flushPromises.delete(n),this.pendingFlushPromise===n)this.pendingFlushPromise=null;if(this.flushPromise===n)this.flushPromise=null}),n}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,i=$a){let n={api_key:this.apiKey,batch:e,sent_at:Ta()};if(this.historicalMigration)n.historical_migration=!0;let r=ji(n),o=`${this.host}/batch/`,s=this.disableCompression?null:await gi(r,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await(await this.fetchWithRetry(o,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((n)=>this.getRouteQueue(n).length>0))return;let t=[],i;for(let n of e)try{await this._flushRoute(n,t)}catch(r){if(i===void 0)i=r}if(i!==void 0)throw i;this._events.emit("flush",t)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(i)||[];if(!n.length)return;let r=n.length,o=0;while(n.length>0&&o<r){let s=n.slice(0,this.maxBatchSize),a=s.map((d)=>d.message===void 0?d.message:this.normalizeMessage(d.message)),g=async()=>{let I=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,I),n=I,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:(d)=>{if(Ki(d))return!1;return sr(d)}};try{await this.sendBatch(a,l,e)}catch(d){if(Ki(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 ci))await g();throw this._events.emit("error",d),d}await g(),t.push(...a),o+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(Ki(o))return!1;return sr(o)}}),{kind:"ok"}}catch(o){if(Ki(o))return{kind:"too-large"};if(o instanceof ci)return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await gi(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(Ki(o))return!1;return sr(o)}}),{kind:"ok"}}catch(o){if(Ki(o))return{kind:"too-large"};if(sr(o))return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async fetchWithRetry(e,t,i,n){let r=t.body?t.body:"",o=-1;try{o=r instanceof Blob?r.size:Buffer.byteLength(r,tu)}catch{if(r instanceof Blob)o=r.size;else o=new TextEncoder().encode(r).length}return await nu(async()=>{let s=new AbortController,a=n??this.requestTimeout,g=he(()=>s.abort(),a),l=null;try{l=await this.fetch(e,{signal:s.signal,...t})}catch(I){throw new ci(I)}finally{clearTimeout(g)}if(t.mode!=="no-cors"&&(l.status<200||l.status>=400))throw new Et(l,o);return l},{...this._retryOptions,...i})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let i=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((s)=>this.getRouteQueue(s).length>0))break;let o=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(r){if(!wB(r))throw r;await Ru(r)}},n;try{return await Promise.race([new Promise((r,o)=>{n=he(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(n)}}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var ku=require("fs"),Pu=require("readline"),Oo=new Ne.ReduceableCache(25),Nu=new Ne.ReduceableCache(20),qa=7,NB=1000,xB=1e4;async function xu(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"||EB(s)||TB(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(Nu.get(r))continue;let o=t[r];if(!o)continue;o.sort((g,l)=>g-l);let s=UB(o);if(s.every((g)=>JB(r,g)))continue;let a=OB(Oo,r,{});n.push(YB(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)SB(e,Oo);return Oo.reduce(),e}function YB(e,t,i){return new Promise((n)=>{let r=ku.createReadStream(e),o=Pu.createInterface({input:r});function s(){r.destroy(),n()}let a=0,g=0,l=t[g];if(l===void 0)return void s();let d=l[0],I=l[1];function C(){Nu.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",C),o.on("error",C),o.on("close",s),o.on("line",(m)=>{if(a++,a<d)return;if(i[a]=zB(m,0),a>=I){if(g===t.length-1){o.close(),o.removeAllListeners();return}g++;let A=t[g];if(A===void 0){o.close(),o.removeAllListeners();return}d=A[0],I=A[1]}})})}function SB(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;XB(i.lineno,i,n)}}function XB(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=Yu(e);r<e;r++){let o=i[r];if(o===void 0)return void Hu(t);t.pre_context.push(o)}if(i[e]===void 0)return void Hu(t);t.context_line=i[e];let n=Su(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 Hu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function EB(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function TB(e){if(e.lineno!==void 0&&e.lineno>xB)return!0;if(e.colno!==void 0&&e.colno>NB)return!0;return!1}function JB(e,t){let i=Oo.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 UB(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=vu(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+qa;else r.push(n),n=vu(o);t++}return r}function vu(e){return[Yu(e),Su(e)]}function Yu(e){return Math.max(1,e-qa)}function Su(e){return e+qa}function OB(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function zB(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 Li=require("path");function Xu(e=process.cwd()){let t=Li.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(Li.isAbsolute(o.filename))o.filename=i(Li.relative(n,i(o.filename)))}return r}}var Eu="5.46.1";var Ft={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class ui{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 ui({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(Ft.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(Ft.QUOTA_LIMITED);if(t===void 0)r.push(Ft.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 Tu(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 jB=60000,DB=1152921504606847000,_B=["is_not","is_set"];class Mi extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Mi.prototype)}}function zu(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class U extends Error{constructor(e){super(e);zu(this,U)}}class Ct extends Error{constructor(e){super(e);zu(this,Ct)}}class eg{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:r,customHeaders:o,...s}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=r,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=o,this.onLoad=s.onLoad,this.onMinimalFlagCalledEvents=s.onMinimalFlagCalledEvents,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},i={},n={},r={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:r}}async getFeatureFlag(e,t,i={},n={},r={}){await this.loadFeatureFlags();let o,s;if(!this.loadedSuccessfullyOnce)return o;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,r);try{o=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(g){if(g instanceof Ct||g instanceof U)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${e}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${g}`))}}return o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},r=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async(a)=>{try{let{value:g,payload:l}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=g,l)n[a.key]=l}catch(g){if(g instanceof Ct||g instanceof U)this.logMsgIfDebug(()=>console.debug(`${g.name} when computing flag locally: ${a.key}: ${g.message}`));else if(g instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${g}`));r=!0}})),{response:i,payloads:n,fallbackToFlags:r}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:r=!1}=i;if(!r)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:r,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new U("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let g=this.groupTypeMapping[String(a)];if(!g)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new U("Flag has unknown group type index");if(!(g in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(r?.$device_id===void 0||r?.$device_id===null||r?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=o[g];return await this.matchFeatureFlagProperties(e,n[g],l,t)}{let g=this.getBucketingValueForFlag(e,i,r);if(g===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new U(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,g,r,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=i?.$device_id;if(n==null||n==="")return;return n}return t}getFeatureFlagPayload(e,t){let i=null;if(t!==!1&&t!=null){if(typeof t=="boolean")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(i!=null){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:n}=i,r=e.key;if(!this.featureFlagsByKey)throw new U("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new U(`Flag dependency property for '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new U(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new U(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let l=this.featureFlagsByKey[a];if(l)if(l.active)try{let d=await this.computeFlagValueLocally(l,i);n[a]=d}catch(d){throw new U(`Error evaluating flag dependency '${a}' for flag '${r}': ${d}`)}else n[a]=!1;else throw new U(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new U(`Dependency '${a}' could not be evaluated`)}let s=n[r];return this.flagEvaluatesToExpectedValue(e.value,s)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,i,n){let r=e.filters||{},o=r.groups||[],s=r.aggregation_group_type_index,a=r.early_exit??!1,{groups:g,groupProperties:l}=n,d=!1,I;for(let C of o)try{let m=C.aggregation_group_type_index!==void 0?C.aggregation_group_type_index:s,A=i,c=t;if(m!==s){if(m!=null){let p=this.groupTypeMapping[String(m)];if(!p||!(p in g)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${m} not available`));continue}if(!(p in l)){d=!0;continue}A=l[p],c=g[p]}}let u=await this.isConditionMatch(e,c,C,A,n);if(u==="match"){let p=C.variant,Z=r.multivariate?.variants||[];I=p&&Z.some((h)=>h.key===p)?p:await this.getMatchingVariant(e,c)||!0;break}if(a&&u==="out_of_rollout_bound")return!1}catch(m){if(m instanceof Ct)throw m;if(m instanceof U)d=!0;else throw m}if(I!==void 0)return I;if(d)throw new U("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,n,r){let o=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let g=a.type,l=!1;if(g==="cohort"){let d=await Du(a,n,this.cohorts,this.debugMode,(I)=>this.evaluateFlagDependency(I,n,r));l=a.operator==="not_in"?!d:d}else l=g==="flag"?await this.evaluateFlagDependency(a,n,r):ju(a,n,s);if(!l)return"no_match"}if(o==null)return"match"}if(o!=null&&await Ju(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await Ju(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(jB,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 Mi(`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 Mi(`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 Mi(`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 Mi)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=he(()=>{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 Ju(e,t,i=""){let n=await Tu(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/DB}function ju(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 U(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!_B.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(l,d){if(Array.isArray(l))return l.map((I)=>String(I).toLowerCase()).includes(String(d).toLowerCase());return String(l).toLowerCase()===String(d).toLowerCase()}function g(l,d,I){if(I==="gt")return l>d;if(I==="gte")return l>=d;if(I==="lt")return l<d;if(I==="lte")return l<=d;throw Error(`Invalid operator: ${I}`)}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 Uu(String(r))&&String(s).match(String(r))!==null;case"not_regex":return Uu(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof r=="number"?r:parseFloat(String(r)),d;if(d=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(l)&&Number.isFinite(d))return g(d,l,o);return g(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new U("Date operations cannot be performed on boolean values");let l=$B(String(r));if(l==null)l=Ou(r);if(l==null)throw new U(`Invalid date: ${r}`);let d=Ou(s);if(["is_date_before"].includes(o))return d<l;return d>l}case"semver_eq":return De(ue(String(s)),ue(String(r)))===0;case"semver_neq":return De(ue(String(s)),ue(String(r)))!==0;case"semver_gt":return De(ue(String(s)),ue(String(r)))>0;case"semver_gte":return De(ue(String(s)),ue(String(r)))>=0;case"semver_lt":return De(ue(String(s)),ue(String(r)))<0;case"semver_lte":return De(ue(String(s)),ue(String(r)))<=0;case"semver_tilde":{let l=ue(String(s)),{lower:d,upper:I}=KB(String(r));return De(l,d)>=0&&De(l,I)<0}case"semver_caret":{let l=ue(String(s)),{lower:d,upper:I}=LB(String(r));return De(l,d)>=0&&De(l,I)<0}case"semver_wildcard":{let l=ue(String(s)),{lower:d,upper:I}=MB(String(r));return De(l,d)>=0&&De(l,I)<0}default:throw new U(`Unknown operator: ${o}`)}}function QB(e,t){if(!(e in t))throw new Ct(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Du(e,t,i,n=!1,r){let o=String(e.value);QB(o,i);let s=i[o];return _u(s,t,i,n,r)}async function _u(e,t,i,n=!1,r){if(!e)return!0;let{type:o,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let g of s)try{let l=await _u(g,t,i,n,r);if(o==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Ct)throw l;if(l instanceof U){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new U("Can't match cohort without a given cohort property value");return o==="AND"}for(let g of s)try{let l;if(g.type==="cohort")l=await Du(g,t,i,n,r);else if(g.type==="flag"){if(!r)throw new U(`Flag dependency '${g.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await r(g)}else l=ju(g,t);let d=g.negation||!1;if(o==="AND"){if(!l&&!d)return!1;if(l&&d)return!1}else{if(l&&!d)return!0;if(!l&&d)return!0}}catch(l){if(l instanceof Ct)throw l;if(l instanceof U){if(n)console.debug(`Failed to compute property ${g} locally: ${l}`);a=!0}else throw l}if(a)throw new U("can't match cohort without a given cohort property value");return o==="AND"}function Uu(e){try{return new RegExp(e),!0}catch(t){return!1}}function Qu(e,t){if(!/^\d+$/.test(e))throw new U(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new U(`Invalid semver: ${t}`);return parseInt(e,10)}function ue(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new U(`Invalid semver: ${e}`);let n=i.split("."),r=(g)=>{if(g===void 0||g==="")return 0;return Qu(g,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function De(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 KB(e){let t=ue(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function LB(e){let t=ue(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 MB(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new U(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(g)=>{try{return Qu(g,e)}catch{throw new U(`Invalid wildcard semver: ${e}`)}},o=r(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let g=r(n[1]);s=[o,g,0],a=[o,g+1,0]}return{lower:s,upper:a}}function Ou(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 U(`${e} is in an invalid date format`)}throw new U(`The date provided ${e} must be a string, number, or date object`)}function $B(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 qB(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 Ku(e,t){globalThis.process?.on("uncaughtException",qB(e,t))}function Lu(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var eR=2000;class mt{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Pa({...Tc(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return qn(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())Ku(this.onException.bind(this),this.onFatalError.bind(this)),Lu(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!mt.isPreviouslyCapturedError(e)){let i=await mt.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(eR),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class tg{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function tR(e){return e==="v0"||e==="v1"}function Mu(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return tR(e)?e:"v0"}var ar="analytics",gr="ai";function $u(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class $i extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super($i.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 ig(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 iR(e){return typeof e=="string"?e:void 0}var nR=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ig},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ig},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ig},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:iR}],rR=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function oR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sR(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 qu(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function aR(e){let i={...oR(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of nR)if(o in i){let g=a(i[o]);if(g!==void 0)n[s]=g;delete i[o]}let r={};for(let{property:o,field:s}of rR)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,qu(i,"$set",e.$set),qu(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:sR(e.timestamp),...r,options:n,properties:i}}function eC(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(aR)};if(i)n.historical_migration=!0;return n}var gR="/i/v1/analytics/events",lR=30000,dR=new Set([408,500,502,503,504]);class ng{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??lR,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>he(n,i))),this.generateRequestId=t.generateRequestId??Oe,this.compress=t.compress??gi}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=eC(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${gR}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let g=1;g<=a;g++){let l=g===a,d=ji({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),I;try{I=await this.sendOnce(r,d,g,t)}catch(u){if(l)return this.surfaceBatchFailure(t,o,s,u);await this.sleep(this.backoffDelay(g));continue}let{status:C}=I;if(C<200||C>=300){if(!l&&dR.has(C)){let p=this.parseRetryAfter(I);await this.cancelBody(I),await this.sleep(this.backoffDelay(g,p));continue}let u=await this.buildHttpError(I,C);return this.surfaceBatchFailure(t,o,s,u)}let m;try{m=await this.parseResponse(I)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${C} response body`))}let A=this.classify(s,m,o);if(A.length===0)return this.surfacePartialDrops(t,o);if(l)return void this.onError(new $i({requestId:t,drops:o,retryExhausted:A.map((u)=>u.uuid)}));s=A;let c=this.parseRetryAfter(I);await this.sleep(this.backoffDelay(g,c))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let g=await this.compress(t,this.config.isDebug);if(g!==null)o=g,r["Content-Encoding"]="gzip"}let s=new AbortController,a=he(()=>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 $i({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new $i({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var IR=100,tC=30000,cR=50000,uR=50,CR=500,mR="https://us.i.posthog.com",iC=new Set;function zo(e,t){if(iC.has(e))return;iC.add(e),console.warn(`[PostHog] ${t}`)}function pR(e){return typeof e=="string"?e.trim():""}function AR(e){return(typeof e=="string"?e.trim():"")||void 0}function bR(e){return(typeof e=="string"?e.trim():"")||mR}function ZR(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function hR(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 rg extends Uo{constructor(e,t={}){let i=pR(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:bR(t.host),personalApiKey:AR(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new tg,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=Mu(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,IR):tC,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 eg({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 mt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||cR}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??CR,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??uR;this._waitUntilCycle.timer=he(()=>{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"&&$u(e)?gr:ar}persistedQueueKeyForRoute(e){return e===gr?Ue.AiQueue:Ue.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[ar,gr]:[ar]}async sendBatch(e,t,i=ar){if(this.captureMode!=="v1"||i===gr)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 ng({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 Eu}get metrics(){if(!this._metrics)this._metrics=new vo(this,Ho(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(i)}_sendPreparedEvent(e,t,i,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:r,event:o,properties:s,options:a})=>{let g={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,l,g):this.enqueue(e,l,g)}).catch((r)=>{if(r)console.error(r)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,l={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(Object.keys(t).length===0&&Object.keys(i).length===0)return;let n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(i).length>0)n.$set_once=i;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let i=ZR(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=tC){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 V=this._flagOverrides[e];if(V===void 0)return;let H=this._payloadOverrides?.[e];return{key:e,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:H}}let{groups:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=i,d=this.addLocalPersonAndGroupProperties(t,o,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C,m=!1,A,c,u,p,Z,h,W;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[e];if(V)try{let H=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,I,{matchValue:n});if(H){m=!0;let Y=H.value;p=V.id,h="Evaluated locally",W=V.has_experiment,C={key:e,enabled:Y!==!1,variant:typeof Y=="string"?Y:void 0,payload:H.payload??void 0}}}catch(H){if(H instanceof Ct||H instanceof U)this._logger?.info(`${H.name} when computing flag locally: ${e}: ${H.message}`);else throw H}}if(!m&&!a){let V=await super.getFeatureFlagDetailsStateless(I.distinctId,I.groups,g,l,s,[e]);if(V===void 0)u=Ft.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=V.minimalFlagCalledEvents===!0,A=V.requestId,c=V.evaluatedAt;let H=[];if(V.errorsWhileComputingFlags)H.push(Ft.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))H.push(Ft.QUOTA_LIMITED);let Y=V.flags[e];if(Y===void 0)H.push(Ft.FLAG_MISSING);else{p=Y.metadata?.id,Z=Y.metadata?.version,h=Y.reason?.description??Y.reason?.code,W=Y.metadata?.has_experiment;let v;if(Y.metadata?.payload!==void 0)try{v=JSON.parse(Y.metadata.payload)}catch{v=Y.metadata.payload}C={key:e,enabled:Y.enabled,variant:Y.variant,payload:v}}if(H.length>0)u=H.join(",")}}if(r){let V=C===void 0?void 0:C.enabled===!1?!1:C.variant??!0,H={$feature_flag:e,$feature_flag_response:V,$feature_flag_id:p,$feature_flag_version:Z,$feature_flag_reason:h,locally_evaluated:m,[`$feature/${e}`]:V,$feature_flag_request_id:A,$feature_flag_evaluated_at:m?Date.now():c};if(W!==void 0)H.$feature_flag_has_experiment=W;if(m&&this.featureFlagsPoller){let Y=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(Y!==void 0)H.$feature_flag_definitions_loaded_at=Y}if(u)H.$feature_flag_error=u;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:V,groups:o,disableGeoip:s,properties:H})}if(C!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)C={...C,payload:this._payloadOverrides[e]};return C}async getFeatureFlag(e,t,i){zo("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(zo("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){zo("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return!!(n.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(i,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(I,s),m={},A={},c=!0;if(C)m=C.response,A=C.payloads,c=C.fallbackToFlags;if(c&&!a){let u=await super.getFeatureFlagsAndPayloadsStateless(I.distinctId,I.groups,g,l,o,s);m={...m,...u.flags||{}},A={...A,...u.payloads||{}}}if(this._flagOverrides!==void 0)m={...m,...this._flagOverrides};if(this._payloadOverrides!==void 0)A={...A,...this._payloadOverrides};return{featureFlags:m,featureFlagPayloads:A}}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 ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:g,groupProperties:l}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,g,l);g=d.allPersonProperties,l=d.allGroupProperties;let I=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,g),l);if(a==null)a=this.options.strictLocalEvaluation??!1;let C={},m,A,c=!1,u=!1,p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(I,s),Z=new Set;if(p)for(let[W,y]of Object.entries(p.response)){let V=this.featureFlagsPoller?.featureFlagsByKey[W];C[W]={key:W,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:p.payloads[W],id:V?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:V?.has_experiment},Z.add(W)}if((p?p.fallbackToFlags:!0)&&!a){let W=await super.getFeatureFlagDetailsStateless(I.distinctId,I.groups,g,l,o,s);if(W){this._minimalFlagCalledEvents=W.minimalFlagCalledEvents===!0,m=W.requestId,A=W.evaluatedAt,c=Boolean(W.errorsWhileComputingFlags),u=Array.isArray(W.quotaLimited)&&W.quotaLimited.includes("feature_flags");for(let[y,V]of Object.entries(W.flags)){if(Z.has(y))continue;let H;if(V.metadata?.payload!==void 0)try{H=JSON.parse(V.metadata.payload)}catch{H=V.metadata.payload}C[y]={key:y,enabled:V.enabled,variant:V.variant,payload:H,id:V.metadata?.id,version:V.metadata?.version,reason:V.reason?.description??V.reason?.code,locallyEvaluated:!1,hasExperiment:V.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[W,y]of Object.entries(this._flagOverrides)){if(y===void 0){delete C[W];continue}let V=C[W];C[W]={key:W,enabled:y!==!1,variant:typeof y=="string"?y:void 0,payload:V?.payload,id:V?.id,version:V?.version,reason:V?.reason,locallyEvaluated:V?.locallyEvaluated??!1,hasExperiment:V?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[W,y]of Object.entries(this._payloadOverrides)){let V=C[W];if(V)C[W]={...V,payload:y}}return new ui({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:C,requestId:m,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:c,quotaLimited:u})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:n,groups:r,disableGeoip:o,properties:s}=e,a=r&&Object.keys(r).length>0?`_${JSON.stringify(Object.entries(r).sort(([l],[d])=>l<d?-1:l>d?1:0))}`:"",g=`${i}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(g))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(g);else this.distinctIdHasSentFlagCalls[t]=new Set([g]);this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:r,disableGeoip:o})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(i)=>Object.fromEntries(i.map((n)=>[n,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let i=t.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in t){let i=t.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(e,t,i){if(!this.context)return t();return this.context.run(e,t,i)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),i=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((n)=>he(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=he(()=>{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(Ec(o)&&t&&r in t){let s={};for(let[a,g]of Object.entries(o))s[String(a)]=String(g);n[String(r)]=s}else i[String(r)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(e,t,i,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let r=n?.personProperties||{},o=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let g={};for(let[l,d]of Object.entries(t||{}))g[l]=String(d);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[l,d]of Object.entries(t||{}))g[l]=String(d);return await this.getAllFlags(e,{groups:g,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,r,o,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let r={...i||{}},o={};if(t)for(let s of Object.keys(t))o[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:r,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,n){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,i,n,r){if(!mt.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(mt.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(!mt.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(mt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((o)=>this.captureImmediate({...o,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:r,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:d}=e,I=this.context?.get(),C=t.includeContextProperties??!0,m=i||I?.distinctId,A=C?{...this.props,...I?.properties||{},...r||{}}:{...r||{}};if(!m)m=Oe(),A.$process_person_profile=!1;if(C&&I?.sessionId&&!A.$session_id)A.$session_id=I.sessionId;let c=this._shouldSendMinimalFlagCalledEvent(n,A)?Mn(A):A,u=this._runBeforeSend({distinctId:m,event:n,properties:c,groups:o,flags:s,sendFeatureFlags:a,timestamp:g,disableGeoip:l,uuid:d});if(!u)return Promise.reject(null);let p=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){zo("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 Z=typeof a=="object"?a:void 0,h=await this.getFeatureFlagsForEvent(u.distinctId,o,l,Z);return hR(h)}return{}}).catch(()=>({})).then((Z)=>{let h=u.groups||o;return{...Z,...u.properties||{},...h!==void 0&&Object.keys(h).length>0?{$groups:h}:{}}});if(u.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof p.$raw_user_agent=="string"){if(kc(p.$raw_user_agent,this.options.custom_blocked_useragents||[]))u.event="$bot_pageview",p.$browser_type="bot"}return{distinctId:u.distinctId,event:u.event,properties:p,options:{timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.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 nC=require("async_hooks");class og{constructor(){this.storage=new nC.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 fR(e,{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:o=!0}={}){return(s)=>{if(!(r==="*"||r.includes(s.level)))return s;if(!s.tags)s.tags={};let g=s.tags[rC.POSTHOG_ID_TAG];if(g===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",d=new URL(`/project/${e.apiKey}/person/${g}`,l).toString();s.tags["PostHog Person URL"]=d;let I=s.exception?.values||[],C=I.map((A)=>({...A,stacktrace:A.stacktrace?{...A.stacktrace,type:"raw",frames:(A.stacktrace.frames||[]).map((c)=>({...c,platform:"node:javascript"}))}:void 0})),m={$exception_message:I[0]?.value||s.message,$exception_type:I[0]?.type,$exception_level:s.level,$exception_list:C,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:I[0]?.value||s.message,$sentry_exception_type:I[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:g,properties:m});return s}}class rC{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(fR(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class sg extends rg{getLibraryId(){return"posthog-node"}initializeContext(){return new og}createErrorPropertiesBuilder(){return new Ne.ErrorPropertiesBuilder([new Ne.EventCoercer,new Ne.ErrorCoercer,new Ne.ObjectCoercer,new Ne.StringCoercer,new Ne.PrimitiveCoercer],Ne.createStackParser("node:javascript",Ne.nodeStackLineParser),[Fc(),xu,Xu()])}}class te 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 te(`Potato API request failed with status ${e}${n}`,"http",e,t,i)}static waitTimeout(e){return new te(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class qi 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 qi(`Pipeline graph validation failed
|
|
38
38
|
${t}`,e)}}var Ge=require("fs/promises"),gC=require("os"),Ci=require("path");class F 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 b(e,t,i){if(!e)throw new F(t,i)}var oC=(e)=>("disabled"in e)?void 0:`Hint: ${e.description}`,P={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>."},Tt={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>."},Ce={description:"Reinstall @toloka-platform/sdk to restore the bundled files."};class lr extends F{constructor(e,t){super(e,t);this.name="CredentialsError"}}var lC=(e)=>e.HOME??gC.homedir(),WR=(e)=>e.XDG_CONFIG_HOME??Ci.join(lC(e),".config"),_e=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??Ci.join(WR(e),"toloka","credentials.json"),dC=(e=process.env)=>Ci.join(lC(e),".toloka","credentials.json"),Do=(e=process.env)=>Ci.dirname(_e(e)),sC=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},pt=(e)=>{let t=sC(e.trim());try{let i=new URL(t);return i.hash="",i.search="",sC(i.toString())}catch{return t}},jo=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,yR=(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}},VR=(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=yR(n);if(r===void 0)return;Object.defineProperty(t,i,{value:r,writable:!0,enumerable:!0,configurable:!0})}return t},BR=(e,t)=>{let i=VR(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}},RR=(e)=>{let t=jo(e,"baseUrl"),i=jo(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=jo(e,"current"),o=jo(e,"projects");if(r===void 0&&o===void 0)return n;let s=BR(o,r);if(s===void 0)return;return{...n,...s}};async function dr(e){let t;try{t=await Ge.readFile(e,"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return"missing";return"invalid"}try{let i=RR(JSON.parse(t));return i===void 0?"invalid":{credentials:i}}catch{return"invalid"}}async function ag(e=process.env){let t=_e(e),i=await dr(t);if(i!=="missing"){if(i==="invalid")throw new lr(`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=dC(e),r=await dr(n);if(r==="missing")return;if(r==="invalid")throw new lr(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:r.credentials,path:n,legacy:!0}}async function en(e,t){try{return{found:await ag(e)}}catch(i){if(!(i instanceof lr)||t===void 0)throw i;return{found:void 0,warning:i.message}}}async function IC(e=process.env){return(await ag(e))?.credentials}async function Jt(e=process.env){let t=await ag(e);if(t!==void 0)return t;throw new lr(`No stored credentials found at ${_e(e)}. Run toloka login.`,{hint:{disabled:!0}})}var GR=(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}:{}}},aC=async(e)=>{try{let t=await Ge.lstat(e);b(!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 Ht(e){let t=Ci.dirname(e);await aC(t),await aC(e),await Ge.mkdir(t,{recursive:!0,mode:448}),await Ge.chmod(t,448)}async function Ir(e,t=process.env){let i=_e(t);return await Ht(i),await Ge.writeFile(i,`${JSON.stringify(GR(e),null,2)}
|
|
39
|
-
`,{mode:384}),await Ge.chmod(i,384),i}var wR=async(e)=>{try{return await Ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},gg=(e=process.env)=>[_e(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[dC(e)]:[]];async function cC(e=process.env){let t=[];for(let i of gg(e)){if(!await wR(i))continue;await Ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,uC=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var Qe=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},tn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var lg={name:"@toloka-platform/sdk",version:"0.11.
|
|
39
|
+
`,{mode:384}),await Ge.chmod(i,384),i}var wR=async(e)=>{try{return await Ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},gg=(e=process.env)=>[_e(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[dC(e)]:[]];async function cC(e=process.env){let t=[];for(let i of gg(e)){if(!await wR(i))continue;await Ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,uC=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var Qe=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},tn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var lg={name:"@toloka-platform/sdk",version:"0.11.1",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","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./testing":"./src/testing/index.ts","./checks":"./src/checks/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"latest"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js","generate:check":"bun ./scripts/check-generated-client.ts",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts","sync-task-ui-declarations":"bun ./scripts/sync-task-ui-declarations.ts",test:"vitest run","test:browser":"vitest run --config vitest.browser.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.2",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","jsonpath-rfc9535":"1.3.0","oxc-parser":"0.138.0","posthog-node":"5.46.1","typescript-api":"npm:typescript@6.0.3"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",playwright:"1.56.1",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},peerDependencies:{playwright:">=1.56.1 <2",vitest:">=4.1.0 <5"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:">=1.4.0"},tolokaBuild:{commit:"62d9c4558758f7409b65de7c849c8a2e8d15ba9a"}};var fe=lg.name,oe=lg.version,dg=(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)]},CC=(e)=>{let t=dg(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},Ig=(e,t)=>{let i=dg(e),n=dg(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 cr=(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},vR=(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!==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},mC=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
|
|
40
40
|
`),nn=(e)=>{if(e instanceof te)return e;if(e instanceof AggregateError)for(let t of e.errors){let i=nn(t);if(i!==void 0)return i}return e instanceof Error?nn(e.cause):void 0},Ut=(e)=>{if(e instanceof F){let t=nn(e.cause),i=t===void 0?[]:t.message===e.message?[cr(t)]:[t.message,cr(t)];return mC([e.message,...i,oC(e.hint)])}if(e instanceof te)return mC([e.message,cr(e),vR(e)]);return e instanceof Error?e.message:String(e)};var kR="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",PR="https://eu.posthog.com",NR={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0};function xR(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(tn(t))return!1;if(Qe(t))return!0;if(Qe(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(Qe(e.CI??process.env.CI))return!1;if(Qe(process.env.VITEST))return!1;return!0}var YR={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},"base-model":{list:!0,get:!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}},SR={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},AC=(e)=>{let t=e[0];if(t===void 0)return"help";let i=YR[t];if(i===void 0)return SR[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 Qo(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(NR[n]===!0)i+=1;continue}t.push(n)}return AC(t)}function XR(e){if(e===void 0)return{error_code:"command_failed"};let t=nn(e);if(t!==void 0)return{error_code:t.code};if(e instanceof qi)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var ER=(e)=>{let t=nn(e);return t===void 0?{}:{status_code:t.status,request_id:t.requestId}},TR=(e)=>_o.join(_o.dirname(_e(e)),"anonymous-id"),JR=async(e)=>{let t=TR(e);await Ht(t);try{let n=(await mi.readFile(t,"utf8")).trim();if(n.length>0)return await mi.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let i=pC.randomUUID();return await mi.writeFile(t,`${i}
|
|
41
41
|
`,{mode:384}),await mi.chmod(t,384),i},UR=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){b(!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&&!xR(t))return UR();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 sg(kR,{host:PR,flushAt:1,flushInterval:0});d.on("error",s),i=d}n??=await JR(t)},g=()=>({sdk_version:oe,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),l=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(d){l=l.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){l=l.then(()=>{if(i===void 0||n===void 0)return;let I=g(),C=AC(d.command.split(" "));if(d.outcome==="failed"){let m=XR(d.error),A=ER(d.error);if(d.error!==void 0){let c=new F(`CLI command failed: ${m.error_code}`,{hint:{disabled:!0}});c.name="PotatoCliError",i.captureException(c,n,{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,$process_person_profile:!1,$geoip_disable:!0,...m,...A})}i.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,...m,...A}});return}i.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...I,command:C,duration_ms:d.durationMs,exit_code:d.exitCode,outcome:d.outcome}})}).catch(()=>{})},submitIssueReport(d){let I=l.then(async()=>{b(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:{...g(),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 C=o[0];if(o.length=0,C!==void 0)throw C});return l=I.catch(()=>{}),I},async shutdown(){try{await l,await i?.shutdown(2000)}catch{}}}}var wn=require("crypto"),Us=require("child_process"),Lr=require("events"),xt=require("fs"),D=require("fs/promises"),ae=require("path"),Os=require("stream"),Yb=require("stream/promises");var mr=require("fs"),Ai=require("path");var pi=()=>Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0,ur=(e,t=pi())=>t?{...e,BUN_BE_BUN:"1"}:e;var ZC=Ai.join("bin","toloka.js"),hC=(e)=>{try{return mr.realpathSync(e)}catch{return e}},Cr=(e)=>{let t=Ai.join(e,ZC);if(mr.existsSync(t))return t;let i=Ai.dirname(e);return i===e?void 0:Cr(i)},fC=(e=process.argv[1])=>(e===void 0?void 0:Cr(Ai.dirname(hC(e))))??Cr(process.cwd()),OR=(e=process.argv[1])=>{let t=e===void 0?void 0:hC(e);if(t!==void 0&&mr.existsSync(t)&&Cr(Ai.dirname(t))!==void 0)return t;let i=Cr(process.cwd());return b(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${ZC} 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},Ko=(e,t,i={})=>{let n=i.executable??process.execPath;if(!(i.native??pi()))return{executable:i.executable??(Reflect.get(process.versions,"bun")?process.execPath:"bun"),args:[OR(i.runtimeEntry),...e],environment:t};let r={...t};return delete r.BUN_BE_BUN,{executable:n,args:[...e],environment:r}};var on=require("fs/promises"),WC=require("path");var rn="auto-update",yC={autoUpdate:!0};class Lo extends F{constructor(e,t){super(e,t);this.name="SettingsError"}}var VC=(e=process.env)=>WC.join(Do(e),"settings.json"),zR=(e)=>{let t=typeof e==="object"&&e!==null?Reflect.get(e,"autoUpdate"):void 0;if(typeof t!=="boolean")return yC;return{autoUpdate:t}};async function pr(e=process.env){try{return zR(JSON.parse(await on.readFile(VC(e),"utf8")))}catch{return yC}}async function jR(e,t=process.env){let i=VC(t);return await Ht(i),await on.writeFile(i,`${JSON.stringify({autoUpdate:e.autoUpdate},null,2)}
|
|
42
42
|
`,{mode:384}),await on.chmod(i,384),i}var DR=(e)=>{if(Qe(e))return!0;if(tn(e))return!1;throw new Lo(`Expected a boolean (true or false), got ${JSON.stringify(e)}.`,{hint:{description:"Run toloka config set auto-update true or false."}})},_R=(e)=>`${rn}=${e.autoUpdate}`,cg=(e,t)=>{if(t===void 0||t.length===0)return{output:_R(e)};if(t!==rn)throw new Lo(`Unknown setting "${t}". Known settings: ${rn}.`,{hint:{disabled:!0}});return{output:String(e.autoUpdate)}};async function BC(e,t,i){if(t!==rn)throw new Lo(`Unknown setting "${t}". Known settings: ${rn}.`,{hint:{disabled:!0}});let n={autoUpdate:DR(i)};return await jR(n,e),{settings:n,output:`Set ${rn} to ${n.autoUpdate}.`}}var wb=require("fs"),Fb=require("child_process"),Hb=require("module"),vb=require("events"),ti=require("fs/promises"),Nd=require("os"),ei=require("path");var wC=require("oxc-parser");var RC=require("oxc-parser"),ug=(e,t,i)=>{let n=RC.parseSync(e,t,{lang:i,preserveParens:!1});return n.errors.some((r)=>r.severity==="Error")?null:n.program},GC=(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 Cg=(e)=>{let t=KR(e.postprocess);if(!t||t.size===0)return[];let i=QR(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.`}})},QR=(e)=>{let t=ug("code.tsx",`(
|
|
@@ -116,7 +116,7 @@ ${e.code}
|
|
|
116
116
|
`)}})};return{data:i(At.data),constants:i(At.constants),preprocess:i(At.preprocess),postprocess:i(At.postprocess),code:i(At.code)}},pg=(e,t)=>{let i=[0];for(let g=0;g<e.length;g+=1)if(e[g]===`
|
|
117
117
|
`)i.push(g+1);let n=(g)=>{let l=0;while(l+1<i.length&&i[l+1]<=g)l+=1;return{line:l,character:g-i[l]}},r=e.split(/\r?\n/gu),o=cF.map(([g,l])=>({key:g,start:e.indexOf(`/* ${l}_START */`)+`/* ${l}_START */`.length+1,end:e.indexOf(`/* ${l}_END */`)-1})),s=(g)=>{let l=o.find((C)=>g>=C.start&&g<=C.end);if(l)return l;let I=o.filter((C)=>C.start<=g).at(-1)??o[0];return R(I,"Task UI diagnostic block is missing"),I},a=uF();for(let g of t){let l=g.labels[0],d=l?.start??e.length,I=s(d),C=g.severity==="Error"?"error":"warning",{line:m,character:A}=n(I.start),{line:c,character:u}=n(d),p=c-m,Z=c===m?u-A:u,h=r[c]??"",W=l?l.end-l.start:0,y=" ".repeat(u)+"^".repeat(W>0?W:1);a[I.key].push({severity:C,text:[`${p}:${Z+1} - [${g.severity}]`,g.message,"",h,y].join(`
|
|
118
118
|
`)})}return a},NC=(e)=>{let t=pg(e,$o.parseSync("runtime.jsx",e).errors);return{...pg(e,$o.parseSync("runtime.tsx",e).errors),preprocess:t.preprocess,postprocess:t.postprocess}},xC=({reactDeclaration:e,elementsDeclaration:t})=>({performTypeCheck:async(i)=>{let n=HC(i),r=vt.createDefaultMapFromNodeModules({target:ze.default.ScriptTarget.Latest},ze.default,IF);r.set("node_modules/@types/react/index.d.ts",e),r.set("node_modules/elements/index.d.ts",t),r.set(sn,n);let o=vt.createSystem(r),{languageService:s}=vt.createVirtualTypeScriptEnvironment(o,[sn],ze.default,{target:ze.default.ScriptTarget.Latest,allowNonTsExtensions:!0,ignoreDeprecations:"6.0",module:ze.default.ModuleKind.CommonJS,moduleResolution:ze.default.ModuleResolutionKind.Node10,noEmit:!0,typeRoots:["node_modules/@types"],jsx:ze.default.JsxEmit.React,jsxFactory:"React.createElement",noErrorTruncation:!0}),a=[],g=[];try{a=s.getSyntacticDiagnostics(sn),g=[...s.getSemanticDiagnostics(sn),...s.getSuggestionDiagnostics(sn),...s.getCompilerOptionsDiagnostics()]}finally{s.dispose()}let l=PC(n,a),d=PC(n,[...a,...g]),I=NC(vC(i));return kC(d,l,I)},performSyntaxCheck:(i)=>{let n=HC(i),r=pg(n,$o.parseSync(sn,n).errors),o=NC(vC(i));return kC(r,r,o)}}),Ag=()=>xC({reactDeclaration:Ar.react.source,elementsDeclaration:Ar.elements.source});var Zg=require("crypto"),an=require("fs/promises"),SC=require("path");var XC="TOLOKA_CHECK_EVIDENCE_DIR",hg="TOLOKA_CHECK_PIPELINE_FINGERPRINT",fg="TOLOKA_CHECK_NODE_ID",Wg="TOLOKA_CHECK_TYPED_ONLY",mF=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),pF=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),bg=(e)=>{if(Array.isArray(e))return e.map(bg);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,bg(i)]))},yg=(e)=>Zg.createHash("sha256").update(JSON.stringify(bg(e))).digest("hex"),AF=(e,t)=>`[toloka:${e}:${t??"pipeline"}]`,YC=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),EC=(e,t)=>t===void 0?YC(`[toloka:${e}:`):YC(AF(e,t));var bF=(e)=>e==="code"||e==="ui"||e==="pipeline",ZF=(e)=>e==="passed"||e==="failed"||e==="infrastructure_error",hF=(e,t)=>{R(mF(e),`Invalid test evidence ${t}`);let i=e;R(i.version===1,`Unsupported test evidence version in ${t}`),R(typeof i.pipelineFingerprint==="string",`Missing pipeline fingerprint in ${t}`),R(bF(i.kind),`Invalid test evidence kind in ${t}`),R(ZF(i.status),`Invalid test evidence status in ${t}`),R(typeof i.testName==="string",`Missing test name in ${t}`),R(i.nodeId===void 0||typeof i.nodeId==="string",`Invalid node id in ${t}`),R(i.diagnostic===void 0||typeof i.diagnostic==="string",`Invalid diagnostic in ${t}`),R(i.partial===void 0||typeof i.partial==="boolean",`Invalid partial coverage in ${t}`),R(i.untestedHardwareFields===void 0||pF(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 TC=async(e)=>{let i=(await an.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=SC.join(e,n),o;try{o=JSON.parse(await an.readFile(r,"utf8"))}catch(s){throw Error(`Invalid test evidence ${r}`,{cause:s})}return hF(o,r)}))};var fF={POTATO_API_KEY:"TOLOKA_API_KEY",POTATO_BASE_URL:"TOLOKA_BASE_URL",POTATO_PROJECT_ID:"TOLOKA_PROJECT_ID"},br=["TOLOKA_API_KEY","POTATO_API_KEY"],JC=(e)=>{let t={...e},i=[];for(let[n,r]of Object.entries(fF)){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 Qr=require("fs/promises"),He=require("path"),Zb=require("url");var Ib=Pe(hd(),1),cb=Pe(gb(),1);var lb={$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:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{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}$"}},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:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","gemini-3.7-flash","claude-sonnet-5","claude-opus-5","claude-fable-5","gpt-5.6-terra","gpt-5.6-luna","gpt-5.6-sol"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{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:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","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:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.6-terra"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.6-terra","gpt-5.6-luna","gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{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:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","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"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var ub=new Ib.default({strict:!1});cb.default(ub);var db=ub.compile(lb),V2=(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 Hd(e){if(db(e))return;let t=db.errors;R(t,"Pipeline graph validation failed without errors");let i=new Set,n=[];for(let r of t){let o=V2(r),s=`${o.path}
|
|
119
|
-
${o.reason}`;if(i.has(s))continue;i.add(s),n.push(o)}throw qi.fromIssues(n)}var B2=Symbol("fieldDefinition"),R2=Symbol.for("@toloka-platform/sdk/pipeline-definition"),mb=Symbol("portDefinition"),G2=Symbol("nodeFieldReferences");function pb(e,t){return{node:e,handle:t,direction:"input",[mb]:"input"}}function Ab(e,t){return{node:e,handle:t,direction:"output",[mb]:"output"}}function bb(e){return typeof e==="object"&&e!==null&&B2 in e}function vd(e,t){if(bb(e)){t.push(e);return}if(Array.isArray(e)){for(let i of e)vd(i,t);return}if(typeof e==="object"&&e!==null)for(let i of Object.values(e))vd(i,t)}function w2(e){let t=[];return vd(e,t),t}function Cb(e){return bb(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function F2(e,t={}){R(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(Cb)},completedFieldProxies:{input:r.map(Cb)}},started:Ab(i,"started"),completed:pb(i,"completed"),[G2]:w2(e)}}var
|
|
119
|
+
${o.reason}`;if(i.has(s))continue;i.add(s),n.push(o)}throw qi.fromIssues(n)}var B2=Symbol("fieldDefinition"),R2=Symbol.for("@toloka-platform/sdk/pipeline-definition"),mb=Symbol("portDefinition"),G2=Symbol("nodeFieldReferences");function pb(e,t){return{node:e,handle:t,direction:"input",[mb]:"input"}}function Ab(e,t){return{node:e,handle:t,direction:"output",[mb]:"output"}}function bb(e){return typeof e==="object"&&e!==null&&B2 in e}function vd(e,t){if(bb(e)){t.push(e);return}if(Array.isArray(e)){for(let i of e)vd(i,t);return}if(typeof e==="object"&&e!==null)for(let i of Object.values(e))vd(i,t)}function w2(e){let t=[];return vd(e,t),t}function Cb(e){return bb(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function F2(e,t={}){R(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(Cb)},completedFieldProxies:{input:r.map(Cb)}},started:Ab(i,"started"),completed:pb(i,"completed"),[G2]:w2(e)}}var pD=Object.assign(F2,{started:Ab("root","started"),completed:pb("root","completed")});function H2(e){return typeof e==="object"&&e!==null&&R2 in e}function Ss(e){R(H2(e),"Invalid pipeline definition: expected a value returned by definePipeline"),R(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;R(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),R(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}Hd(e.graph)}function _r(e,t){let i={version:e.graph.version,fields:e.graph.fields.map((n)=>({...n})),nodes:e.graph.nodes.map((n)=>n.type==="root"?{...n,settings:{...n.settings,datasetId:t.datasetId}}:n),connections:e.graph.connections.map((n)=>({from:{...n.from},to:{...n.to},settings:{...n.settings}}))};return Hd(i),i}var hb=async(e)=>{let t;try{t=await Qr.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=He.join(e,n.name);if(n.isDirectory())i.push(...await hb(r));else if(n.isFile()&&n.name==="pipeline.ts")i.push(r)}return i},v2="toloka.json",k2=async(e)=>{try{return(await Qr.stat(He.join(e,v2))).isFile()}catch{return!1}};async function fb(e){let t=He.resolve(e);for(;;){if(await k2(t))return t;let i=He.dirname(t);if(i===t)return;t=i}}async function Rn(e){let t=await hb(He.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(n)=>{let r=await Qr.stat(n),o=Zb.pathToFileURL(n);o.searchParams.set("version",`${r.mtimeMs}-${r.size}`);let s=await import(o.href);b(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");Ss(a);let g=He.relative(e,He.dirname(n)).split(He.sep).join("/");return{sourceDirectory:g,name:He.basename(g),definition:a}}))).toSorted((n,r)=>n.sourceDirectory.localeCompare(r.sourceDirectory))}}class Gn extends F{phase;constructor(e,t,i){super(t,i);this.name="FreshCheckProcessError",this.phase=e}}var Wb=5000,P2=65536,ii="TOLOKA_INTERNAL_CHECK_RESULT_FILE",N2=(e)=>e.message.length<=Wb?e:{...e,message:`${e.message.slice(0,Wb)}
|
|
120
120
|
\u2026output truncated`},kd=20,yb=async(e)=>{let t=[],i=0,n=!1;for await(let o of e){let s=Buffer.isBuffer(o)?o:Buffer.from(o),a=P2-i;if(a>0){let g=s.subarray(0,a);t.push(g),i+=g.length}if(s.length>a)n=!0}let r=Buffer.concat(t).toString("utf8");return n?`${r}
|
|
121
121
|
\u2026output truncated`:r},xd=async(e,t,i,n,r)=>{r?.throwIfAborted();let o=Fb.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,g,l]=await Promise.all([vb.once(o,"close"),yb(o.stdout),yb(o.stderr)]),d=a[0];return typeof d==="number"?{exitCode:d,stdout:g,stderr:l}:{exitCode:2,stdout:g,stderr:[l,`Process terminated by ${String(a[1])}`].filter(Boolean).join(`
|
|
122
122
|
`),infrastructureError:!0}}finally{r?.removeEventListener("abort",s)}},kb=(e,t,i)=>{let n=Hb.createRequire(ei.join(e,"package.json"));return ei.join(ei.dirname(n.resolve(`${t}/package.json`)),i)},x2=async(e,t,i)=>{try{return await xd(e,process.execPath,[kb(e,"typescript","bin/tsc"),"--noEmit"],ur(t),i)}catch(n){return{exitCode:2,stdout:"",stderr:`Unable to run project TypeScript: ${n instanceof Error?n.message:String(n)}. Install it with \`bun add --dev typescript\`.`,infrastructureError:!0}}},Y2=(e)=>{if(e.exitCode===0)return e;let t=`${e.stderr}
|
|
@@ -148,15 +148,15 @@ save = false
|
|
|
148
148
|
`),D.writeFile(a,"")]);let g=Us.spawn(e.runtimeExecutable,["add",i,`--cwd=${t}`,`--config=${s}`,`--registry=${n}`,"--ignore-scripts","--offline","--no-save","--linker=hoisted"],{cwd:t,env:ur({...process.env,...r,HOME:o,XDG_CONFIG_HOME:o,NPM_CONFIG_USERCONFIG:a,BUN_INSTALL_CACHE_DIR:ae.join(t,"cache")},!0),stdio:["ignore","pipe","pipe"]}),[l,d,I]=await Promise.all([Lr.once(g,"close"),Js(g.stdout),Js(g.stderr)]),C=l[0];if(C===0)return;let m=[I.trim(),d.trim()].filter((A)=>A.length>0).join(`
|
|
149
149
|
`);throw new F(m.length>0?`Embedded Bun package staging failed: ${m}`:`Embedded Bun package staging exited ${String(C)}`,{hint:{description:"Reinstall the Toloka CLI, or disable automatic updates in toloka config."}})},FN=async(e)=>{let t=await D.realpath(e.executablePath),i=await D.lstat(t);if(!i.isFile())throw new F("Refusing to replace a non-file Toloka executable.",{hint:{disabled:!0}});let n=await D.mkdtemp(ae.join(ae.dirname(t),".toloka-update-"));try{let r=ae.join(n,"package.tgz");await GN(e.distribution,r,e.fetchTarball),await wN({stagingDirectory:n,tarballPath:r,registry:e.registry,environment:e.environment,runtimeExecutable:e.runtimeExecutable});let o=ae.join(n,"node_modules",...e.packageName.split("/")),s=JSON.parse(await D.readFile(ae.join(o,"package.json"),"utf8"));if(typeof s!=="object"||s===null||Reflect.get(s,"name")!==e.packageName||Reflect.get(s,"version")!==e.version)throw new F("Staged native CLI package has unexpected metadata.",{hint:{disabled:!0}});let a=ae.join(o,"bin","toloka"),g=ae.join(o,"bin","toloka.sha256"),[l,d,I]=await Promise.all([D.lstat(a),D.lstat(g),D.readFile(g,"utf8")]);if(!l.isFile()||!d.isFile())throw new F("Staged native CLI package has an invalid artifact layout.",{hint:{disabled:!0}});let C=/^([a-f0-9]{64}) toloka\n$/u.exec(I)?.[1];if(C===void 0)throw new F("Staged native CLI package has an invalid checksum file.",{hint:{disabled:!0}});let m=wn.createHash("sha256");for await(let p of xt.createReadStream(a))m.update(p);let A=m.digest(),c=Buffer.from(C,"hex");if(A.length!==c.length||!wn.timingSafeEqual(A,c))throw new F("Staged native CLI executable failed its checksum.",{hint:{disabled:!0}});await D.chmod(a,i.mode&511);let u=await D.open(a,"r");try{await u.sync()}finally{await u.close()}await D.rename(a,t)}finally{await D.rm(n,{recursive:!0,force:!0})}},HN=async({packageName:e,version:t,registry:i,environment:n})=>{let r=Us.spawn(process.execPath,["add","--global",`${e}@${t}`,`--registry=${i}`],{env:{...process.env,...n},stdio:["ignore","pipe","pipe"]}),[o,s,a]=await Promise.all([Lr.once(r,"close"),Js(r.stdout),Js(r.stderr)]),g=o[0];if(g===0)return;let l=[a.trim(),s.trim()].filter((d)=>d.length>0).join(`
|
|
150
150
|
`);throw new F(l.length>0?`bun add --global failed: ${l}`:`bun add --global exited ${String(g)}`,{hint:{description:"Run the bun add --global command yourself, or turn the check off with toloka config set auto-update false."}})},vN=async({argv:e,environment:t})=>{let i=Ko(e,{...process.env,...t,TOLOKA_SKIP_AUTO_UPDATE:"1"}),n=Us.spawn(i.executable,i.args,{env:i.environment,stdio:"inherit"}),[r]=await Lr.once(n,"close");return typeof r==="number"?r:1},Es=()=>({status:"continue"}),kN=async(e)=>{let{argv:t,environment:i,hooks:n,native:r}=e;if(yN(t))return{status:"skip"};if(!r){if(!await(n.isGlobalInstall??(()=>fN()))())return{status:"skip"}}let o=await pr(i);if(!WN(i,o))return{status:"skip"};let s=n.now?.()??new Date,a=await ZN(i);if(a!==void 0){let g=new Date(a.lastCheckedAt).getTime();if(s.getTime()-g<sN)return{status:"skip"}}return{status:"check",now:s}},PN=async(e)=>{let{environment:t,io:i,now:n,currentVersion:r,fetchRegistry:o,packageName:s}=e;try{await hN({lastCheckedAt:n.toISOString()},t)}catch{}let a;try{a=await o(dN(s))}catch(I){return i.stderr(`Auto-update check failed: ${I instanceof Error?I.message:String(I)}.`),{status:"skip"}}let g=pN(a,r);if(g===void 0)return{status:"skip"};let l=Ig(r,g);if(l===void 0||l>=0)return{status:"skip"};let d=AN(a,g);if(d===void 0)return{status:"skip"};if(n.getTime()-d.getTime()<aN)return{status:"skip"};return{status:"update",currentVersion:r,version:g,distribution:a.versions?.[g]?.dist}};async function Xb(e){let{argv:t,environment:i,io:n,hooks:r={}}=e,o=r.isNative?.()??pi(),s=await kN({argv:t,environment:i,hooks:r,native:o});if(s.status==="skip")return Es();let a;try{a=o?cN():fe}catch(d){return n.stderr(`Auto-update check failed: ${Ut(d)}`),Es()}let g=await PN({environment:i,io:n,now:s.now,currentVersion:e.currentVersion??oe,fetchRegistry:r.fetchRegistry??VN,packageName:a});if(g.status==="skip")return Es();try{let d={packageName:a,version:g.version,registry:lN(),environment:i,...g.distribution===void 0?{}:{distribution:g.distribution}};if(r.install!==void 0)await r.install(d);else if(o){if(g.distribution===void 0)throw new ni("npm registry metadata has no native CLI distribution");await FN({...d,distribution:g.distribution,executablePath:r.executablePath?.()??process.execPath,fetchTarball:r.fetchTarball??fetch,runtimeExecutable:r.runtimeExecutable??process.execPath})}else await HN(d)}catch(d){return n.stderr(`Auto-update to ${g.version} failed: ${Ut(d)}`),Es()}return n.stderr(`Updated ${a} from ${g.currentVersion} to ${g.version}.`),{status:"reexec",exitCode:await(r.reexec??vN)({argv:t,environment:i})}}var ge=(e)=>{let t=e.reduce((i,n)=>n.map((r,o)=>Math.max(i[o]??0,r.length)),[]);return e.map((i)=>i.map((n,r)=>n.padEnd(t[r]??n.length)).join(" ").trimEnd()).join(`
|
|
151
|
-
`)},ie=(e,t,i,n)=>{e.stdout(t?JSON.stringify(i,null,2):n)};var Eb=async(e,t,i)=>{let n=[];for await(let r of e.audience.specializations.listAll())n.push(r);ie(i,t.json,n,n.length===0?"No specializations available.":ge([["ID","NAME","EXPERTS"],...n.map((r)=>[r.id,r.name,String(r.expertsCount)])]))};var uI=require("path");var Xd="x-potato-sdk-base-url",NN="pst_",xN="X-Scoped-Token",Tb=(e,t,i)=>{R(e.length>0,"The SDK base URL cannot be empty");let n={Accept:"application/json",[Xd]:new URL(e).toString()};if(t.accessToken!==void 0){let s=t.accessToken;return{headers:n,fetch:i,authorization:async()=>`Bearer ${await s()}`}}let{apiKey:r}=t;R(r.length>0,"The SDK API key cannot be empty");let o=r.startsWith(NN)?{[xN]:r}:{Authorization:`ApiKey ${r}`};return{headers:{...n,...o},fetch:i}},YN=(e,t)=>{let i=(e.method??"GET").toUpperCase();if(i==="GET"||i==="HEAD"||e.body!==void 0)return{...e,headers:t};return t.set("Content-Type","application/json"),{...e,headers:t,body:"{}"}};async function B(e,t){let{fetch:i=globalThis.fetch,authorization:n,...r}=t,o=new Headers(r.headers),s=o.get(Xd);if(R(s,"The SDK base URL is missing"),o.delete(Xd),n!==void 0)o.set("Authorization",await n());let a=await i(new URL(e,s),YN(r,o)),g=await a.text();if(!a.ok){let l=g;if(g.length===0)l=void 0;else if(a.headers.get("content-type")?.includes("application/json"))l=JSON.parse(g);throw te.fromResponse(a.status,l,a.headers.get("x-request-id")??void 0)}return g.length===0?void 0:JSON.parse(g)}var SN=()=>"/api/v2-beta/base-models",Jb=async(e)=>B(SN(),{...e,method:"GET"}),XN=(e)=>`/api/v2-beta/base-models/${e}`,Ub=async(e,t)=>B(XN(e),{...t,method:"GET"}),EN=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/models?${n}`:`/api/v2-beta/projects/${e}/models`},Ed=async(e,t,i)=>B(EN(e,t),{...i,method:"GET"}),TN=(e)=>`/api/v2-beta/projects/${e}/models`,Ob=async(e,t,i)=>B(TN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),JN=(e,t,i)=>{let n=new URLSearchParams;Object.entries(i||{}).forEach(([o,s])=>{if(s!==void 0)n.append(o,s===null?"null":s.toString())});let r=n.toString();return r.length>0?`/api/v2-beta/projects/${e}/models/${t}/versions?${r}`:`/api/v2-beta/projects/${e}/models/${t}/versions`},Td=async(e,t,i,n)=>B(JN(e,t,i),{...n,method:"GET"}),UN=(e)=>`/api/v2-beta/model-versions/${e}`,zb=async(e,t)=>B(UN(e),{...t,method:"GET"}),ON=(e)=>`/api/v2-beta/model-versions/${e}/content`,jb=async(e,t)=>B(ON(e),{...t,method:"GET"}),zN=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}/archive`,Db=async(e,t,i)=>B(zN(e,t),{...i,method:"POST"}),jN=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}`,_b=async(e,t,i)=>B(jN(e,t),{...i,method:"GET"}),DN=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/trainings?${n}`:`/api/v2-beta/projects/${e}/trainings`},Jd=async(e,t,i)=>B(DN(e,t),{...i,method:"GET"}),_N=(e)=>`/api/v2-beta/projects/${e}/trainings`,Qb=async(e,t,i)=>B(_N(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),QN=(e)=>`/api/v2-beta/trainings/${e}`,Kb=async(e,t)=>B(QN(e),{...t,method:"GET"}),KN=(e)=>`/api/v2-beta/trainings/${e}`,Lb=async(e,t,i)=>B(KN(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),LN=(e)=>`/api/v2-beta/trainings/${e}/configuration`,Mb=async(e,t,i)=>B(LN(e),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),MN=(e)=>`/api/v2-beta/trainings/${e}/cost-estimate-inputs`,$b=async(e,t,i)=>B(MN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),$N=(e)=>`/api/v2-beta/trainings/${e}/cost-estimate`,qb=async(e,t,i)=>B($N(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),qN=(e)=>`/api/v2-beta/trainings/${e}/runs`,eZ=async(e,t,i)=>B(qN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),ex=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/trainings/${e}/runs?${n}`:`/api/v2-beta/trainings/${e}/runs`},Ud=async(e,t,i)=>B(ex(e,t),{...i,method:"GET"}),tx=(e)=>`/api/v2-beta/training-runs/${e}`,tZ=async(e,t)=>B(tx(e),{...t,method:"GET"}),ix=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/training-runs/${e}/logs?${n}`:`/api/v2-beta/training-runs/${e}/logs`},iZ=async(e,t,i)=>B(ix(e,t),{...i,method:"GET"}),nx=(e)=>`/api/v2-beta/training-runs/${e}/metrics`,nZ=async(e,t)=>B(nx(e),{...t,method:"GET"}),rx=(e,t,i)=>{let n=new URLSearchParams;Object.entries(i||{}).forEach(([o,s])=>{if(s!==void 0)n.append(o,s===null?"null":s.toString())});let r=n.toString();return r.length>0?`/api/v2-beta/training-runs/${e}/metrics/${t}?${r}`:`/api/v2-beta/training-runs/${e}/metrics/${t}`},rZ=async(e,t,i,n)=>B(rx(e,t,i),{...n,method:"GET"}),ox=(e)=>`/api/v2-beta/training-runs/${e}/resume`,oZ=async(e,t)=>B(ox(e),{...t,method:"POST"}),sx=(e)=>`/api/v2-beta/training-runs/${e}/cancel`,sZ=async(e,t)=>B(sx(e),{...t,method:"POST"}),ax=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([n,r])=>{if(r!==void 0)t.append(n,r===null?"null":r.toString())});let i=t.toString();return i.length>0?`/api/v2-beta/audience/specializations?${i}`:"/api/v2-beta/audience/specializations"},Od=async(e,t)=>B(ax(e),{...t,method:"GET"}),gx=()=>"/api/v2-beta/me",aZ=async(e)=>B(gx(),{...e,method:"GET"}),lx=()=>"/api/v2-beta/delivery-orders",gZ=async(e)=>B(lx(),{...e,method:"GET"}),dx=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([n,r])=>{if(r!==void 0)t.append(n,r===null?"null":r.toString())});let i=t.toString();return i.length>0?`/api/v2-beta/projects?${i}`:"/api/v2-beta/projects"},zd=async(e,t)=>B(dx(e),{...t,method:"GET"}),Ix=()=>"/api/v2-beta/projects",lZ=async(e,t)=>B(Ix(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),cx=(e)=>`/api/v2-beta/projects/${e}`,dZ=async(e,t)=>B(cx(e),{...t,method:"GET"}),ux=(e)=>`/api/v2-beta/projects/${e}`,IZ=async(e,t,i)=>B(ux(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Cx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/pipelines?${n}`:`/api/v2-beta/projects/${e}/pipelines`},jd=async(e,t,i)=>B(Cx(e,t),{...i,method:"GET"}),mx=(e)=>`/api/v2-beta/pipelines/${e}`,cZ=async(e,t)=>B(mx(e),{...t,method:"GET"}),px=(e)=>`/api/v2-beta/pipelines/${e}`,uZ=async(e,t,i)=>B(px(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Ax=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/datasets?${n}`:`/api/v2-beta/projects/${e}/datasets`},Dd=async(e,t,i)=>B(Ax(e,t),{...i,method:"GET"}),bx=(e)=>`/api/v2-beta/projects/${e}/datasets`,CZ=async(e,t,i)=>B(bx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Zx=(e)=>`/api/v2-beta/datasets/${e}`,mZ=async(e,t)=>B(Zx(e),{...t,method:"GET"}),hx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/datasets/${e}/fields?${n}`:`/api/v2-beta/datasets/${e}/fields`},_d=async(e,t,i)=>B(hx(e,t),{...i,method:"GET"}),fx=(e)=>`/api/v2-beta/datasets/${e}/fields`,Qd=async(e,t,i)=>B(fx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Wx=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,pZ=async(e,t)=>B(Wx(e),{...t,method:"GET"}),yx=(e)=>`/api/v2-beta/datasets/${e}/items`,AZ=async(e,t,i)=>B(yx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Vx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/datasets/${e}/items?${n}`:`/api/v2-beta/datasets/${e}/items`},Kd=async(e,t,i)=>B(Vx(e,t),{...i,method:"GET"}),Bx=(e)=>`/api/v2-beta/datasets/${e}/uploads`,bZ=async(e,t,i)=>B(Bx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Rx=(e)=>`/api/v2-beta/uploads/${e}/finalize`,ZZ=async(e,t)=>B(Rx(e),{...t,method:"POST"}),Gx=(e)=>`/api/v2-beta/uploads/${e}/cancel`,hZ=async(e,t)=>B(Gx(e),{...t,method:"POST"}),wx=(e)=>`/api/v2-beta/uploads/${e}`,Ld=async(e,t)=>B(wx(e),{...t,method:"GET"}),Fx=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,fZ=async(e,t,i)=>B(Fx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Hx=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,WZ=async(e,t,i)=>B(Hx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),vx=(e)=>`/api/v2-beta/pipelines/${e}/export`,yZ=async(e,t)=>B(vx(e),{...t,method:"GET"}),kx=(e)=>`/api/v2-beta/pipelines/${e}/copy`,VZ=async(e,t,i)=>B(kx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Px=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,BZ=async(e,t,i)=>B(Px(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Nx=(e)=>`/api/v2-beta/pipelines/${e}/runs`,RZ=async(e,t)=>B(Nx(e),{...t,method:"POST"}),xx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/pipelines/${e}/runs?${n}`:`/api/v2-beta/pipelines/${e}/runs`},Md=async(e,t,i)=>B(xx(e,t),{...i,method:"GET"}),Yx=(e)=>`/api/v2-beta/runs/${e}`,$d=async(e,t)=>B(Yx(e),{...t,method:"GET"});var Sx=(e)=>`/api/v2-beta/runs/${e}/cancel`,GZ=async(e,t)=>B(Sx(e),{...t,method:"POST"});var Xx=(e)=>`/api/v2-beta/datasets/${e}/exports`,wZ=async(e,t,i)=>B(Xx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Ex=(e)=>`/api/v2-beta/exports/${e}`,qd=async(e,t)=>B(Ex(e),{...t,method:"GET"}),Tx=(e)=>`/api/v2-beta/pipelines/${e}/graph`,FZ=async(e,t)=>B(Tx(e),{...t,method:"GET"}),Jx=(e)=>`/api/v2-beta/pipelines/${e}/graph`,HZ=async(e,t,i)=>B(Jx(e),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Ux=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,vZ=async(e,t,i)=>B(Ux(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Ox=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,kZ=async(e,t,i,n)=>B(Ox(e,t),{...n,method:"PATCH",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(i)}),zx=(e)=>`/api/v2-beta/projects/${e}/tokens`,PZ=async(e,t,i)=>B(zx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),jx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/tokens?${n}`:`/api/v2-beta/projects/${e}/tokens`},eI=async(e,t,i)=>B(jx(e,t),{...i,method:"GET"}),Dx=(e)=>`/api/v2-beta/projects/${e}/tokens`,NZ=async(e,t)=>B(Dx(e),{...t,method:"DELETE"}),_x=(e,t)=>`/api/v2-beta/projects/${e}/tokens/${t}`,xZ=async(e,t,i)=>B(_x(e,t),{...i,method:"DELETE"}),Qx=()=>"/api/v2-beta/tokens/current",YZ=async(e)=>B(Qx(),{...e,method:"DELETE"}),Kx=(e)=>`/api/v2-beta/projects/${e}/secrets`,SZ=async(e,t)=>B(Kx(e),{...t,method:"GET"}),Lx=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,XZ=async(e,t,i,n)=>B(Lx(e,t),{...n,method:"PUT",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(i)}),Mx=(e)=>`/api/v2-beta/projects/${e}/files`,EZ=async(e,t)=>B(Mx(e),{...t,method:"GET"}),$x=(e)=>`/api/v2-beta/projects/${e}/files`,TZ=async(e,t,i)=>B($x(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),qx=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,JZ=async(e,t,i)=>B(qx(e,t),{...i,method:"POST"}),eY=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,UZ=async(e,t,i)=>B(eY(e,t),{...i,method:"DELETE"}),tY=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/runs/${e}/items?${n}`:`/api/v2-beta/runs/${e}/items`},tI=async(e,t,i)=>B(tY(e,t),{...i,method:"GET"}),iY=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,OZ=async(e,t,i)=>B(iY(e,t),{...i,method:"GET"}),nY=(e)=>`/api/v2-beta/pipelines/${e}/checks`,zZ=async(e,t)=>B(nY(e),{...t,method:"GET"}),rY=(e)=>`/api/v2-beta/pipelines/${e}/checks`,jZ=async(e,t,i)=>B(rY(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),oY=(e)=>`/api/v2-beta/checks/${e}`,iI=async(e,t)=>B(oY(e),{...t,method:"GET"});async function*Ee(e,t={}){let i=t.offset;while(!0){let n=await e({limit:t.limit,offset:i});if(yield*n.items,!n.pagination.hasMore)return;i=n.pagination.offset+n.pagination.limit}}var Mr=async(e,t,i={})=>{let n=i.timeoutMs??60000,r=i.intervalMs??1000;R(Number.isFinite(n)&&n>=0,"The wait timeout must be a nonnegative finite number"),R(Number.isFinite(r)&&r>0,"The polling interval must be a positive finite number");let o=Date.now()+n,s=new AbortController,a=setTimeout(()=>s.abort(),n);try{while(!0){if(s.signal.aborted)throw te.waitTimeout(n);let g=await e(s.signal);if(t(g))return g;let l=o-Date.now();if(l<=0)throw te.waitTimeout(n);let{promise:d,resolve:I}=Promise.withResolvers();setTimeout(I,Math.min(r,l)),await d}}catch(g){if(s.signal.aborted)throw te.waitTimeout(n);throw g}finally{clearTimeout(a)}};var aY=(e)=>{let t=Tb(e.baseUrl,e,e.fetch);async function i(c,u){switch(c.type){case"datasetUpload":return Mr((p)=>Ld(c.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"datasetExport":return Mr((p)=>qd(c.exportId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"pipelineCheck":return Mr((p)=>iI(c.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"pipelineRun":return Mr((p)=>$d(c.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u)}}return{me:()=>aZ(t),audience:{specializations:{listPage:(c={})=>Od(c,t),listAll:(c={})=>Ee(async(u)=>{let p=await Od({...c,...u},t);return{items:p.specializations,pagination:p.pagination}},c)}},projects:{create:(c)=>lZ(c,t),get:({projectId:c})=>dZ(c,t),update:({projectId:c,...u})=>IZ(c,u,t),listPage:(c={})=>zd(c,t),listAll:(c={})=>Ee(async(u)=>{let p=await zd({...c,...u},t);return{items:p.projects,pagination:p.pagination}},c),createToken:({projectId:c,...u})=>PZ(c,u,t),listTokens:({projectId:c,...u})=>eI(c,u,t),listAllTokens:({projectId:c,...u})=>Ee(async(p)=>{let Z=await eI(c,{...u,...p},t);return{items:Z.tokens,pagination:Z.pagination}},u),revokeToken:({projectId:c,tokenId:u})=>xZ(c,u,t),revokeAllTokens:({projectId:c})=>NZ(c,t),revokeCurrentToken:()=>YZ(t)},pipelines:{import:({projectId:c,...u})=>fZ(c,u,t),get:({pipelineId:c})=>cZ(c,t),update:({pipelineId:c,...u})=>uZ(c,u,t),listPage:({projectId:c,...u})=>jd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await jd(c,{...u,...p},t);return{items:Z.pipelines,pagination:Z.pagination}},u),getGraph:({pipelineId:c})=>FZ(c,t),replaceGraph:({pipelineId:c,...u})=>HZ(c,"version"in u?{graph:u.graph,expectedVersion:u.version}:u,t),validateGraph:({pipelineId:c,...u})=>vZ(c,u,t),estimateCost:({pipelineId:c,...u})=>BZ(c,u,t),patchNode:({pipelineId:c,nodeId:u,...p})=>kZ(c,u,p,t),attachDataset:({pipelineId:c,...u})=>WZ(c,u,t),export:({pipelineId:c})=>yZ(c,t),copy:({pipelineId:c,...u})=>VZ(c,u,t)},datasets:{create:({projectId:c,...u})=>CZ(c,u,t),get:({datasetId:c})=>mZ(c,t),listPage:({projectId:c,...u})=>Dd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Dd(c,{...u,...p},t);return{items:Z.datasets,pagination:Z.pagination}},u),createField:async({datasetId:c,...u})=>{let p=await Qd(c,u,t);return R(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:c,fields:u})=>{let p=await Qd(c,{fields:u},t);return R("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:c,...u})=>_d(c,u,t),getInferredFields:({datasetId:c})=>pZ(c,t),listAllFields:({datasetId:c,...u})=>Ee(async(p)=>{let Z=await _d(c,{...u,...p},t);return{items:Z.fields,pagination:Z.pagination}},u),appendItems:({datasetId:c,...u})=>AZ(c,u,t),listItemsPage:({datasetId:c,...u})=>Kd(c,u,t),listAllItems:({datasetId:c,...u})=>Ee(async(p)=>{let Z=await Kd(c,{...u,...p},t);return{items:Z.items,pagination:Z.pagination}},u),startUpload:({datasetId:c,...u})=>bZ(c,u,t),finalizeUpload:({uploadId:c})=>ZZ(c,t),cancelUpload:({uploadId:c})=>hZ(c,t),getUpload:({uploadId:c})=>Ld(c,t),startExport:({datasetId:c,...u})=>wZ(c,u,t),getExport:({exportId:c})=>qd(c,t)},baseModels:{list:async()=>(await Jb(t)).baseModels,get:({id:c})=>Ub(c,t)},models:{listPage:({projectId:c,...u})=>Ed(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Ed(c,{...u,...p},t);return{items:Z.models,pagination:Z.pagination}},u),get:({projectId:c,modelId:u})=>_b(c,u,t),listVersionsPage:({projectId:c,modelId:u,...p})=>Td(c,u,p,t),listAllVersions:({projectId:c,modelId:u,...p})=>Ee(async(Z)=>{let h=await Td(c,u,{...p,...Z},t);return{items:h.versions,pagination:h.pagination}},p),create:({projectId:c,...u})=>Ob(c,u,t),getVersion:({modelVersionId:c})=>zb(c,t),getVersionContent:({modelVersionId:c})=>jb(c,t),archive:({projectId:c,modelId:u})=>{let p=new Headers(t.headers);return p.set("Content-Type","application/json"),Db(c,u,{...t,headers:p})}},trainings:{listPage:({projectId:c,...u})=>Jd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Jd(c,{...u,...p},t);return{items:Z.trainings,pagination:Z.pagination}},u),get:({trainingId:c})=>Kb(c,t),create:({projectId:c,...u})=>Qb(c,u,t),updateMetadata:({trainingId:c,...u})=>Lb(c,u,t),replaceConfiguration:({trainingId:c,...u})=>Mb(c,u,t),prepareCostEstimateInputs:({trainingId:c,idempotencyKey:u,...p})=>{let Z=new Headers(t.headers);return Z.set("Idempotency-Key",u),$b(c,p,{...t,headers:Object.fromEntries(Z.entries())})},estimateCost:({trainingId:c,...u})=>qb(c,u,t),resumeRun:({trainingRunId:c})=>oZ(c,t),cancelRun:({trainingRunId:c})=>sZ(c,t),createRun:({trainingId:c,idempotencyKey:u,...p})=>{let Z=new Headers(t.headers);return Z.set("Idempotency-Key",u),eZ(c,p,{...t,headers:Object.fromEntries(Z.entries())})},listRunsPage:({trainingId:c,...u})=>Ud(c,u,t),listAllRuns:({trainingId:c,...u})=>Ee(async(p)=>{let Z=await Ud(c,{...u,...p},t);return{items:Z.trainingRuns,pagination:Z.pagination}},u),getRun:({trainingRunId:c})=>tZ(c,t),getRunLogs:({trainingRunId:c,...u})=>iZ(c,u,t),getRunMetrics:({trainingRunId:c})=>nZ(c,t),getRunMetricHistory:({trainingRunId:c,metricKey:u,...p})=>rZ(c,u,p,t)},runs:{start:({pipelineId:c})=>RZ(c,t),get:({runId:c})=>$d(c,t),cancel:({runId:c})=>GZ(c,t),listPage:({pipelineId:c,...u})=>Md(c,u,t),listAll:({pipelineId:c,...u})=>Ee(async(p)=>{let Z=await Md(c,{...u,...p},t);return{items:Z.runs,pagination:Z.pagination}},u),listItemsPage:({runId:c,...u})=>tI(c,u,t),listAllItems:({runId:c,...u})=>Ee(async(p)=>{let Z=await tI(c,{...u,...p},t);return{items:Z.items,pagination:Z.pagination}},u),getItem:({runId:c,itemId:u})=>OZ(c,u,t)},secrets:{list:async({projectId:c})=>(await SZ(c,t)).secrets,set:({projectId:c,name:u,...p})=>XZ(c,u,p,t)},files:{list:async({projectId:c})=>(await EZ(c,t)).files,startUpload:({projectId:c,...u})=>TZ(c,u,t),finalizeUpload:({projectId:c,fileId:u})=>JZ(c,u,t),delete:({projectId:c,fileId:u})=>UZ(c,u,t)},checks:{list:async({pipelineId:c})=>(await zZ(c,t)).checks,start:({pipelineId:c,...u})=>jZ(c,u,t),get:({checkRunId:c})=>iI(c,t)},deliveryOrders:{list:async()=>(await gZ(t)).deliveryOrders},waitFor:i}};function Fn(e){return aY(e)}var Hn=require("fs/promises"),nI=require("path"),_Z=Pe(hd(),1);var Gi="toloka.json";class rI extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var gY="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",lY={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:gY},additionalProperties:{type:"object",properties:{pipelineId:{type:"string",minLength:1}},required:["pipelineId"],additionalProperties:!1}},datasets:{type:"object",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",properties:{datasetId:{type:"string",minLength:1}},required:["datasetId"],additionalProperties:!1}}},required:["projectId","pipelines","datasets"],additionalProperties:!1},dY=new _Z.default({allErrors:!0,strict:!1}),DZ=dY.compile(lY);function IY(e){let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return`${typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/"}: ${e.message??`failed ${e.keyword} validation`}`}function QZ(e){if(DZ(e))return e;let t=DZ.errors;throw R(t,"toloka.json validation failed without errors"),new rI(`Invalid toloka.json: ${t.map(IY).join("; ")}`)}async function Ae(e){let t;try{t=await Hn.readFile(nI.join(e,Gi),"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;throw i}try{return QZ(JSON.parse(t))}catch(i){if(i instanceof SyntaxError)throw new rI(`Invalid toloka.json: ${i.message}`,{cause:i});throw i}}async function ri(e,t){let i=QZ(t),n=Object.fromEntries(Object.entries(i.pipelines).sort(([o],[s])=>o<s?-1:o>s?1:0)),r=Object.fromEntries(Object.entries(i.datasets).sort(([o],[s])=>o<s?-1:o>s?1:0));await Hn.mkdir(e,{recursive:!0}),await Hn.writeFile(nI.join(e,Gi),`${JSON.stringify({projectId:i.projectId,pipelines:n,datasets:r},null,2)}
|
|
152
|
-
`,"utf8")}var rh=require("crypto"),Yt=require("fs/promises"),oh=require("os"),kn=require("path");var KZ=15000,LZ={alias:"google",name:"Google",variant:"outline",hint:"google"},MZ={alias:"ms",name:"Microsoft",variant:"outline",hint:"ms"},
|
|
153
|
-
`,{mode:384,flag:"wx"}),await Yt.rename(r,n)}catch(o){throw await Yt.rm(r,{force:!0}),o}return n}async function sh(e,t=process.env){let i=Ds(e,t);try{return await Yt.rm(i),i}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return;throw n}}async function _s(e,t=process.env){let i=zs(e);if(i===void 0)return;let n=await $r(i,t);if(n===void 0)return;return{provider:i,session:n,path:Ds(i,t)}}var
|
|
154
|
-
`);return e.io.stdout(o),{output:o}}async function dh(e){let t=await Ae(e.sourceRoot);b(t,`No ${Gi} found in ${e.sourceRoot}.`,{hint:{description:"Run toloka init in the source root, or cd into the checkout that holds toloka.json."}});let i=e.type==="pipeline"?t.pipelines:t.datasets,n=i[e.name];b(n,`${e.type==="pipeline"?"Pipeline":"Dataset"} ${e.name} is not tracked.`,{hint:{description:"Open toloka.json to see the tracked pipelines and datasets."}});let r="pipelineId"in n?n.pipelineId:n.datasetId,o=`${e.type} ${e.name} (${r})`;if(!e.confirm){b(e.io.prompt,`Refusing to untrack ${o} without confirmation. Pass --confirm after reviewing ${Gi}.`,{hint:{disabled:!0}});let g=(await e.io.prompt(`Untrack ${o}? The live resource will not be deleted. [y/N] `)).trim().toLowerCase();b(g==="y"||g==="yes","Untrack canceled.",{hint:{disabled:!0}})}let s=Object.fromEntries(Object.entries(i).filter(([g])=>g!==e.name));await ri(e.sourceRoot,{...t,...e.type==="pipeline"?{pipelines:s}:{datasets:s}});let a=`Untracked ${o}. The live ${e.type} was not deleted.`;return e.io.stdout(a),{output:a}}async function Ih(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias??await dI(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),n=ve(e.projectId)??await dI(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),r=qr(t.credentials.projects,i);b(r===void 0||r.id===n,`Alias ${i} already points at ${r?.id}. Run toloka project remove ${i} first.`,{hint:{disabled:!0}}),await e.afterPreflight?.();let o=await e.client.projects.get({projectId:n});await Ms(gh(t.credentials,i,{id:o.id,name:o.name}),e.environment);let s=`Using project ${o.id} as ${i}.`;return e.io?.stdout(s),{output:s,alias:i,projectId:o.id}}async function ch(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias),n=qr(t.credentials.projects,i);b(n,`Unknown project alias ${i}.`,{hint:{description:"Run toloka project add <alias> <project-id> to register it, or check the alias spelling."}}),await Ms({...t.credentials,current:i},e.environment);let r=`Using project ${n.id} as ${i}.`;return e.io?.stdout(r),{output:r}}async function uh(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias),n=Object.assign(Object.create(null),t.credentials.projects??{});b(qr(n,i),`Unknown project alias ${i}.`,{hint:{description:"Run toloka project add <alias> <project-id> to register it, or check the alias spelling."}}),delete n[i];let r=t.credentials.current===i?void 0:t.credentials.current;await Ms({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...r===void 0?{}:{current:r},...Object.keys(n).length===0?{}:{projects:n}},e.environment);let o=`Removed local alias ${i}.`;return e.io?.stdout(o),{output:o}}function Ch(e){let t=Fi(e),i=t===void 0?
|
|
155
|
-
`),{cause:r,hint:{description:`The project exists. Make ${e} writable, then run toloka --project-id ${i.id} init to bind it.`}})}return}if(t.projectId===i.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function mh(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias??await dI(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));b(t.credentials.projects?.[i]===void 0,`Alias ${i} already exists. Run toloka project remove ${i} first.`,{hint:{disabled:!0}});let n=e.sourceRoot===void 0?void 0:await Ae(e.sourceRoot);await e.afterPreflight?.();let r=await
|
|
156
|
-
`),{cause:l,hint:{disabled:!0}})}let a=[`Created project ${s.id} as ${i}.`];if(e.sourceRoot!==void 0){let l=await
|
|
157
|
-
`);return e.io?.stdout(g),{output:g,projectId:s.id,alias:i}}var Hi="https://platform.toloka.ai",
|
|
158
|
-
`),cI=(e,t,i)=>e.apiKey??t.TOLOKA_API_KEY??i?.apiKey,xn=(e,t,i)=>e.baseUrl??t.TOLOKA_BASE_URL??oi(t)??i?.baseUrl??Hi;function Ah(e,t,i,n,r){let o=cI(e,i,n),s=xn(e,i,n),a=Fi({flags:e,state:t,environment:i,stored:n,effectiveBaseUrl:s}),g=o!==void 0?{type:"apiKey",apiKey:o}:r!==void 0?{type:"browser",provider:r}:void 0;return b(g,
|
|
159
|
-
`),Zh=(e)=>{if(e!=="human"&&e!=="agent")throw new Ze('Expected "human" or "agent".');return e},Te=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Ze("Expected a positive integer.");return t};var hh=(e)=>{if(e!=="sft"&&e!=="gisting")throw new Ze('Expected training method "sft" or "gisting".');return e},CI=(e)=>{let t=Number(e);if(t!==8&&t!==16&&t!==32)throw new Ze("Expected a LoRA rank of 8, 16, or 32.");return t},mI=(e)=>{if(e==="1/4"||e==="1/8"||e==="1/16"||e==="1/32")return e;let t=Number(e);if(t!==8&&t!==32&&t!==64)throw new Ze('Expected 8, 32, or 64 gist tokens, or a fraction of the prompt: "1/4", "1/8", "1/16", or "1/32".');return t},pI=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<1||t>5)throw new Ze("Expected epochs from 1 through 5.");return t},AI=(e)=>{let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Ze("Expected a positive learning rate, for example 0.00015.");return t},bI=(e)=>{let t=Number(e);if(t!==8&&t!==16&&t!==32&&t!==64)throw new Ze("Expected a batch size of 8, 16, 32, or 64.");return t},ZI=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<64||t>16384)throw new Ze("Expected a maximum sequence length from 64 through 16384 tokens.");return t},hI=(e)=>({method:e.method,baseModelId:e.baseModel,modelVersionId:e.modelVersion,datasetId:e.dataset,validationDatasetId:e.validationDataset,trainingFilter:e.trainFilter,validationFilter:e.validationFilter,loraRank:e.loraRank,gistTokens:e.gistTokens,epochs:e.epochs,learningRate:e.learningRate,batchSize:e.batchSize,maxSequenceLength:e.maxSequenceLength,promptFilePath:e.promptFile}),qs=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},Be=async(e,t)=>{if(e.sourceRoot!==void 0)return uI.resolve(e.sourceRoot);let i=process.cwd(),n=await fb(i);if(n===void 0||n===i)return i;return t.stderr(`Using project root ${n} (found from ${i}).`),n},ea=(e)=>e.sourceRoot===void 0?process.cwd():uI.resolve(e.sourceRoot),fI=async(e,t)=>{let{found:i,warning:n}=await en(t.environment,e.apiKey??t.environment.TOLOKA_API_KEY);if(n!==void 0)t.io.stderr(n);return i?.credentials},vi=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},ki=async(e,t,i,n)=>{let{environment:r}=t,o=cI(e,r,n)===void 0?(await _s(xn(e,r,n),r))?.provider:void 0,s=Ah(e,i,r,n,o),{baseUrl:a,credential:g}=s,l=t.injectedClient??Fn(g.type==="apiKey"?{baseUrl:a,apiKey:g.apiKey}:{baseUrl:a,accessToken:Qs({provider:g.provider,baseUrl:a,environment:r})});return{config:s,client:l}},w=async(e,t)=>{let i=await Be(e,t.io),n=await Ae(i),r=await fI(e,t),{config:o,client:s}=await ki(e,t,n,r);return await vi(s,t.analytics),{sourceRoot:i,client:s,baseUrl:o.baseUrl,state:n,stored:r,...o.projectId===void 0?{}:{projectId:o.projectId}}},ta=(e,t,i,n)=>Fi({flags:e,environment:t.environment,stored:i,...n===void 0?{}:{state:n}});var fh=(e,t)=>{let{context:i,globals:n}=t;e.command("audience").description("inspect the expert audience catalog used by node audience filters").command("specialization").description("expert specializations (platform qualifications)").command("list").option("--json","print JSON",!1).description("list specializations with their id, name, and expert count").action(async(s)=>{let{client:a}=await w(n(),i);await Eb(a,{json:s.json},i.io)})};var wh=require("child_process"),eo=require("crypto"),Fh=require("http");var Pi=(e)=>e.replace(/[&<>"']/gu,(t)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t);var
|
|
151
|
+
`)},ie=(e,t,i,n)=>{e.stdout(t?JSON.stringify(i,null,2):n)};var Eb=async(e,t,i)=>{let n=[];for await(let r of e.audience.specializations.listAll())n.push(r);ie(i,t.json,n,n.length===0?"No specializations available.":ge([["ID","NAME","EXPERTS"],...n.map((r)=>[r.id,r.name,String(r.expertsCount)])]))};var uI=require("path");var Xd="x-potato-sdk-base-url",NN="pst_",xN="X-Scoped-Token",Tb=(e,t,i)=>{R(e.length>0,"The SDK base URL cannot be empty");let n={Accept:"application/json",[Xd]:new URL(e).toString()};if(t.accessToken!==void 0){let s=t.accessToken;return{headers:n,fetch:i,authorization:async()=>`Bearer ${await s()}`}}let{apiKey:r}=t;R(r.length>0,"The SDK API key cannot be empty");let o=r.startsWith(NN)?{[xN]:r}:{Authorization:`ApiKey ${r}`};return{headers:{...n,...o},fetch:i}},YN=(e,t)=>{let i=(e.method??"GET").toUpperCase();if(i==="GET"||i==="HEAD"||e.body!==void 0)return{...e,headers:t};return t.set("Content-Type","application/json"),{...e,headers:t,body:"{}"}},SN=(e,t)=>{if(!e.startsWith("/")||e.startsWith("//"))return new URL(e,t);let i=new URL(t);return new URL(`${i.pathname.replace(/\/+$/,"")}${e}`,i.origin)};async function B(e,t){let{fetch:i=globalThis.fetch,authorization:n,...r}=t,o=new Headers(r.headers),s=o.get(Xd);if(R(s,"The SDK base URL is missing"),o.delete(Xd),n!==void 0)o.set("Authorization",await n());let a=await i(SN(e,s),YN(r,o)),g=await a.text();if(!a.ok){let l=g;if(g.length===0)l=void 0;else if(a.headers.get("content-type")?.includes("application/json"))l=JSON.parse(g);throw te.fromResponse(a.status,l,a.headers.get("x-request-id")??void 0)}return g.length===0?void 0:JSON.parse(g)}var XN=()=>"/api/v2-beta/base-models",Jb=async(e)=>B(XN(),{...e,method:"GET"}),EN=(e)=>`/api/v2-beta/base-models/${e}`,Ub=async(e,t)=>B(EN(e),{...t,method:"GET"}),TN=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/models?${n}`:`/api/v2-beta/projects/${e}/models`},Ed=async(e,t,i)=>B(TN(e,t),{...i,method:"GET"}),JN=(e)=>`/api/v2-beta/projects/${e}/models`,Ob=async(e,t,i)=>B(JN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),UN=(e,t,i)=>{let n=new URLSearchParams;Object.entries(i||{}).forEach(([o,s])=>{if(s!==void 0)n.append(o,s===null?"null":s.toString())});let r=n.toString();return r.length>0?`/api/v2-beta/projects/${e}/models/${t}/versions?${r}`:`/api/v2-beta/projects/${e}/models/${t}/versions`},Td=async(e,t,i,n)=>B(UN(e,t,i),{...n,method:"GET"}),ON=(e)=>`/api/v2-beta/model-versions/${e}`,zb=async(e,t)=>B(ON(e),{...t,method:"GET"}),zN=(e)=>`/api/v2-beta/model-versions/${e}/content`,jb=async(e,t)=>B(zN(e),{...t,method:"GET"}),jN=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}/archive`,Db=async(e,t,i)=>B(jN(e,t),{...i,method:"POST"}),DN=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}`,_b=async(e,t,i)=>B(DN(e,t),{...i,method:"GET"}),_N=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/trainings?${n}`:`/api/v2-beta/projects/${e}/trainings`},Jd=async(e,t,i)=>B(_N(e,t),{...i,method:"GET"}),QN=(e)=>`/api/v2-beta/projects/${e}/trainings`,Qb=async(e,t,i)=>B(QN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),KN=(e)=>`/api/v2-beta/trainings/${e}`,Kb=async(e,t)=>B(KN(e),{...t,method:"GET"}),LN=(e)=>`/api/v2-beta/trainings/${e}`,Lb=async(e,t,i)=>B(LN(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),MN=(e)=>`/api/v2-beta/trainings/${e}/configuration`,Mb=async(e,t,i)=>B(MN(e),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),$N=(e)=>`/api/v2-beta/trainings/${e}/cost-estimate-inputs`,$b=async(e,t,i)=>B($N(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),qN=(e)=>`/api/v2-beta/trainings/${e}/cost-estimate`,qb=async(e,t,i)=>B(qN(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),ex=(e)=>`/api/v2-beta/trainings/${e}/runs`,eZ=async(e,t,i)=>B(ex(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),tx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/trainings/${e}/runs?${n}`:`/api/v2-beta/trainings/${e}/runs`},Ud=async(e,t,i)=>B(tx(e,t),{...i,method:"GET"}),ix=(e)=>`/api/v2-beta/training-runs/${e}`,tZ=async(e,t)=>B(ix(e),{...t,method:"GET"}),nx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/training-runs/${e}/logs?${n}`:`/api/v2-beta/training-runs/${e}/logs`},iZ=async(e,t,i)=>B(nx(e,t),{...i,method:"GET"}),rx=(e)=>`/api/v2-beta/training-runs/${e}/metrics`,nZ=async(e,t)=>B(rx(e),{...t,method:"GET"}),ox=(e,t,i)=>{let n=new URLSearchParams;Object.entries(i||{}).forEach(([o,s])=>{if(s!==void 0)n.append(o,s===null?"null":s.toString())});let r=n.toString();return r.length>0?`/api/v2-beta/training-runs/${e}/metrics/${t}?${r}`:`/api/v2-beta/training-runs/${e}/metrics/${t}`},rZ=async(e,t,i,n)=>B(ox(e,t,i),{...n,method:"GET"}),sx=(e)=>`/api/v2-beta/training-runs/${e}/resume`,oZ=async(e,t)=>B(sx(e),{...t,method:"POST"}),ax=(e)=>`/api/v2-beta/training-runs/${e}/cancel`,sZ=async(e,t)=>B(ax(e),{...t,method:"POST"}),gx=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([n,r])=>{if(r!==void 0)t.append(n,r===null?"null":r.toString())});let i=t.toString();return i.length>0?`/api/v2-beta/audience/specializations?${i}`:"/api/v2-beta/audience/specializations"},Od=async(e,t)=>B(gx(e),{...t,method:"GET"}),lx=()=>"/api/v2-beta/me",aZ=async(e)=>B(lx(),{...e,method:"GET"}),dx=()=>"/api/v2-beta/delivery-orders",gZ=async(e)=>B(dx(),{...e,method:"GET"}),Ix=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([n,r])=>{if(r!==void 0)t.append(n,r===null?"null":r.toString())});let i=t.toString();return i.length>0?`/api/v2-beta/projects?${i}`:"/api/v2-beta/projects"},zd=async(e,t)=>B(Ix(e),{...t,method:"GET"}),cx=()=>"/api/v2-beta/projects",lZ=async(e,t)=>B(cx(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),ux=(e)=>`/api/v2-beta/projects/${e}`,dZ=async(e,t)=>B(ux(e),{...t,method:"GET"}),Cx=(e)=>`/api/v2-beta/projects/${e}`,IZ=async(e,t,i)=>B(Cx(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),mx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/pipelines?${n}`:`/api/v2-beta/projects/${e}/pipelines`},jd=async(e,t,i)=>B(mx(e,t),{...i,method:"GET"}),px=(e)=>`/api/v2-beta/pipelines/${e}`,cZ=async(e,t)=>B(px(e),{...t,method:"GET"}),Ax=(e)=>`/api/v2-beta/pipelines/${e}`,uZ=async(e,t,i)=>B(Ax(e),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),bx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/datasets?${n}`:`/api/v2-beta/projects/${e}/datasets`},Dd=async(e,t,i)=>B(bx(e,t),{...i,method:"GET"}),Zx=(e)=>`/api/v2-beta/projects/${e}/datasets`,CZ=async(e,t,i)=>B(Zx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),hx=(e)=>`/api/v2-beta/datasets/${e}`,mZ=async(e,t)=>B(hx(e),{...t,method:"GET"}),fx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/datasets/${e}/fields?${n}`:`/api/v2-beta/datasets/${e}/fields`},_d=async(e,t,i)=>B(fx(e,t),{...i,method:"GET"}),Wx=(e)=>`/api/v2-beta/datasets/${e}/fields`,Qd=async(e,t,i)=>B(Wx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),yx=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,pZ=async(e,t)=>B(yx(e),{...t,method:"GET"}),Vx=(e)=>`/api/v2-beta/datasets/${e}/items`,AZ=async(e,t,i)=>B(Vx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Bx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/datasets/${e}/items?${n}`:`/api/v2-beta/datasets/${e}/items`},Kd=async(e,t,i)=>B(Bx(e,t),{...i,method:"GET"}),Rx=(e)=>`/api/v2-beta/datasets/${e}/uploads`,bZ=async(e,t,i)=>B(Rx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Gx=(e)=>`/api/v2-beta/uploads/${e}/finalize`,ZZ=async(e,t)=>B(Gx(e),{...t,method:"POST"}),wx=(e)=>`/api/v2-beta/uploads/${e}/cancel`,hZ=async(e,t)=>B(wx(e),{...t,method:"POST"}),Fx=(e)=>`/api/v2-beta/uploads/${e}`,Ld=async(e,t)=>B(Fx(e),{...t,method:"GET"}),Hx=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,fZ=async(e,t,i)=>B(Hx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),vx=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,WZ=async(e,t,i)=>B(vx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),kx=(e)=>`/api/v2-beta/pipelines/${e}/export`,yZ=async(e,t)=>B(kx(e),{...t,method:"GET"}),Px=(e)=>`/api/v2-beta/pipelines/${e}/copy`,VZ=async(e,t,i)=>B(Px(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Nx=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,BZ=async(e,t,i)=>B(Nx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),xx=(e)=>`/api/v2-beta/pipelines/${e}/runs`,RZ=async(e,t)=>B(xx(e),{...t,method:"POST"}),Yx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/pipelines/${e}/runs?${n}`:`/api/v2-beta/pipelines/${e}/runs`},Md=async(e,t,i)=>B(Yx(e,t),{...i,method:"GET"}),Sx=(e)=>`/api/v2-beta/runs/${e}`,$d=async(e,t)=>B(Sx(e),{...t,method:"GET"});var Xx=(e)=>`/api/v2-beta/runs/${e}/cancel`,GZ=async(e,t)=>B(Xx(e),{...t,method:"POST"});var Ex=(e)=>`/api/v2-beta/datasets/${e}/exports`,wZ=async(e,t,i)=>B(Ex(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Tx=(e)=>`/api/v2-beta/exports/${e}`,qd=async(e,t)=>B(Tx(e),{...t,method:"GET"}),Jx=(e)=>`/api/v2-beta/pipelines/${e}/graph`,FZ=async(e,t)=>B(Jx(e),{...t,method:"GET"}),Ux=(e)=>`/api/v2-beta/pipelines/${e}/graph`,HZ=async(e,t,i)=>B(Ux(e),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Ox=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,vZ=async(e,t,i)=>B(Ox(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),zx=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,kZ=async(e,t,i,n)=>B(zx(e,t),{...n,method:"PATCH",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(i)}),jx=(e)=>`/api/v2-beta/projects/${e}/tokens`,PZ=async(e,t,i)=>B(jx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),Dx=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/projects/${e}/tokens?${n}`:`/api/v2-beta/projects/${e}/tokens`},eI=async(e,t,i)=>B(Dx(e,t),{...i,method:"GET"}),_x=(e)=>`/api/v2-beta/projects/${e}/tokens`,NZ=async(e,t)=>B(_x(e),{...t,method:"DELETE"}),Qx=(e,t)=>`/api/v2-beta/projects/${e}/tokens/${t}`,xZ=async(e,t,i)=>B(Qx(e,t),{...i,method:"DELETE"}),Kx=()=>"/api/v2-beta/tokens/current",YZ=async(e)=>B(Kx(),{...e,method:"DELETE"}),Lx=(e)=>`/api/v2-beta/projects/${e}/secrets`,SZ=async(e,t)=>B(Lx(e),{...t,method:"GET"}),Mx=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,XZ=async(e,t,i,n)=>B(Mx(e,t),{...n,method:"PUT",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(i)}),$x=(e)=>`/api/v2-beta/projects/${e}/files`,EZ=async(e,t)=>B($x(e),{...t,method:"GET"}),qx=(e)=>`/api/v2-beta/projects/${e}/files`,TZ=async(e,t,i)=>B(qx(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),eY=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,JZ=async(e,t,i)=>B(eY(e,t),{...i,method:"POST"}),tY=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,UZ=async(e,t,i)=>B(tY(e,t),{...i,method:"DELETE"}),iY=(e,t)=>{let i=new URLSearchParams;Object.entries(t||{}).forEach(([r,o])=>{if(o!==void 0)i.append(r,o===null?"null":o.toString())});let n=i.toString();return n.length>0?`/api/v2-beta/runs/${e}/items?${n}`:`/api/v2-beta/runs/${e}/items`},tI=async(e,t,i)=>B(iY(e,t),{...i,method:"GET"}),nY=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,OZ=async(e,t,i)=>B(nY(e,t),{...i,method:"GET"}),rY=(e)=>`/api/v2-beta/pipelines/${e}/checks`,zZ=async(e,t)=>B(rY(e),{...t,method:"GET"}),oY=(e)=>`/api/v2-beta/pipelines/${e}/checks`,jZ=async(e,t,i)=>B(oY(e),{...i,method:"POST",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(t)}),sY=(e)=>`/api/v2-beta/checks/${e}`,iI=async(e,t)=>B(sY(e),{...t,method:"GET"});async function*Ee(e,t={}){let i=t.offset;while(!0){let n=await e({limit:t.limit,offset:i});if(yield*n.items,!n.pagination.hasMore)return;i=n.pagination.offset+n.pagination.limit}}var Mr=async(e,t,i={})=>{let n=i.timeoutMs??60000,r=i.intervalMs??1000;R(Number.isFinite(n)&&n>=0,"The wait timeout must be a nonnegative finite number"),R(Number.isFinite(r)&&r>0,"The polling interval must be a positive finite number");let o=Date.now()+n,s=new AbortController,a=setTimeout(()=>s.abort(),n);try{while(!0){if(s.signal.aborted)throw te.waitTimeout(n);let g=await e(s.signal);if(t(g))return g;let l=o-Date.now();if(l<=0)throw te.waitTimeout(n);let{promise:d,resolve:I}=Promise.withResolvers();setTimeout(I,Math.min(r,l)),await d}}catch(g){if(s.signal.aborted)throw te.waitTimeout(n);throw g}finally{clearTimeout(a)}};var gY=(e)=>{let t=Tb(e.baseUrl,e,e.fetch);async function i(c,u){switch(c.type){case"datasetUpload":return Mr((p)=>Ld(c.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"datasetExport":return Mr((p)=>qd(c.exportId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"pipelineCheck":return Mr((p)=>iI(c.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u);case"pipelineRun":return Mr((p)=>$d(c.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",u)}}return{me:()=>aZ(t),audience:{specializations:{listPage:(c={})=>Od(c,t),listAll:(c={})=>Ee(async(u)=>{let p=await Od({...c,...u},t);return{items:p.specializations,pagination:p.pagination}},c)}},projects:{create:(c)=>lZ(c,t),get:({projectId:c})=>dZ(c,t),update:({projectId:c,...u})=>IZ(c,u,t),listPage:(c={})=>zd(c,t),listAll:(c={})=>Ee(async(u)=>{let p=await zd({...c,...u},t);return{items:p.projects,pagination:p.pagination}},c),createToken:({projectId:c,...u})=>PZ(c,u,t),listTokens:({projectId:c,...u})=>eI(c,u,t),listAllTokens:({projectId:c,...u})=>Ee(async(p)=>{let Z=await eI(c,{...u,...p},t);return{items:Z.tokens,pagination:Z.pagination}},u),revokeToken:({projectId:c,tokenId:u})=>xZ(c,u,t),revokeAllTokens:({projectId:c})=>NZ(c,t),revokeCurrentToken:()=>YZ(t)},pipelines:{import:({projectId:c,...u})=>fZ(c,u,t),get:({pipelineId:c})=>cZ(c,t),update:({pipelineId:c,...u})=>uZ(c,u,t),listPage:({projectId:c,...u})=>jd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await jd(c,{...u,...p},t);return{items:Z.pipelines,pagination:Z.pagination}},u),getGraph:({pipelineId:c})=>FZ(c,t),replaceGraph:({pipelineId:c,...u})=>HZ(c,"version"in u?{graph:u.graph,expectedVersion:u.version}:u,t),validateGraph:({pipelineId:c,...u})=>vZ(c,u,t),estimateCost:({pipelineId:c,...u})=>BZ(c,u,t),patchNode:({pipelineId:c,nodeId:u,...p})=>kZ(c,u,p,t),attachDataset:({pipelineId:c,...u})=>WZ(c,u,t),export:({pipelineId:c})=>yZ(c,t),copy:({pipelineId:c,...u})=>VZ(c,u,t)},datasets:{create:({projectId:c,...u})=>CZ(c,u,t),get:({datasetId:c})=>mZ(c,t),listPage:({projectId:c,...u})=>Dd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Dd(c,{...u,...p},t);return{items:Z.datasets,pagination:Z.pagination}},u),createField:async({datasetId:c,...u})=>{let p=await Qd(c,u,t);return R(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:c,fields:u})=>{let p=await Qd(c,{fields:u},t);return R("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:c,...u})=>_d(c,u,t),getInferredFields:({datasetId:c})=>pZ(c,t),listAllFields:({datasetId:c,...u})=>Ee(async(p)=>{let Z=await _d(c,{...u,...p},t);return{items:Z.fields,pagination:Z.pagination}},u),appendItems:({datasetId:c,...u})=>AZ(c,u,t),listItemsPage:({datasetId:c,...u})=>Kd(c,u,t),listAllItems:({datasetId:c,...u})=>Ee(async(p)=>{let Z=await Kd(c,{...u,...p},t);return{items:Z.items,pagination:Z.pagination}},u),startUpload:({datasetId:c,...u})=>bZ(c,u,t),finalizeUpload:({uploadId:c})=>ZZ(c,t),cancelUpload:({uploadId:c})=>hZ(c,t),getUpload:({uploadId:c})=>Ld(c,t),startExport:({datasetId:c,...u})=>wZ(c,u,t),getExport:({exportId:c})=>qd(c,t)},baseModels:{list:async()=>(await Jb(t)).baseModels,get:({id:c})=>Ub(c,t)},models:{listPage:({projectId:c,...u})=>Ed(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Ed(c,{...u,...p},t);return{items:Z.models,pagination:Z.pagination}},u),get:({projectId:c,modelId:u})=>_b(c,u,t),listVersionsPage:({projectId:c,modelId:u,...p})=>Td(c,u,p,t),listAllVersions:({projectId:c,modelId:u,...p})=>Ee(async(Z)=>{let h=await Td(c,u,{...p,...Z},t);return{items:h.versions,pagination:h.pagination}},p),create:({projectId:c,...u})=>Ob(c,u,t),getVersion:({modelVersionId:c})=>zb(c,t),getVersionContent:({modelVersionId:c})=>jb(c,t),archive:({projectId:c,modelId:u})=>{let p=new Headers(t.headers);return p.set("Content-Type","application/json"),Db(c,u,{...t,headers:p})}},trainings:{listPage:({projectId:c,...u})=>Jd(c,u,t),listAll:({projectId:c,...u})=>Ee(async(p)=>{let Z=await Jd(c,{...u,...p},t);return{items:Z.trainings,pagination:Z.pagination}},u),get:({trainingId:c})=>Kb(c,t),create:({projectId:c,...u})=>Qb(c,u,t),updateMetadata:({trainingId:c,...u})=>Lb(c,u,t),replaceConfiguration:({trainingId:c,...u})=>Mb(c,u,t),prepareCostEstimateInputs:({trainingId:c,idempotencyKey:u,...p})=>{let Z=new Headers(t.headers);return Z.set("Idempotency-Key",u),$b(c,p,{...t,headers:Object.fromEntries(Z.entries())})},estimateCost:({trainingId:c,...u})=>qb(c,u,t),resumeRun:({trainingRunId:c})=>oZ(c,t),cancelRun:({trainingRunId:c})=>sZ(c,t),createRun:({trainingId:c,idempotencyKey:u,...p})=>{let Z=new Headers(t.headers);return Z.set("Idempotency-Key",u),eZ(c,p,{...t,headers:Object.fromEntries(Z.entries())})},listRunsPage:({trainingId:c,...u})=>Ud(c,u,t),listAllRuns:({trainingId:c,...u})=>Ee(async(p)=>{let Z=await Ud(c,{...u,...p},t);return{items:Z.trainingRuns,pagination:Z.pagination}},u),getRun:({trainingRunId:c})=>tZ(c,t),getRunLogs:({trainingRunId:c,...u})=>iZ(c,u,t),getRunMetrics:({trainingRunId:c})=>nZ(c,t),getRunMetricHistory:({trainingRunId:c,metricKey:u,...p})=>rZ(c,u,p,t)},runs:{start:({pipelineId:c})=>RZ(c,t),get:({runId:c})=>$d(c,t),cancel:({runId:c})=>GZ(c,t),listPage:({pipelineId:c,...u})=>Md(c,u,t),listAll:({pipelineId:c,...u})=>Ee(async(p)=>{let Z=await Md(c,{...u,...p},t);return{items:Z.runs,pagination:Z.pagination}},u),listItemsPage:({runId:c,...u})=>tI(c,u,t),listAllItems:({runId:c,...u})=>Ee(async(p)=>{let Z=await tI(c,{...u,...p},t);return{items:Z.items,pagination:Z.pagination}},u),getItem:({runId:c,itemId:u})=>OZ(c,u,t)},secrets:{list:async({projectId:c})=>(await SZ(c,t)).secrets,set:({projectId:c,name:u,...p})=>XZ(c,u,p,t)},files:{list:async({projectId:c})=>(await EZ(c,t)).files,startUpload:({projectId:c,...u})=>TZ(c,u,t),finalizeUpload:({projectId:c,fileId:u})=>JZ(c,u,t),delete:({projectId:c,fileId:u})=>UZ(c,u,t)},checks:{list:async({pipelineId:c})=>(await zZ(c,t)).checks,start:({pipelineId:c,...u})=>jZ(c,u,t),get:({checkRunId:c})=>iI(c,t)},deliveryOrders:{list:async()=>(await gZ(t)).deliveryOrders},waitFor:i}};function Fn(e){return gY(e)}var Hn=require("fs/promises"),nI=require("path"),_Z=Pe(hd(),1);var Gi="toloka.json";class rI extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var lY="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",dY={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:lY},additionalProperties:{type:"object",properties:{pipelineId:{type:"string",minLength:1}},required:["pipelineId"],additionalProperties:!1}},datasets:{type:"object",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",properties:{datasetId:{type:"string",minLength:1}},required:["datasetId"],additionalProperties:!1}}},required:["projectId","pipelines","datasets"],additionalProperties:!1},IY=new _Z.default({allErrors:!0,strict:!1}),DZ=IY.compile(dY);function cY(e){let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return`${typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/"}: ${e.message??`failed ${e.keyword} validation`}`}function QZ(e){if(DZ(e))return e;let t=DZ.errors;throw R(t,"toloka.json validation failed without errors"),new rI(`Invalid toloka.json: ${t.map(cY).join("; ")}`)}async function Ae(e){let t;try{t=await Hn.readFile(nI.join(e,Gi),"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;throw i}try{return QZ(JSON.parse(t))}catch(i){if(i instanceof SyntaxError)throw new rI(`Invalid toloka.json: ${i.message}`,{cause:i});throw i}}async function ri(e,t){let i=QZ(t),n=Object.fromEntries(Object.entries(i.pipelines).sort(([o],[s])=>o<s?-1:o>s?1:0)),r=Object.fromEntries(Object.entries(i.datasets).sort(([o],[s])=>o<s?-1:o>s?1:0));await Hn.mkdir(e,{recursive:!0}),await Hn.writeFile(nI.join(e,Gi),`${JSON.stringify({projectId:i.projectId,pipelines:n,datasets:r},null,2)}
|
|
152
|
+
`,"utf8")}var rh=require("crypto"),Yt=require("fs/promises"),oh=require("os"),kn=require("path");var KZ=15000,LZ={alias:"google",name:"Google",variant:"outline",hint:"google"},MZ={alias:"ms",name:"Microsoft",variant:"outline",hint:"ms"},uY={alias:"email",name:"Email",variant:"ghost"},CY={alias:"testing-users",name:"Testing",variant:"ghost",hint:"testing-users"},$Z=(e,t,i,n)=>{let r=`https://${e}/realms/${t}`;return{authHost:e,realm:t,clientId:i,identityProviders:n,issuer:r,authorizationEndpoint:`${r}/protocol/openid-connect/auth`,tokenEndpoint:`${r}/protocol/openid-connect/token`,logoutEndpoint:`${r}/protocol/openid-connect/logout`}},qZ=$Z("auth.toloka.ai","toloka","platform-cli-production",[LZ,MZ]),eh=$Z("auth.toloka-test.ai","toloka","platform-cli-testing",[LZ,MZ,uY,CY]),th=[qZ,eh],zs=(e)=>{let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:")return;if(t.host==="platform.toloka.ai")return qZ;if(t.host.endsWith(".platform.toloka-test.ai"))return eh;return},wi=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,ih=(e)=>{try{return JSON.parse(e)}catch{return}},mY=(e)=>{let t=ih(e),i=wi(t,"access_token"),n=wi(t,"expires_in"),r=wi(t,"refresh_token"),o=wi(t,"refresh_expires_in")??0,s=wi(t,"scope")??"";if(typeof i!=="string"||i.length===0)return;if(typeof n!=="number"||!Number.isFinite(n))return;if(typeof r!=="string"||r.length===0)return;if(typeof o!=="number"||!Number.isFinite(o))return;if(typeof s!=="string")return;return{access_token:i,expires_in:n,refresh_token:r,refresh_expires_in:o,scope:s}};class vn extends Error{status;oauthError;constructor(e,t){let i=ih(t),n=wi(i,"error"),r=wi(i,"error_description"),o=typeof r==="string"&&r.length>0?typeof n==="string"?`${n}: ${r}`:r:typeof n==="string"?n:t.slice(0,200)||"empty response";super(`The login service answered ${e}: ${o}`);this.name="TokenRequestError",this.status=e,this.oauthError=typeof n==="string"?n:void 0}}var js=async(e,t,i=globalThis.fetch)=>{let n=await i(e.tokenEndpoint,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,...t}).toString(),signal:AbortSignal.timeout(KZ)}),r=await n.text();if(!n.ok)throw new vn(n.status,r);let o=mY(r);if(o===void 0)throw new F(`${e.issuer} returned a token response the CLI does not understand.`,{hint:{description:"Retry; if it keeps failing, report it with toloka report."}});return o},nh=async(e,t,i=globalThis.fetch)=>{try{return(await i(e.logoutEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,refresh_token:t}).toString(),signal:AbortSignal.timeout(KZ)})).ok}catch{return!1}};var pY=60,Nn=()=>Math.floor(Date.now()/1000),AY=(e)=>e.TOLOKA_CLI_CREDENTIALS_DIR??(e.TOLOKA_CREDENTIALS_FILE===void 0?kn.join(e.HOME??oh.homedir(),".toloka","cli","credentials"):kn.join(kn.dirname(e.TOLOKA_CREDENTIALS_FILE),"browser-sessions")),Ds=(e,t=process.env)=>kn.join(AY(t),e.authHost,e.realm,`${e.clientId}.json`),aI=(e,t,i=Nn())=>({version:1,issuer:e.issuer,client_id:e.clientId,token_endpoint:e.tokenEndpoint,access_token:t.access_token,access_token_expires_at:i+t.expires_in,refresh_token:t.refresh_token,refresh_token_expires_at:t.refresh_expires_in>0?i+t.refresh_expires_in:0,scope:t.scope,obtained_at:i}),Vt=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,oI=(e)=>typeof e==="string"&&e.length>0,sI=(e)=>typeof e==="number"&&Number.isFinite(e),bY=(e,t)=>{if(Vt(e,"version")!==1)return;let i=Vt(e,"issuer"),n=Vt(e,"client_id");if(i!==t.issuer||n!==t.clientId)return;let r=Vt(e,"token_endpoint"),o=Vt(e,"access_token"),s=Vt(e,"access_token_expires_at"),a=Vt(e,"refresh_token"),g=Vt(e,"refresh_token_expires_at"),l=Vt(e,"scope"),d=Vt(e,"obtained_at");if(!oI(r)||!oI(o))return;if(!oI(a)||typeof l!=="string")return;if(!sI(s)||!sI(g))return;if(!sI(d))return;return{version:1,issuer:i,client_id:n,token_endpoint:r,access_token:o,access_token_expires_at:s,refresh_token:a,refresh_token_expires_at:g,scope:l,obtained_at:d}};async function $r(e,t=process.env){let i;try{i=await Yt.readFile(Ds(e,t),"utf8")}catch{return}try{return bY(JSON.parse(i),e)}catch{return}}async function gI(e,t,i=process.env){let n=Ds(t,i);await Ht(n);let r=`${n}.${rh.randomUUID()}.tmp`;try{await Yt.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
153
|
+
`,{mode:384,flag:"wx"}),await Yt.rename(r,n)}catch(o){throw await Yt.rm(r,{force:!0}),o}return n}async function sh(e,t=process.env){let i=Ds(e,t);try{return await Yt.rm(i),i}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return;throw n}}async function _s(e,t=process.env){let i=zs(e);if(i===void 0)return;let n=await $r(i,t);if(n===void 0)return;return{provider:i,session:n,path:Ds(i,t)}}var ZY=(e,t)=>e.access_token_expires_at-pY>t,lI=(e,t=Nn())=>e.refresh_token_expires_at>0&&e.refresh_token_expires_at<=t;class Pn extends F{constructor(e,t){super(`Your browser login for ${e} has expired.`,{hint:{description:"Run toloka login to sign in again."},...t===void 0?{}:{cause:t}});this.name="BrowserLoginExpiredError"}}var Qs=({provider:e,baseUrl:t,environment:i=process.env,fetch:n=globalThis.fetch,now:r=Nn})=>{let o,s=async(g)=>{if(lI(g,r()))throw new Pn(t);let l;try{l=await js(e,{grant_type:"refresh_token",refresh_token:g.refresh_token},n)}catch(I){if(I instanceof vn&&I.oauthError==="invalid_grant")throw new Pn(t,I);let C=I instanceof Error?I.message:String(I);throw new F(`Could not renew your browser login for ${t}: ${C}`,{hint:{description:"Check network access and retry; run toloka login if it keeps failing."},cause:I})}let d=aI(e,l,r());return await gI(d,e,i),d},a=async()=>{let g=await $r(e,i);if(g===void 0)throw new F(`Not logged in to ${t}.`,{hint:{description:"Run toloka login."}});return(ZY(g,r())?g:await s(g)).access_token};return()=>(o??=a().finally(()=>{o=void 0}),o)};var hY="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, use a bound toloka.json, run toloka project create for a new project, or run toloka project add for an existing project.";function S(e){b(e,hY,{hint:{disabled:!0}})}var fY="No project selected. Run toloka project create for a new project, toloka project add for an existing project, or cd into a checkout.",ah="project add writes the machine registry; unset --api-key / --base-url / TOLOKA_API_KEY / TOLOKA_BASE_URL, or run login against that platform first.",WY=/^[^/\s]+$/u,Ks=(e)=>{let t=e.trim();return b(t.length>0&&WY.test(t),"Project alias must be non-empty and contain no / or whitespace.",{hint:{description:"Use letters, digits, dashes, or underscores, for example my-project."}}),t},ve=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},yY=(e,t,i)=>ve(e?.baseUrl)??ve(t?.TOLOKA_BASE_URL)??oi(t??{})??ve(i?.baseUrl),qr=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,VY=(e,t,i)=>{if(!i||t?.projects===void 0)return{};if(t.current!==void 0){let n=qr(t.projects,t.current);if(n?.id===e)return n.name===void 0?{alias:t.current}:{alias:t.current,name:n.name}}for(let n of Object.keys(t.projects).toSorted()){let r=qr(t.projects,n);if(r?.id!==e)continue;return r.name===void 0?{alias:n}:{alias:n,name:r.name}}return{}};function Fi(e={}){let t=e.flags??{},i=e.environment??{},n=e.stored,r=e.effectiveBaseUrl??yY(t,i,n),o=n!==void 0&&r!==void 0&&pt(r)===pt(n.baseUrl),a=[{id:ve(t.projectId),source:"flag"},{id:ve(i.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:ve(e.state?.projectId),source:"toloka.json"},{id:o&&n.current!==void 0?ve(n.projects?.[n.current]?.id):void 0,source:"registry"}].find((g)=>g.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...VY(a.id,n,o)}}var II=(e,t)=>{if(e===void 0)return"Project: (none). Run toloka project create or toloka project add.";let i=e.alias===void 0?"":`alias ${e.alias}, `,n=e.source!=="registry"&&t?.current!==void 0?`; registry current is ${t.current}`:"";return`Project: ${e.id} (${i}from ${e.source}${n})`},Ls=(e,t,i)=>{let n=ve(e.apiKey)??ve(t.TOLOKA_API_KEY),r=ve(e.baseUrl)??ve(t.TOLOKA_BASE_URL)??oi(t);b(n===void 0||n===i.apiKey,ah,{hint:{disabled:!0}}),b(r===void 0||pt(r)===pt(i.baseUrl),ah,{hint:{disabled:!0}})},Ms=async(e,t)=>{await Ir(e,t)},gh=(e,t,i)=>{let n=Object.assign(Object.create(null),e.projects??{},{[t]:i.name===void 0?{id:i.id}:i});return{...e,current:t,projects:n}},dI=async(e,t,i)=>{b(e?.prompt,i,{hint:{disabled:!0}});let n=(await e.prompt(t)).trim();return b(n.length>0,i,{hint:{disabled:!0}}),n};async function lh(e){let t=e.limit??20,i=await e.client.projects.listPage({limit:t}),n=i.projects.map((s)=>{let a=e.context?.id===s.id,g=a?e.context.alias??"-":"-";return`${a?"*":"-"} ${s.id} ${s.name} ${g}`}),r=n.length===0?[]:["CURRENT\tID\tNAME\tALIAS",...n];if(i.pagination.hasMore)r.push(`Showing ${i.projects.length} of ${i.pagination.total} projects. Raise --limit to see more.`);let o=r.length===0?"No projects visible.":r.join(`
|
|
154
|
+
`);return e.io.stdout(o),{output:o}}async function dh(e){let t=await Ae(e.sourceRoot);b(t,`No ${Gi} found in ${e.sourceRoot}.`,{hint:{description:"Run toloka init in the source root, or cd into the checkout that holds toloka.json."}});let i=e.type==="pipeline"?t.pipelines:t.datasets,n=i[e.name];b(n,`${e.type==="pipeline"?"Pipeline":"Dataset"} ${e.name} is not tracked.`,{hint:{description:"Open toloka.json to see the tracked pipelines and datasets."}});let r="pipelineId"in n?n.pipelineId:n.datasetId,o=`${e.type} ${e.name} (${r})`;if(!e.confirm){b(e.io.prompt,`Refusing to untrack ${o} without confirmation. Pass --confirm after reviewing ${Gi}.`,{hint:{disabled:!0}});let g=(await e.io.prompt(`Untrack ${o}? The live resource will not be deleted. [y/N] `)).trim().toLowerCase();b(g==="y"||g==="yes","Untrack canceled.",{hint:{disabled:!0}})}let s=Object.fromEntries(Object.entries(i).filter(([g])=>g!==e.name));await ri(e.sourceRoot,{...t,...e.type==="pipeline"?{pipelines:s}:{datasets:s}});let a=`Untracked ${o}. The live ${e.type} was not deleted.`;return e.io.stdout(a),{output:a}}async function Ih(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias??await dI(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),n=ve(e.projectId)??await dI(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),r=qr(t.credentials.projects,i);b(r===void 0||r.id===n,`Alias ${i} already points at ${r?.id}. Run toloka project remove ${i} first.`,{hint:{disabled:!0}}),await e.afterPreflight?.();let o=await e.client.projects.get({projectId:n});await Ms(gh(t.credentials,i,{id:o.id,name:o.name}),e.environment);let s=`Using project ${o.id} as ${i}.`;return e.io?.stdout(s),{output:s,alias:i,projectId:o.id}}async function ch(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias),n=qr(t.credentials.projects,i);b(n,`Unknown project alias ${i}.`,{hint:{description:"Run toloka project add <alias> <project-id> to register it, or check the alias spelling."}}),await Ms({...t.credentials,current:i},e.environment);let r=`Using project ${n.id} as ${i}.`;return e.io?.stdout(r),{output:r}}async function uh(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias),n=Object.assign(Object.create(null),t.credentials.projects??{});b(qr(n,i),`Unknown project alias ${i}.`,{hint:{description:"Run toloka project add <alias> <project-id> to register it, or check the alias spelling."}}),delete n[i];let r=t.credentials.current===i?void 0:t.credentials.current;await Ms({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...r===void 0?{}:{current:r},...Object.keys(n).length===0?{}:{projects:n}},e.environment);let o=`Removed local alias ${i}.`;return e.io?.stdout(o),{output:o}}function Ch(e){let t=Fi(e),i=t===void 0?fY:II(t,e.stored);return e.io?.stdout(i),t===void 0?{output:i}:{output:i,project:t}}var BY=async(e,t)=>{let i=ve(t);if(i!==void 0)return i;let{teams:n}=await e.me();b(n!==void 0,"Missing team id. Pass --team-id. This platform does not report team memberships, so the team cannot be inferred.",{hint:{description:"Copy the team id from the platform URL after /teams/, or update the platform."}});let r=n.filter((s)=>s.writable).map((s)=>s.id);b(r.length>0,"This account has no writable team, so it cannot create a project. Ask a team admin for write access or use toloka project add for an existing project.",{hint:{disabled:!0}});let[o]=r;return b(o!==void 0&&r.length===1,`Missing team id. Pass --team-id. This account can create projects in several teams: ${r.join(", ")}.`,{hint:{disabled:!0}}),o},RY="Internal teams attach a Sunday delivery order to every project: run toloka delivery-order list, then re-run toloka project create with --delivery-order-id <id>.",GY="The owning team is not internal, so re-run toloka project create without --delivery-order-id. toloka whoami marks internal teams (internal) on its Teams: line.",wY=(e,t)=>{if(!t.includes("deliveryOrderId"))return;if(e.deliveryOrderId===void 0&&t.includes("required"))return RY;if(e.deliveryOrderId!==void 0&&t.includes("only be set"))return GY;return},FY=async(e,t)=>{try{return await e.projects.create(t)}catch(i){if(i instanceof te&&i.status===400){let n=cr(i),r=n===void 0?void 0:wY(t,n);if(r!==void 0)throw new F(i.message,{cause:i,hint:{description:r}})}throw i}},HY=async(e,t,i,n)=>{if(t===void 0){try{await ri(e,{projectId:i.id,pipelines:{},datasets:{}})}catch(r){let o=r instanceof Error?r.message:String(r);throw new F([`Created project ${i.id} as ${n}.`,`Failed to write toloka.json: ${o}`].join(`
|
|
155
|
+
`),{cause:r,hint:{description:`The project exists. Make ${e} writable, then run toloka --project-id ${i.id} init to bind it.`}})}return}if(t.projectId===i.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function mh(e){let t=await Jt(e.environment);Ls(e.flags??{},e.environment,t.credentials);let i=Ks(e.alias??await dI(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));b(t.credentials.projects?.[i]===void 0,`Alias ${i} already exists. Run toloka project remove ${i} first.`,{hint:{disabled:!0}});let n=e.sourceRoot===void 0?void 0:await Ae(e.sourceRoot);await e.afterPreflight?.();let r=await BY(e.client,e.teamId),o=ve(e.deliveryOrderId),s=await FY(e.client,{teamId:r,name:ve(e.name)??i,...o===void 0?{}:{deliveryOrderId:o}});try{await Ms(gh(t.credentials,i,{id:s.id,name:s.name}),e.environment)}catch(l){let d=l instanceof Error?l.message:String(l);throw new F([`Created ${s.id} but failed to update the local registry: ${d}`,`Run: toloka project add ${i} ${s.id}`].join(`
|
|
156
|
+
`),{cause:l,hint:{disabled:!0}})}let a=[`Created project ${s.id} as ${i}.`];if(e.sourceRoot!==void 0){let l=await HY(e.sourceRoot,n,s,i);if(l!==void 0)a.push(l)}let g=a.join(`
|
|
157
|
+
`);return e.io?.stdout(g),{output:g,projectId:s.id,alias:i}}var Hi="https://platform.toloka.ai",vY=/^(?:prestable|pr-\d+)$/u,oi=(e)=>{let t=e.ENV?.trim();if(t===void 0||!vY.test(t))return;return`https://${t}.platform.toloka-test.ai`},kY="https://console.toloka.ai",PY="https://prestable.console.toloka-test.ai",ph=(e)=>new URL("/auth?redirectPath=%2Fregistration",e).href,$s=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return kY;if(t.endsWith(".platform.toloka-test.ai"))return PY;return},NY=["Not logged in. Run toloka login once to sign in through your browser on this machine:",""," toloka login","","Automation can pass --api-key, set TOLOKA_API_KEY, or pipe a key to toloka login --api-key-stdin.","Run toloka auth-status to see what is in effect."].join(`
|
|
158
|
+
`),cI=(e,t,i)=>e.apiKey??t.TOLOKA_API_KEY??i?.apiKey,xn=(e,t,i)=>e.baseUrl??t.TOLOKA_BASE_URL??oi(t)??i?.baseUrl??Hi;function Ah(e,t,i,n,r){let o=cI(e,i,n),s=xn(e,i,n),a=Fi({flags:e,state:t,environment:i,stored:n,effectiveBaseUrl:s}),g=o!==void 0?{type:"apiKey",apiKey:o}:r!==void 0?{type:"browser",provider:r}:void 0;return b(g,NY,{hint:{disabled:!0}}),{baseUrl:s,credential:g,...a===void 0?{}:{projectId:a.id}}}var bh=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. TOLOKA_API_KEY / TOLOKA_BASE_URL"," 3. the API key stored by toloka login --api-key-stdin"," 4. the browser login stored by toloka login",`The platform defaults to ${Hi}.`].join(`
|
|
159
|
+
`),Zh=(e)=>{if(e!=="human"&&e!=="agent")throw new Ze('Expected "human" or "agent".');return e},Te=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Ze("Expected a positive integer.");return t};var hh=(e)=>{if(e!=="sft"&&e!=="gisting")throw new Ze('Expected training method "sft" or "gisting".');return e},CI=(e)=>{let t=Number(e);if(t!==8&&t!==16&&t!==32)throw new Ze("Expected a LoRA rank of 8, 16, or 32.");return t},mI=(e)=>{if(e==="1/4"||e==="1/8"||e==="1/16"||e==="1/32")return e;let t=Number(e);if(t!==8&&t!==32&&t!==64)throw new Ze('Expected 8, 32, or 64 gist tokens, or a fraction of the prompt: "1/4", "1/8", "1/16", or "1/32".');return t},pI=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<1||t>5)throw new Ze("Expected epochs from 1 through 5.");return t},AI=(e)=>{let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Ze("Expected a positive learning rate, for example 0.00015.");return t},bI=(e)=>{let t=Number(e);if(t!==8&&t!==16&&t!==32&&t!==64)throw new Ze("Expected a batch size of 8, 16, 32, or 64.");return t},ZI=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<64||t>16384)throw new Ze("Expected a maximum sequence length from 64 through 16384 tokens.");return t},hI=(e)=>({method:e.method,baseModelId:e.baseModel,modelVersionId:e.modelVersion,datasetId:e.dataset,validationDatasetId:e.validationDataset,trainingFilter:e.trainFilter,validationFilter:e.validationFilter,loraRank:e.loraRank,gistTokens:e.gistTokens,epochs:e.epochs,learningRate:e.learningRate,batchSize:e.batchSize,maxSequenceLength:e.maxSequenceLength,promptFilePath:e.promptFile}),qs=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},Be=async(e,t)=>{if(e.sourceRoot!==void 0)return uI.resolve(e.sourceRoot);let i=process.cwd(),n=await fb(i);if(n===void 0||n===i)return i;return t.stderr(`Using project root ${n} (found from ${i}).`),n},ea=(e)=>e.sourceRoot===void 0?process.cwd():uI.resolve(e.sourceRoot),fI=async(e,t)=>{let{found:i,warning:n}=await en(t.environment,e.apiKey??t.environment.TOLOKA_API_KEY);if(n!==void 0)t.io.stderr(n);return i?.credentials},vi=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},ki=async(e,t,i,n)=>{let{environment:r}=t,o=cI(e,r,n)===void 0?(await _s(xn(e,r,n),r))?.provider:void 0,s=Ah(e,i,r,n,o),{baseUrl:a,credential:g}=s,l=t.injectedClient??Fn(g.type==="apiKey"?{baseUrl:a,apiKey:g.apiKey}:{baseUrl:a,accessToken:Qs({provider:g.provider,baseUrl:a,environment:r})});return{config:s,client:l}},w=async(e,t)=>{let i=await Be(e,t.io),n=await Ae(i),r=await fI(e,t),{config:o,client:s}=await ki(e,t,n,r);return await vi(s,t.analytics),{sourceRoot:i,client:s,baseUrl:o.baseUrl,state:n,stored:r,...o.projectId===void 0?{}:{projectId:o.projectId}}},ta=(e,t,i,n)=>Fi({flags:e,environment:t.environment,stored:i,...n===void 0?{}:{state:n}});var fh=(e,t)=>{let{context:i,globals:n}=t;e.command("audience").description("inspect the expert audience catalog used by node audience filters").command("specialization").description("expert specializations (platform qualifications)").command("list").option("--json","print JSON",!1).description("list specializations with their id, name, and expert count").action(async(s)=>{let{client:a}=await w(n(),i);await Eb(a,{json:s.json},i.io)})};var wh=require("child_process"),eo=require("crypto"),Fh=require("http");var Pi=(e)=>e.replace(/[&<>"']/gu,(t)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t);var xY={google:'<svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M30.0014 16.3109C30.0014 15.1598 29.9061 14.3198 29.6998 13.4487H16.2871V18.6442H24.1601C24.0014 19.9354 23.1442 21.8798 21.2394 23.1864L21.2127 23.3604L25.4536 26.58L25.7474 26.6087C28.4458 24.1665 30.0014 20.5731 30.0014 16.3109Z" fill="#4285F4"/><path d="M16.2863 29.9998C20.1434 29.9998 23.3814 28.7553 25.7466 26.6086L21.2386 23.1863C20.0323 24.0108 18.4132 24.5863 16.2863 24.5863C12.5086 24.5863 9.30225 22.1441 8.15929 18.7686L7.99176 18.7825L3.58208 22.127L3.52441 22.2841C5.87359 26.8574 10.699 29.9998 16.2863 29.9998Z" fill="#34A853"/><path d="M8.15964 18.769C7.85806 17.8979 7.68352 16.9645 7.68352 16.0001C7.68352 15.0356 7.85806 14.1023 8.14377 13.2312L8.13578 13.0456L3.67083 9.64746L3.52475 9.71556C2.55654 11.6134 2.00098 13.7445 2.00098 16.0001C2.00098 18.2556 2.55654 20.3867 3.52475 22.2845L8.15964 18.769Z" fill="#FBBC05"/><path d="M16.2864 7.4133C18.9689 7.4133 20.7784 8.54885 21.8102 9.4978L25.8419 5.64C23.3658 3.38445 20.1435 2 16.2864 2C10.699 2 5.8736 5.1422 3.52441 9.71549L8.14345 13.2311C9.30229 9.85555 12.5086 7.4133 16.2864 7.4133Z" fill="#EB4335"/></svg>',ms:'<svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="17" y="17" width="10" height="10" fill="#FEBA08"/><rect x="5" y="17" width="10" height="10" fill="#05A6F0"/><rect x="17" y="5" width="10" height="10" fill="#80BC06"/><rect x="5" y="5" width="10" height="10" fill="#F25325"/></svg>',"testing-users":'<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="#FFCC4D" d="M22.845 13.625c-.21-1.907-.428-2.875-1.012-4.042 0 0 1.75-5.25.584-7.408-.394-.727-4.32.985-5.834 2.158 0 0-2.333-.582-4.083-.582s-4.083.582-4.083.582C6.902 3.16 2.977 1.448 2.583 2.175c-1.166 2.158.584 7.408.584 7.408-.584 1.167-.803 2.135-1.012 4.042-.23 2.09.228 3.757.428 4.125.228.418 1.381 1.764 2.917 2.916 2.333 1.75 5.833 2.334 7 2.334 1.166 0 4.666-.584 7-2.334 1.536-1.152 2.689-2.498 2.916-2.916.2-.368.66-2.034.429-4.125z"/><path fill="#664500" d="M18.6 12.382c-.035-.08-.874-1.924-2.6-1.924-1.725 0-2.565 1.845-2.6 1.924a.294.294 0 00.44.353c.008-.006.737-.527 2.16-.527 1.415 0 2.143.514 2.16.526a.29.29 0 00.44-.352zm-7 0c-.035-.08-.874-1.924-2.6-1.924-1.725 0-2.565 1.845-2.6 1.924a.291.291 0 00.44.353c.008-.006.736-.527 2.16-.527 1.415 0 2.143.514 2.16.526a.29.29 0 00.44-.352zm3.617 3.406a.299.299 0 01.348-.035.29.29 0 01.135.318c-.007.025-.668 2.554-3.2 2.554s-3.193-2.529-3.199-2.554a.292.292 0 01.489-.278s.586.499 2.71.499c2.126 0 2.71-.499 2.717-.504z"/></svg>',email:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>'},Wh=(e,t)=>`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${Pi(e)}</title><style>
|
|
160
160
|
:root {
|
|
161
161
|
color-scheme: light dark;
|
|
162
162
|
--background: oklch(0.967 0.001 286.375 / 60%);
|
|
@@ -258,28 +258,28 @@ body {
|
|
|
258
258
|
}
|
|
259
259
|
.footer a { color: var(--primary); font-weight: 500; text-decoration: underline; text-underline-offset: 4px; }
|
|
260
260
|
.footer div + div { margin-top: 0.5rem; }
|
|
261
|
-
</style></head><body><main class="stage"><svg class="logo" viewBox="0 0 99 32" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Toloka"><path d="M54.7053 8H42.8716V9.94458H47.6776V23.7003H49.9094V9.94458H54.7053V8Z" fill="currentColor"/><path d="M61.1436 13.8363C60.7103 13.335 60.1687 12.9471 59.5264 12.6725C58.8816 12.398 58.136 12.2619 57.2897 12.2619C56.4433 12.2619 55.7078 12.398 55.068 12.6725C54.4282 12.9471 53.8891 13.335 53.4559 13.8363C53.0226 14.3375 52.6927 14.937 52.4735 15.6347C52.2519 16.3325 52.1436 17.1159 52.1436 17.9849V18.272C52.1436 19.1335 52.2544 19.9169 52.4735 20.6222C52.6952 21.3274 53.0226 21.9295 53.4559 22.4282C53.8891 22.9269 54.4282 23.3123 55.068 23.5869C55.7078 23.8614 56.4483 23.9975 57.2897 23.9975C58.131 23.9975 58.8816 23.8614 59.5264 23.5869C60.1713 23.3123 60.7103 22.9269 61.1436 22.4282C61.5768 21.9295 61.9043 21.3274 62.1259 20.6222C62.3476 19.9169 62.4559 19.1335 62.4559 18.272V17.9849C62.4559 17.1159 62.3451 16.3325 62.1259 15.6347C61.9043 14.937 61.5768 14.3375 61.1436 13.8363ZM60.1813 18.3174C60.1813 18.9219 60.1259 19.466 60.0151 19.9471C59.9043 20.4282 59.733 20.8388 59.4962 21.1813C59.2619 21.5239 58.9597 21.7859 58.5944 21.9672C58.2267 22.1486 57.7909 22.2393 57.2871 22.2393C56.7834 22.2393 56.3551 22.1486 55.9899 21.9672C55.6221 21.7859 55.3224 21.5239 55.0881 21.1813C54.8539 20.8388 54.6801 20.4282 54.5692 19.9471C54.4584 19.466 54.403 18.9244 54.403 18.3174V17.932C54.403 17.335 54.4584 16.7934 54.5692 16.3148C54.6801 15.8337 54.8514 15.4257 55.0881 15.0856C55.3224 14.7481 55.6247 14.4861 55.9899 14.2997C56.3577 14.1159 56.7884 14.0227 57.2871 14.0227C57.7859 14.0227 58.2292 14.1159 58.5944 14.2997C58.9622 14.4861 59.2619 14.7456 59.4962 15.0856C59.7305 15.4232 59.9043 15.8337 60.0151 16.3148C60.1259 16.796 60.1813 17.335 60.1813 17.932V18.3174Z" fill="currentColor"/><path d="M66.3302 8H64.1841V23.7003H66.3302V8Z" fill="currentColor"/><path d="M77.0728 13.8363C76.6395 13.335 76.0979 12.9471 75.4556 12.6725C74.8108 12.398 74.0652 12.2619 73.2188 12.2619C72.3725 12.2619 71.637 12.398 70.9972 12.6725C70.3574 12.9471 69.8183 13.335 69.3851 13.8363C68.9518 14.3375 68.6219 14.937 68.4027 15.6347C68.1811 16.3325 68.0728 17.1159 68.0728 17.9849V18.272C68.0728 19.1335 68.1836 19.9169 68.4027 20.6222C68.6244 21.3274 68.9518 21.9295 69.3851 22.4282C69.8183 22.9269 70.3574 23.3123 70.9972 23.5869C71.637 23.8614 72.3775 23.9975 73.2188 23.9975C74.0602 23.9975 74.8108 23.8614 75.4556 23.5869C76.1005 23.3123 76.6395 22.9269 77.0728 22.4282C77.506 21.9295 77.8335 21.3274 78.0551 20.6222C78.2768 19.9169 78.3851 19.1335 78.3851 18.272V17.9849C78.3851 17.1159 78.2743 16.3325 78.0551 15.6347C77.8335 14.937 77.506 14.3375 77.0728 13.8363ZM76.1131 18.3174C76.1131 18.9219 76.0576 19.466 75.9468 19.9471C75.836 20.4282 75.6647 20.8388 75.4279 21.1813C75.1937 21.5239 74.8914 21.7859 74.5262 21.9672C74.1584 22.1486 73.7226 22.2393 73.2188 22.2393C72.7151 22.2393 72.2869 22.1486 71.9216 21.9672C71.5539 21.7859 71.2541 21.5239 71.0199 21.1813C70.7856 20.8388 70.6118 20.4282 70.501 19.9471C70.3901 19.466 70.3347 18.9244 70.3347 18.3174V17.932C70.3347 17.335 70.3901 16.7934 70.501 16.3148C70.6118 15.8337 70.7831 15.4257 71.0199 15.0856C71.2541 14.7481 71.5564 14.4861 71.9216 14.2997C72.2894 14.1159 72.7201 14.0227 73.2188 14.0227C73.7176 14.0227 74.1609 14.1159 74.5262 14.2997C74.8939 14.4861 75.1937 14.7456 75.4279 15.0856C75.6622 15.4232 75.836 15.8337 75.9468 16.3148C76.0576 16.796 76.1131 17.335 76.1131 17.932V18.3174Z" fill="currentColor"/><path d="M80.043 8V23.7003H82.1689V18.7305L86.4838 23.7003H89.2722L84.0379 17.7733L89.0052 12.5718H86.3881L82.1689 17.2141V8H80.043Z" fill="currentColor"/><path d="M29.267 8H-0.188965V9.94458H13.4307V23.7003H15.6649V9.94458H29.267V8Z" fill="currentColor"/><path d="M98.8563 22.9471C98.816 22.6952 98.7858 22.4282 98.7657 22.1461C98.7455 21.864 98.7329 21.5617 98.7279 21.2393C98.7254 20.9143 98.7228 20.5567 98.7228 20.1662L98.743 16.7481C98.743 16.2065 98.7002 15.7204 98.6145 15.2897C98.5289 14.8589 98.4029 14.476 98.2342 14.141C98.0679 13.806 97.8589 13.5189 97.6095 13.2821C97.3601 13.0428 97.073 12.8488 96.7505 12.6952C96.4256 12.5415 96.0654 12.4282 95.6674 12.3526C95.2694 12.2771 94.8387 12.2393 94.3752 12.2393C93.7128 12.2393 93.1158 12.3274 92.5818 12.5012C92.0478 12.675 91.5893 12.9219 91.2039 13.2443C90.8186 13.5642 90.5138 13.9572 90.2845 14.4181C90.0578 14.8816 89.9243 15.4005 89.8891 15.9773H92.0679C92.083 15.6347 92.1385 15.335 92.2392 15.0755C92.34 14.8161 92.4835 14.5995 92.6725 14.4282C92.8614 14.2569 93.0931 14.1284 93.3727 14.0378C93.6498 13.9496 93.9747 13.9043 94.345 13.9043C94.6926 13.9043 95.0075 13.9546 95.2845 14.0529C95.5616 14.1536 95.7984 14.3048 95.9898 14.5113C96.1813 14.7179 96.3299 14.9823 96.4332 15.3073C96.5364 15.6322 96.5868 16.0151 96.5868 16.4559V16.8211C95.549 16.8791 94.5994 16.9773 93.7405 17.1209C92.8689 17.267 92.1259 17.4836 91.5062 17.7758C90.8891 18.0655 90.408 18.4458 90.0553 18.9169C89.7027 19.3879 89.5264 19.9748 89.5264 20.6801V20.7431C89.5264 21.2619 89.6246 21.7229 89.8211 22.1259C90.0175 22.5289 90.2871 22.869 90.6271 23.1461C90.9697 23.4232 91.3727 23.6347 91.8362 23.7758C92.2997 23.9194 92.7808 23.9949 93.2971 23.9949C93.7102 23.9949 94.0931 23.9597 94.4483 23.8917C94.8034 23.8237 95.1259 23.7229 95.4181 23.5944C95.7102 23.466 95.9747 23.3073 96.209 23.1184C96.4432 22.9295 96.6448 22.7153 96.8186 22.4307C96.816 22.932 96.8538 23.3123 96.9521 23.6952H99.0024C98.9445 23.4458 98.8966 23.1939 98.8589 22.942L98.8563 22.9471ZM96.6397 19.2519C96.6397 19.5995 96.6044 19.9143 96.5364 20.1939C96.4684 20.4735 96.3702 20.7229 96.2442 20.942C96.1183 21.1612 95.9621 21.3526 95.7833 21.5164C95.6019 21.6801 95.4029 21.8161 95.1863 21.9219C94.9697 22.0277 94.7329 22.1058 94.481 22.1587C94.2266 22.209 93.9621 22.2368 93.6876 22.2368C93.3626 22.2368 93.0679 22.2015 92.806 22.1284C92.544 22.0579 92.3223 21.9496 92.1385 21.8111C91.9546 21.67 91.811 21.4962 91.7102 21.2871C91.6095 21.0781 91.5591 20.8388 91.5591 20.5642V20.5038C91.5591 20.1284 91.6674 19.8111 91.884 19.5541C92.1007 19.2972 92.4256 19.0907 92.8563 18.9345C93.2871 18.7783 93.8236 18.6574 94.4659 18.5768C95.0931 18.4962 95.8211 18.4357 96.6448 18.3954V19.2544L96.6397 19.2519Z" fill="currentColor"/></svg><section class="card" role="region" aria-labelledby="title">${t}</section></main></body></html>`,xY=(e,t)=>`<a class="button ${e.variant}" href="${Pi(t)}">${NY[e.alias]??""}Continue with ${Pi(e.name)}</a>`,WI=(e,t)=>`<a href="${Pi(e)}" target="_blank" rel="noopener noreferrer">${Pi(t)}</a>`,yh=(e,t,i)=>{let n=e.map((o)=>xY(o,t(o.hint))).join(""),r=i===void 0?"":`<div>New to Toloka? ${WI(i,"Create an account")}. By signing up, you agree to our ${WI("https://toloka.ai/legal/self-service-agreement","User Agreement")}.</div>`;return Wh("Sign in to Toloka",`<header class="header"><h1 class="title" id="title"><span>Welcome</span><span>to Toloka Platform</span></h1><p class="lead"><span>Choose how to sign in.</span><span>The Toloka CLI is waiting in your terminal.</span></p></header><div class="content">${n}</div><footer class="footer">${r}<div>You can close this tab once you are signed in.</div><div>Want to use an API key instead? Run <code>toloka login</code> and choose API key. ${WI("https://platform.toloka.ai/docs/integration/cli/","Help")}</div></footer>`)},Ni=(e,t)=>Wh(e,`<header class="header"><h1 class="title" id="title">${Pi(e)}</h1><p class="lead">${Pi(t)}</p></header><footer class="footer"><div>Toloka CLI</div></footer>`);var Vh=String.fromCharCode(27),ia=(e,t)=>(i)=>`${Vh}[${e}m${i}${Vh}[${t}m`,na=(e)=>e,Bh={bold:ia(1,22),dim:ia(2,22),green:ia(32,39),cyan:ia(36,39)},xi={bold:na,dim:na,green:na,cyan:na},Rh=(e,t)=>{if(e.FORCE_COLOR!==void 0)return e.FORCE_COLOR==="0"?xi:Bh;if(!t||e.NO_COLOR!==void 0||e.TERM==="dumb")return xi;return Bh};var YY=300000,SY=2000,Gh="/callback",XY=()=>{let e=eo.randomBytes(32).toString("base64url"),t=eo.createHash("sha256").update(e).digest("base64url");return{verifier:e,challenge:t}},EY=(e)=>{let t=new URL(e.provider.authorizationEndpoint);if(t.searchParams.set("client_id",e.provider.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("response_type","code"),t.searchParams.set("scope","openid"),t.searchParams.set("state",e.state),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),e.identityProviderHint!==void 0)t.searchParams.set("kc_idp_hint",e.identityProviderHint);return t.toString()},TY=(e,t)=>{let i=e.BROWSER?.trim();if(i!==void 0&&i.length>0)return[i];if(t==="darwin")return["open"];if(t==="win32")return["rundll32","url.dll,FileProtocolHandler"];return["xdg-open"]},JY=(e,t)=>new Promise((i)=>{let[n,...r]=TY(t,process.platform),o=wh.spawn(n,[...r,e],{detached:!0,stdio:"ignore"}),s=(g)=>{clearTimeout(a),o.unref(),i(g)},a=setTimeout(()=>s(!0),SY);o.once("error",()=>s(!1)),o.once("exit",(g)=>s(g===0))}),ra={description:"Run toloka login again and finish the sign-in in the tab it opens."},UY=async(e,t,i)=>{let{promise:n,resolve:r,reject:o}=Promise.withResolvers(),s="",a="",g=Fh.createServer((A,c)=>{let u=new URL(A.url??"/","http://127.0.0.1"),p=(W,y)=>{c.writeHead(W,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}),c.end(y)};if(A.headers.host!==s){p(400,Ni("Unexpected address","This page is only served on the loopback address the Toloka CLI opened."));return}if(u.pathname==="/"&&i!==void 0){p(200,i(a));return}if(u.pathname!==Gh){p(404,Ni("Not found","This address only serves the Toloka CLI sign-in."));return}if(u.searchParams.get("state")!==e){p(400,Ni("Sign-in mismatch","This response belongs to another sign-in attempt."));return}let Z=u.searchParams.get("error");if(Z!==null){let W=u.searchParams.get("error_description")??Z;p(400,Ni("Sign-in failed",W)),o(new F(`The browser sign-in was not completed: ${W}`,{hint:ra}));return}let h=u.searchParams.get("code");if(h===null||h.length===0){p(400,Ni("Sign-in failed","The response carried no authorization code.")),o(new F("The browser returned no authorization code.",{hint:ra}));return}p(200,Ni("You are signed in","You can close this tab and return to the terminal.")),r(h)});await new Promise((A,c)=>{g.once("error",c),g.listen(0,"127.0.0.1",()=>A())});let{port:l}=g.address();s=`127.0.0.1:${l}`;let d=`http://${s}`;a=`${d}${Gh}`;let I=Math.max(1,Math.round(t/60000)),C=setTimeout(()=>{o(new F(`Timed out after ${I} minute${I===1?"":"s"} waiting for the browser sign-in.`,{hint:ra}))},t),m=()=>{clearTimeout(C),g.close(),g.closeIdleConnections()};return n.then(m,m),{origin:d,redirectUri:a,authorizationCode:n,close:m}},OY=async(e,t,i)=>{let n=i.launchBrowser??((s)=>JY(s,i.environment??process.env)),r=e.openBrowser&&await n(t);b(r||e.requireBrowser!==!0,"No browser could be opened and there is no terminal to fall back to.",{hint:{description:"Run toloka login where a browser is available, pass --no-browser to get a link you can open elsewhere, or pipe an API key to toloka login --api-key-stdin."}});let o=e.style??xi;e.write(r?o.dim("Waiting for the sign-in to finish in your browser... If no browser opened, run toloka login --no-browser to get a link."):`Open this link in your browser to sign in:
|
|
261
|
+
</style></head><body><main class="stage"><svg class="logo" viewBox="0 0 99 32" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Toloka"><path d="M54.7053 8H42.8716V9.94458H47.6776V23.7003H49.9094V9.94458H54.7053V8Z" fill="currentColor"/><path d="M61.1436 13.8363C60.7103 13.335 60.1687 12.9471 59.5264 12.6725C58.8816 12.398 58.136 12.2619 57.2897 12.2619C56.4433 12.2619 55.7078 12.398 55.068 12.6725C54.4282 12.9471 53.8891 13.335 53.4559 13.8363C53.0226 14.3375 52.6927 14.937 52.4735 15.6347C52.2519 16.3325 52.1436 17.1159 52.1436 17.9849V18.272C52.1436 19.1335 52.2544 19.9169 52.4735 20.6222C52.6952 21.3274 53.0226 21.9295 53.4559 22.4282C53.8891 22.9269 54.4282 23.3123 55.068 23.5869C55.7078 23.8614 56.4483 23.9975 57.2897 23.9975C58.131 23.9975 58.8816 23.8614 59.5264 23.5869C60.1713 23.3123 60.7103 22.9269 61.1436 22.4282C61.5768 21.9295 61.9043 21.3274 62.1259 20.6222C62.3476 19.9169 62.4559 19.1335 62.4559 18.272V17.9849C62.4559 17.1159 62.3451 16.3325 62.1259 15.6347C61.9043 14.937 61.5768 14.3375 61.1436 13.8363ZM60.1813 18.3174C60.1813 18.9219 60.1259 19.466 60.0151 19.9471C59.9043 20.4282 59.733 20.8388 59.4962 21.1813C59.2619 21.5239 58.9597 21.7859 58.5944 21.9672C58.2267 22.1486 57.7909 22.2393 57.2871 22.2393C56.7834 22.2393 56.3551 22.1486 55.9899 21.9672C55.6221 21.7859 55.3224 21.5239 55.0881 21.1813C54.8539 20.8388 54.6801 20.4282 54.5692 19.9471C54.4584 19.466 54.403 18.9244 54.403 18.3174V17.932C54.403 17.335 54.4584 16.7934 54.5692 16.3148C54.6801 15.8337 54.8514 15.4257 55.0881 15.0856C55.3224 14.7481 55.6247 14.4861 55.9899 14.2997C56.3577 14.1159 56.7884 14.0227 57.2871 14.0227C57.7859 14.0227 58.2292 14.1159 58.5944 14.2997C58.9622 14.4861 59.2619 14.7456 59.4962 15.0856C59.7305 15.4232 59.9043 15.8337 60.0151 16.3148C60.1259 16.796 60.1813 17.335 60.1813 17.932V18.3174Z" fill="currentColor"/><path d="M66.3302 8H64.1841V23.7003H66.3302V8Z" fill="currentColor"/><path d="M77.0728 13.8363C76.6395 13.335 76.0979 12.9471 75.4556 12.6725C74.8108 12.398 74.0652 12.2619 73.2188 12.2619C72.3725 12.2619 71.637 12.398 70.9972 12.6725C70.3574 12.9471 69.8183 13.335 69.3851 13.8363C68.9518 14.3375 68.6219 14.937 68.4027 15.6347C68.1811 16.3325 68.0728 17.1159 68.0728 17.9849V18.272C68.0728 19.1335 68.1836 19.9169 68.4027 20.6222C68.6244 21.3274 68.9518 21.9295 69.3851 22.4282C69.8183 22.9269 70.3574 23.3123 70.9972 23.5869C71.637 23.8614 72.3775 23.9975 73.2188 23.9975C74.0602 23.9975 74.8108 23.8614 75.4556 23.5869C76.1005 23.3123 76.6395 22.9269 77.0728 22.4282C77.506 21.9295 77.8335 21.3274 78.0551 20.6222C78.2768 19.9169 78.3851 19.1335 78.3851 18.272V17.9849C78.3851 17.1159 78.2743 16.3325 78.0551 15.6347C77.8335 14.937 77.506 14.3375 77.0728 13.8363ZM76.1131 18.3174C76.1131 18.9219 76.0576 19.466 75.9468 19.9471C75.836 20.4282 75.6647 20.8388 75.4279 21.1813C75.1937 21.5239 74.8914 21.7859 74.5262 21.9672C74.1584 22.1486 73.7226 22.2393 73.2188 22.2393C72.7151 22.2393 72.2869 22.1486 71.9216 21.9672C71.5539 21.7859 71.2541 21.5239 71.0199 21.1813C70.7856 20.8388 70.6118 20.4282 70.501 19.9471C70.3901 19.466 70.3347 18.9244 70.3347 18.3174V17.932C70.3347 17.335 70.3901 16.7934 70.501 16.3148C70.6118 15.8337 70.7831 15.4257 71.0199 15.0856C71.2541 14.7481 71.5564 14.4861 71.9216 14.2997C72.2894 14.1159 72.7201 14.0227 73.2188 14.0227C73.7176 14.0227 74.1609 14.1159 74.5262 14.2997C74.8939 14.4861 75.1937 14.7456 75.4279 15.0856C75.6622 15.4232 75.836 15.8337 75.9468 16.3148C76.0576 16.796 76.1131 17.335 76.1131 17.932V18.3174Z" fill="currentColor"/><path d="M80.043 8V23.7003H82.1689V18.7305L86.4838 23.7003H89.2722L84.0379 17.7733L89.0052 12.5718H86.3881L82.1689 17.2141V8H80.043Z" fill="currentColor"/><path d="M29.267 8H-0.188965V9.94458H13.4307V23.7003H15.6649V9.94458H29.267V8Z" fill="currentColor"/><path d="M98.8563 22.9471C98.816 22.6952 98.7858 22.4282 98.7657 22.1461C98.7455 21.864 98.7329 21.5617 98.7279 21.2393C98.7254 20.9143 98.7228 20.5567 98.7228 20.1662L98.743 16.7481C98.743 16.2065 98.7002 15.7204 98.6145 15.2897C98.5289 14.8589 98.4029 14.476 98.2342 14.141C98.0679 13.806 97.8589 13.5189 97.6095 13.2821C97.3601 13.0428 97.073 12.8488 96.7505 12.6952C96.4256 12.5415 96.0654 12.4282 95.6674 12.3526C95.2694 12.2771 94.8387 12.2393 94.3752 12.2393C93.7128 12.2393 93.1158 12.3274 92.5818 12.5012C92.0478 12.675 91.5893 12.9219 91.2039 13.2443C90.8186 13.5642 90.5138 13.9572 90.2845 14.4181C90.0578 14.8816 89.9243 15.4005 89.8891 15.9773H92.0679C92.083 15.6347 92.1385 15.335 92.2392 15.0755C92.34 14.8161 92.4835 14.5995 92.6725 14.4282C92.8614 14.2569 93.0931 14.1284 93.3727 14.0378C93.6498 13.9496 93.9747 13.9043 94.345 13.9043C94.6926 13.9043 95.0075 13.9546 95.2845 14.0529C95.5616 14.1536 95.7984 14.3048 95.9898 14.5113C96.1813 14.7179 96.3299 14.9823 96.4332 15.3073C96.5364 15.6322 96.5868 16.0151 96.5868 16.4559V16.8211C95.549 16.8791 94.5994 16.9773 93.7405 17.1209C92.8689 17.267 92.1259 17.4836 91.5062 17.7758C90.8891 18.0655 90.408 18.4458 90.0553 18.9169C89.7027 19.3879 89.5264 19.9748 89.5264 20.6801V20.7431C89.5264 21.2619 89.6246 21.7229 89.8211 22.1259C90.0175 22.5289 90.2871 22.869 90.6271 23.1461C90.9697 23.4232 91.3727 23.6347 91.8362 23.7758C92.2997 23.9194 92.7808 23.9949 93.2971 23.9949C93.7102 23.9949 94.0931 23.9597 94.4483 23.8917C94.8034 23.8237 95.1259 23.7229 95.4181 23.5944C95.7102 23.466 95.9747 23.3073 96.209 23.1184C96.4432 22.9295 96.6448 22.7153 96.8186 22.4307C96.816 22.932 96.8538 23.3123 96.9521 23.6952H99.0024C98.9445 23.4458 98.8966 23.1939 98.8589 22.942L98.8563 22.9471ZM96.6397 19.2519C96.6397 19.5995 96.6044 19.9143 96.5364 20.1939C96.4684 20.4735 96.3702 20.7229 96.2442 20.942C96.1183 21.1612 95.9621 21.3526 95.7833 21.5164C95.6019 21.6801 95.4029 21.8161 95.1863 21.9219C94.9697 22.0277 94.7329 22.1058 94.481 22.1587C94.2266 22.209 93.9621 22.2368 93.6876 22.2368C93.3626 22.2368 93.0679 22.2015 92.806 22.1284C92.544 22.0579 92.3223 21.9496 92.1385 21.8111C91.9546 21.67 91.811 21.4962 91.7102 21.2871C91.6095 21.0781 91.5591 20.8388 91.5591 20.5642V20.5038C91.5591 20.1284 91.6674 19.8111 91.884 19.5541C92.1007 19.2972 92.4256 19.0907 92.8563 18.9345C93.2871 18.7783 93.8236 18.6574 94.4659 18.5768C95.0931 18.4962 95.8211 18.4357 96.6448 18.3954V19.2544L96.6397 19.2519Z" fill="currentColor"/></svg><section class="card" role="region" aria-labelledby="title">${t}</section></main></body></html>`,YY=(e,t)=>`<a class="button ${e.variant}" href="${Pi(t)}">${xY[e.alias]??""}Continue with ${Pi(e.name)}</a>`,WI=(e,t)=>`<a href="${Pi(e)}" target="_blank" rel="noopener noreferrer">${Pi(t)}</a>`,yh=(e,t,i)=>{let n=e.map((o)=>YY(o,t(o.hint))).join(""),r=i===void 0?"":`<div>New to Toloka? ${WI(i,"Create an account")}. By signing up, you agree to our ${WI("https://toloka.ai/legal/self-service-agreement","User Agreement")}.</div>`;return Wh("Sign in to Toloka",`<header class="header"><h1 class="title" id="title"><span>Welcome</span><span>to Toloka Platform</span></h1><p class="lead"><span>Choose how to sign in.</span><span>The Toloka CLI is waiting in your terminal.</span></p></header><div class="content">${n}</div><footer class="footer">${r}<div>You can close this tab once you are signed in.</div><div>Want to use an API key instead? Run <code>toloka login</code> and choose API key. ${WI("https://platform.toloka.ai/docs/integration/cli/","Help")}</div></footer>`)},Ni=(e,t)=>Wh(e,`<header class="header"><h1 class="title" id="title">${Pi(e)}</h1><p class="lead">${Pi(t)}</p></header><footer class="footer"><div>Toloka CLI</div></footer>`);var Vh=String.fromCharCode(27),ia=(e,t)=>(i)=>`${Vh}[${e}m${i}${Vh}[${t}m`,na=(e)=>e,Bh={bold:ia(1,22),dim:ia(2,22),green:ia(32,39),cyan:ia(36,39)},xi={bold:na,dim:na,green:na,cyan:na},Rh=(e,t)=>{if(e.FORCE_COLOR!==void 0)return e.FORCE_COLOR==="0"?xi:Bh;if(!t||e.NO_COLOR!==void 0||e.TERM==="dumb")return xi;return Bh};var SY=300000,XY=2000,Gh="/callback",EY=()=>{let e=eo.randomBytes(32).toString("base64url"),t=eo.createHash("sha256").update(e).digest("base64url");return{verifier:e,challenge:t}},TY=(e)=>{let t=new URL(e.provider.authorizationEndpoint);if(t.searchParams.set("client_id",e.provider.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("response_type","code"),t.searchParams.set("scope","openid"),t.searchParams.set("state",e.state),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),e.identityProviderHint!==void 0)t.searchParams.set("kc_idp_hint",e.identityProviderHint);return t.toString()},JY=(e,t)=>{let i=e.BROWSER?.trim();if(i!==void 0&&i.length>0)return[i];if(t==="darwin")return["open"];if(t==="win32")return["rundll32","url.dll,FileProtocolHandler"];return["xdg-open"]},UY=(e,t)=>new Promise((i)=>{let[n,...r]=JY(t,process.platform),o=wh.spawn(n,[...r,e],{detached:!0,stdio:"ignore"}),s=(g)=>{clearTimeout(a),o.unref(),i(g)},a=setTimeout(()=>s(!0),XY);o.once("error",()=>s(!1)),o.once("exit",(g)=>s(g===0))}),ra={description:"Run toloka login again and finish the sign-in in the tab it opens."},OY=async(e,t,i)=>{let{promise:n,resolve:r,reject:o}=Promise.withResolvers(),s="",a="",g=Fh.createServer((A,c)=>{let u=new URL(A.url??"/","http://127.0.0.1"),p=(W,y)=>{c.writeHead(W,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}),c.end(y)};if(A.headers.host!==s){p(400,Ni("Unexpected address","This page is only served on the loopback address the Toloka CLI opened."));return}if(u.pathname==="/"&&i!==void 0){p(200,i(a));return}if(u.pathname!==Gh){p(404,Ni("Not found","This address only serves the Toloka CLI sign-in."));return}if(u.searchParams.get("state")!==e){p(400,Ni("Sign-in mismatch","This response belongs to another sign-in attempt."));return}let Z=u.searchParams.get("error");if(Z!==null){let W=u.searchParams.get("error_description")??Z;p(400,Ni("Sign-in failed",W)),o(new F(`The browser sign-in was not completed: ${W}`,{hint:ra}));return}let h=u.searchParams.get("code");if(h===null||h.length===0){p(400,Ni("Sign-in failed","The response carried no authorization code.")),o(new F("The browser returned no authorization code.",{hint:ra}));return}p(200,Ni("You are signed in","You can close this tab and return to the terminal.")),r(h)});await new Promise((A,c)=>{g.once("error",c),g.listen(0,"127.0.0.1",()=>A())});let{port:l}=g.address();s=`127.0.0.1:${l}`;let d=`http://${s}`;a=`${d}${Gh}`;let I=Math.max(1,Math.round(t/60000)),C=setTimeout(()=>{o(new F(`Timed out after ${I} minute${I===1?"":"s"} waiting for the browser sign-in.`,{hint:ra}))},t),m=()=>{clearTimeout(C),g.close(),g.closeIdleConnections()};return n.then(m,m),{origin:d,redirectUri:a,authorizationCode:n,close:m}},zY=async(e,t,i)=>{let n=i.launchBrowser??((s)=>UY(s,i.environment??process.env)),r=e.openBrowser&&await n(t);b(r||e.requireBrowser!==!0,"No browser could be opened and there is no terminal to fall back to.",{hint:{description:"Run toloka login where a browser is available, pass --no-browser to get a link you can open elsewhere, or pipe an API key to toloka login --api-key-stdin."}});let o=e.style??xi;e.write(r?o.dim("Waiting for the sign-in to finish in your browser... If no browser opened, run toloka login --no-browser to get a link."):`Open this link in your browser to sign in:
|
|
262
262
|
|
|
263
263
|
${o.cyan(t)}
|
|
264
264
|
|
|
265
|
-
${o.dim("Waiting for the sign-in to finish...")}`)},Hh=async(e,t={})=>{let i=
|
|
265
|
+
${o.dim("Waiting for the sign-in to finish...")}`)},Hh=async(e,t={})=>{let i=EY(),n=eo.randomBytes(16).toString("base64url"),r=(s,a)=>TY({provider:e.provider,redirectUri:s,state:n,codeChallenge:i.challenge,...a===void 0?{}:{identityProviderHint:a}}),o=await OY(n,t.timeoutMs??SY,(s)=>yh(e.provider.identityProviders,(a)=>r(s,a),e.registrationUrl));try{await zY(e,`${o.origin}/`,t);let s=await o.authorizationCode;return await js(e.provider,{grant_type:"authorization_code",code:s,redirect_uri:o.redirectUri,code_verifier:i.verifier},t.fetch)}catch(s){if(s instanceof vn)throw new F(`The login service rejected the browser sign-in: ${s.message}`,{hint:ra,cause:s});throw s}finally{o.close()}};var kh=(e)=>{let t=e instanceof Error?e.message:String(e);if(e instanceof Pn)return{kind:"rejected",reason:t};if(!(e instanceof te)||e.status===void 0)return{kind:"unreachable",reason:t};return{kind:e.status===401||e.status===403?"rejected":"platform",reason:t}},jY={rejected:"Rejected",unreachable:"Not reachable",platform:"Platform error"},DY={rejected:()=>"Check that the key was copied whole and has not been revoked.",unreachable:(e)=>`${e} did not answer, so the key was not evaluated. Check network access, VPN, or proxy settings and retry.`,platform:()=>"The platform failed before confirming the key. Retry later."},_Y={rejected:(e)=>`${e} did not accept the account you signed in with. Check that it belongs to a Toloka team, or sign in with another account.`,unreachable:(e)=>`${e} did not answer, so the login was not evaluated. Check network access, VPN, or proxy settings and retry.`,platform:()=>"The platform failed before confirming the login. Retry later."},Ph={rejected:()=>"Run toloka login to sign in again.",unreachable:(e)=>`Check network access to ${e}; the stored login was not evaluated.`,platform:()=>"The platform failed before confirming the login. Retry later."},QY=(e)=>{let t=$s(e);return[...t===void 0?[`An API key identifies you to ${e}. Generate one in the console that`,"serves this platform, under Company -> API Keys -> Generate API Key."]:[`An API key identifies you to ${e}. To generate one:`,"",` 1. open ${t}`," 2. go to Company -> API Keys"," 3. press Generate API Key and copy it"],"","The key is shown once. Treat it like a password: it is stored with owner-only","permissions and never printed back to you."].join(`
|
|
266
266
|
`)},Nh=async(e,t,i)=>{try{return(await e.projects.listPage({limit:1})).pagination.total}catch(n){let r=kh(n);throw new F([`Could not authenticate against ${t}: ${r.reason}`,"",`Nothing was saved. ${i[r.kind](t)}`].join(`
|
|
267
|
-
`),{cause:n,hint:{disabled:!0}})}},xh=async(e,t)=>{let i=await dr(_e(e));if(typeof i!=="object")return{};if(pt(i.credentials.baseUrl)!==pt(t))return{};return{...i.credentials.current===void 0?{}:{current:i.credentials.current},...i.credentials.projects===void 0?{}:{projects:i.credentials.projects}}},
|
|
268
|
-
${
|
|
269
|
-
`),r=(await e.prompt("API key: ",{mask:!0})).trim();b(r.length>0,"No API key entered.",{hint:{description:"Re-run toloka login and paste the key at the prompt, or pass --api-key."}});let o=e.style??xi,s={baseUrl:i,apiKey:r},a=e.probe?.(s)??Fn(s),g=await Nh(a,i,
|
|
270
|
-
`)}},Sh="api-key",
|
|
271
|
-
`)}},Xh=async(e)=>{for(let t of gg(e)){let i=await dr(t);if(i==="missing")continue;return typeof i==="object"?i.credentials:void 0}return};async function Eh(e={}){let t=e.environment??process.env,i=e.write??(()=>{return}),n=await Xh(t),r=pt(xn(e,t,n)),o=e.browser===void 0?t.TOLOKA_API_KEY:void 0;if(e.apiKey!==void 0||o!==void 0)return yI(e,t,r,i);let s=zs(r);if(s===void 0)return i(`Browser login is not available for ${r}, so an API key is needed.`),yI(e,t,r,i);let a=await
|
|
272
|
-
`)}}var Jh=(e)=>e.find((t)=>t!==void 0),
|
|
273
|
-
`)};let{value:C,source:m}=g;I.push(`Platform: ${C} (${m})`);let A;if(a!==void 0)I.push(`API key: ${e.showToken===!0?a.value:uC(a.value)} (${a.source})`),A={baseUrl:C,apiKey:a.value};else{b(l,"No login is in effect.",{hint:{description:"Run toloka login."}});let u=await
|
|
274
|
-
`)};A=u.clientConfig}if(I.push(d),t.TOLOKA_API_KEY!==void 0&&r?.credentials.apiKey!==void 0)I.push("",`TOLOKA_API_KEY is set, so the key stored in ${r.path} is ignored.`);if(r?.legacy===!0)I.push("",`Credentials still live at the old path ${r.path}. Run toloka login to move them to ${_e(t)}.`);let c=e.probe?.(A)??Fn(A);try{let u=await c.projects.listPage({limit:1});return I.push("",`Reachable: ${u.pagination.total} project(s) visible.`),I.push(...await
|
|
275
|
-
`)}}catch(u){let p=kh(u);return I.push("",`${
|
|
276
|
-
`)}}}var Oh=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("login").description("sign in through your browser, or store an API key, after verifying access").option("--browser","sign in through your browser without asking; pick the provider on the page it opens").option("--no-browser","the same, but print the sign-in link instead of opening a browser").option("--api-key-stdin","store an API key read from standard input instead",!1).action(async(o)=>{let s=o.apiKeyStdin?(await i.io.readStdin()).trim():r().apiKey,a=i.injectedClient,g=await Eh({...s===void 0?{}:{apiKey:s},...o.browser===void 0?{}:{browser:o.browser},...r().baseUrl===void 0?{}:{baseUrl:r().baseUrl},...i.io.prompt===void 0?{}:{prompt:i.io.prompt},...i.io.choose===void 0?{}:{choose:i.io.choose},...a===void 0?{}:{probe:()=>a},...i.browserLogin===void 0?{}:{browserLogin:i.browserLogin},...i.io.style===void 0?{}:{style:i.io.style},write:i.io.stdout,environment:i.environment});i.io.stdout(g.output);try{let l=await IC(i.environment),{client:d}=await ki(r(),i,void 0,l);await vi(d,i.analytics)}catch{}}),e.command("logout").description("remove stored credentials from this machine and end the browser login").action(async()=>{let o=r().baseUrl,s=await Th(i.environment,o===void 0?{}:{baseUrl:o});i.io.stdout(s.output)}),e.command("auth-status").alias("whoami").description("show which platform and login the CLI would use").option("--show-token","print the API key or access token instead of masking it",!1).action(async(o)=>{let s=r(),a=await en(i.environment,s.apiKey??i.environment.TOLOKA_API_KEY),g=a.found?.credentials,l=await Be(s,i.io),d=await Ae(l),I=ta(s,i,g,d),C=i.injectedClient,m=await Uh({environment:i.environment,showToken:o.showToken,credentialLookup:a,...s.apiKey===void 0?{}:{flagApiKey:s.apiKey},...s.baseUrl===void 0?{}:{flagBaseUrl:s.baseUrl},...C===void 0?{}:{probe:()=>C},...I===void 0?{}:{project:I}});if(i.io.stdout(m.output),!m.authenticated){n.value=1;return}try{let{client:A}=await ki(s,i,d,g);await vi(A,i.analytics)}catch{}})};var zh=(e,t)=>{let i=e.command("config").description("read and write machine CLI settings");i.command("get").argument("[name]","setting name; omit to print every setting").description("print a CLI setting, or every setting").action(async(n)=>{let r=await pr(t.context.environment);t.context.io.stdout(cg(r,n).output)}),i.command("set").argument("<name>","setting name").argument("<value>","setting value").description("write a CLI setting for this machine").action(async(n,r)=>{let o=await BC(t.context.environment,n,r);t.context.io.stdout(o.output)}),i.action(async()=>{let n=await pr(t.context.environment);t.context.io.stdout(cg(n,void 0).output)})};var xI=require("path");var Yn=require("fs/promises"),ro=require("path");var Kh=Symbol("sourceReference"),Lh={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},
|
|
267
|
+
`),{cause:n,hint:{disabled:!0}})}},xh=async(e,t)=>{let i=await dr(_e(e));if(typeof i!=="object")return{};if(pt(i.credentials.baseUrl)!==pt(t))return{};return{...i.credentials.current===void 0?{}:{current:i.credentials.current},...i.credentials.projects===void 0?{}:{projects:i.credentials.projects}}},KY=async(e)=>{if(e.me===void 0)return;try{let t=(await e.me()).email;return typeof t==="string"&&t.length>0?t:void 0}catch{return}},VI=(e)=>new Date(e*1000).toISOString().replace(/\.\d{3}Z$/u,"Z"),Yh=(e)=>`${e} ${e===1?"project":"projects"} visible`,yI=async(e,t,i,n)=>{let r=e.apiKey??t.TOLOKA_API_KEY;if(r===void 0)b(e.prompt,"No terminal to type the API key in. Pipe it to toloka login --api-key-stdin, pass --api-key, or set TOLOKA_API_KEY.",{hint:{disabled:!0}}),n(`
|
|
268
|
+
${QY(i)}
|
|
269
|
+
`),r=(await e.prompt("API key: ",{mask:!0})).trim();b(r.length>0,"No API key entered.",{hint:{description:"Re-run toloka login and paste the key at the prompt, or pass --api-key."}});let o=e.style??xi,s={baseUrl:i,apiKey:r},a=e.probe?.(s)??Fn(s),g=await Nh(a,i,DY),l=await xh(t,i),d=await Ir({baseUrl:i,apiKey:r,...l},t);return{credentialsFile:d,baseUrl:i,method:"apiKey",output:[`${o.green("\u2714")} Authenticated against ${o.bold(i)} with an API key`,o.dim(` ${Yh(g)} \xB7 stored in ${d}`),o.dim(` This API key does not expire. To revoke it, delete it in ${$s(i)??"the Business Console"}.`)].join(`
|
|
270
|
+
`)}},Sh="api-key",LY="browser",MY=(e)=>[{name:"Sign in with your browser",value:LY,description:`${e.identityProviders.map((t)=>t.name).join(", ")}. Lasts up to 14 days.`},{name:"Use an API key",value:Sh,description:"Paste a key from the Business Console. Works until you delete it; made for scripts, CI, and coding agents."}],$Y=async(e,t)=>{if(e.browser===!1)return{method:"browser",openBrowser:!1,requireBrowser:!1};if(e.browser===!0||e.choose===void 0)return{method:"browser",openBrowser:!0,requireBrowser:e.choose===void 0};return await e.choose("How do you want to sign in?",MY(t))===Sh?{method:"apiKey"}:{method:"browser",openBrowser:!0,requireBrowser:!1}},qY=async(e,t,i,n,r,o)=>{let s=await(e.browserLogin??Hh)({provider:n,openBrowser:r.openBrowser,requireBrowser:r.requireBrowser,registrationUrl:ph(i),...e.style===void 0?{}:{style:e.style},write:o},{environment:t,...e.fetch===void 0?{}:{fetch:e.fetch}}),a=aI(n,s,(e.now??Nn)()),g={baseUrl:i,accessToken:async()=>a.access_token},l=e.probe?.(g)??Fn(g),d=await Nh(l,i,_Y),I=await KY(l);await gI(a,n,t);let C=await xh(t,i),m=await Ir({baseUrl:i,...C},t),A=e.style??xi,c=a.refresh_token_expires_at>0?`session renews automatically until ${VI(a.refresh_token_expires_at)}, then run toloka login again`:"session renews automatically while the login service allows; when it lapses, run toloka login again";return{credentialsFile:m,baseUrl:i,method:"browser",output:[`${A.green("\u2714")} Logged in to ${A.bold(i)}${I===void 0?"":` as ${A.bold(I)}`}`,A.dim(` ${Yh(d)} \xB7 ${c}`)].join(`
|
|
271
|
+
`)}},Xh=async(e)=>{for(let t of gg(e)){let i=await dr(t);if(i==="missing")continue;return typeof i==="object"?i.credentials:void 0}return};async function Eh(e={}){let t=e.environment??process.env,i=e.write??(()=>{return}),n=await Xh(t),r=pt(xn(e,t,n)),o=e.browser===void 0?t.TOLOKA_API_KEY:void 0;if(e.apiKey!==void 0||o!==void 0)return yI(e,t,r,i);let s=zs(r);if(s===void 0)return i(`Browser login is not available for ${r}, so an API key is needed.`),yI(e,t,r,i);let a=await $Y(e,s);return a.method==="apiKey"?yI(e,t,r,i):qY(e,t,r,s,a,i)}var eS=async(e,t)=>{let i=[];for(let n of th){let r=await $r(n,e);if(r===void 0)continue;let o=await nh(n,r.refresh_token,t),s=await sh(n,e);i.push({issuer:n.issuer,ended:o,path:s})}return i},tS=(e)=>e.ended?`Signed out of ${e.issuer}.`:`The login at ${e.issuer} could not be ended and will expire on its own; the local session was removed.`;async function Th(e=process.env,t={}){let i=await Xh(e),n=pt(xn(t,e,i)),r=await cC(e),o=await eS(e,t.fetch);for(let g of o)if(g.path!==void 0)r.push(g.path);if(r.length===0)return{removed:r,output:`No stored credentials found at ${_e(e)}.`};let s=`This does not revoke the API key. Delete it in ${$s(n)??"the Business Console"} to do that.`,a=[`Removed ${r.join(", ")}.`,...i?.apiKey===void 0?[]:["",s],...o.flatMap((g)=>["",tS(g)])];return{removed:r,...o.length===0?{}:{sessionEnded:o.every((g)=>g.ended)},output:a.join(`
|
|
272
|
+
`)}}var Jh=(e)=>e.find((t)=>t!==void 0),iS=(e,t,i,n)=>Jh([e.flagApiKey===void 0?void 0:{value:e.flagApiKey,source:"from --api-key"},t.TOLOKA_API_KEY===void 0?void 0:{value:t.TOLOKA_API_KEY,source:"from TOLOKA_API_KEY"},i?.credentials.apiKey===void 0?void 0:{value:i.credentials.apiKey,source:`stored in ${n}`}]),nS=(e,t,i)=>{let n=oi(t);return Jh([e.flagBaseUrl===void 0?void 0:{value:e.flagBaseUrl.replace(/\/+$/u,""),source:"from --base-url"},t.TOLOKA_BASE_URL===void 0?void 0:{value:t.TOLOKA_BASE_URL,source:"from TOLOKA_BASE_URL"},n===void 0?void 0:{value:n,source:`from ENV=${t.ENV}`},i===void 0?void 0:{value:i.credentials.baseUrl,source:"stored"}])??{value:Hi,source:"default"}},rS=async(e)=>{if(e.me===void 0)return[];try{let t=await e.me(),i=typeof t.email==="string"&&t.email.length>0?[`Account: ${t.email}`]:[];if(t.teams===void 0)return[...i,`Internal: ${t.internal}`];let n=t.teams.map((r)=>{let o=[...r.internal?["internal"]:[],...r.writable?[]:["read-only"]];return o.length===0?r.id:`${r.id} (${o.join(", ")})`});return[...i,`Internal: ${t.internal}`,`Teams: ${n.length===0?"(none)":n.join(", ")}`]}catch{return[]}},vh=(e,t)=>{if(lI(e,t))return`expired on ${VI(e.refresh_token_expires_at)}; run toloka login`;return e.refresh_token_expires_at>0?`renews automatically; the current refresh window ends ${VI(e.refresh_token_expires_at)}`:"renews automatically"},oS=async(e,t,i,n,r)=>{let o=`Login: browser (stored in ${e.path})`,s=Qs({provider:e.provider,baseUrl:t,environment:i,...n.fetch===void 0?{}:{fetch:n.fetch},...n.now===void 0?{}:{now:n.now}});try{let a=await s(),g=await $r(e.provider,i)??e.session;return{lines:[o,`Session: ${vh(g,r)}`,...n.showToken===!0?[`Access token: ${a}`]:[]],clientConfig:{baseUrl:t,accessToken:s}}}catch(a){if(a instanceof Pn)return{lines:[o,`Session: ${vh(e.session,r)}`],failure:Ph.rejected(t)};return{lines:[o,"Session: could not be renewed"],failure:`Not reachable: ${a instanceof Error?a.message:String(a)}`}}};async function Uh(e={}){let t=e.environment??process.env,i=(e.now??Nn)(),n=e.credentialLookup??await en(t,e.flagApiKey??t.TOLOKA_API_KEY),{found:r,warning:o}=n,s=r?.path??_e(t),a=iS(e,t,r,s),g=nS(e,t,r),l=a===void 0?await _s(g.value,t):void 0,d=II(e.project,r?.credentials),I=o===void 0?[]:[o,""];if(a===void 0&&l===void 0)return I.push("Not logged in.","","Run toloka login to sign in through your browser, or store an API key with toloka login --api-key-stdin.","",d),{authenticated:!1,output:I.join(`
|
|
273
|
+
`)};let{value:C,source:m}=g;I.push(`Platform: ${C} (${m})`);let A;if(a!==void 0)I.push(`API key: ${e.showToken===!0?a.value:uC(a.value)} (${a.source})`),A={baseUrl:C,apiKey:a.value};else{b(l,"No login is in effect.",{hint:{description:"Run toloka login."}});let u=await oS(l,C,t,e,i);if(I.push(...u.lines),u.clientConfig===void 0)return I.push(d,"",u.failure??""),{authenticated:!1,output:I.join(`
|
|
274
|
+
`)};A=u.clientConfig}if(I.push(d),t.TOLOKA_API_KEY!==void 0&&r?.credentials.apiKey!==void 0)I.push("",`TOLOKA_API_KEY is set, so the key stored in ${r.path} is ignored.`);if(r?.legacy===!0)I.push("",`Credentials still live at the old path ${r.path}. Run toloka login to move them to ${_e(t)}.`);let c=e.probe?.(A)??Fn(A);try{let u=await c.projects.listPage({limit:1});return I.push("",`Reachable: ${u.pagination.total} project(s) visible.`),I.push(...await rS(c)),{authenticated:!0,output:I.join(`
|
|
275
|
+
`)}}catch(u){let p=kh(u);return I.push("",`${jY[p.kind]}: ${p.reason}`,"",Ph[p.kind](C)),{authenticated:!1,output:I.join(`
|
|
276
|
+
`)}}}var Oh=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("login").description("sign in through your browser, or store an API key, after verifying access").option("--browser","sign in through your browser without asking; pick the provider on the page it opens").option("--no-browser","the same, but print the sign-in link instead of opening a browser").option("--api-key-stdin","store an API key read from standard input instead",!1).action(async(o)=>{let s=o.apiKeyStdin?(await i.io.readStdin()).trim():r().apiKey,a=i.injectedClient,g=await Eh({...s===void 0?{}:{apiKey:s},...o.browser===void 0?{}:{browser:o.browser},...r().baseUrl===void 0?{}:{baseUrl:r().baseUrl},...i.io.prompt===void 0?{}:{prompt:i.io.prompt},...i.io.choose===void 0?{}:{choose:i.io.choose},...a===void 0?{}:{probe:()=>a},...i.browserLogin===void 0?{}:{browserLogin:i.browserLogin},...i.io.style===void 0?{}:{style:i.io.style},write:i.io.stdout,environment:i.environment});i.io.stdout(g.output);try{let l=await IC(i.environment),{client:d}=await ki(r(),i,void 0,l);await vi(d,i.analytics)}catch{}}),e.command("logout").description("remove stored credentials from this machine and end the browser login").action(async()=>{let o=r().baseUrl,s=await Th(i.environment,o===void 0?{}:{baseUrl:o});i.io.stdout(s.output)}),e.command("auth-status").alias("whoami").description("show which platform and login the CLI would use").option("--show-token","print the API key or access token instead of masking it",!1).action(async(o)=>{let s=r(),a=await en(i.environment,s.apiKey??i.environment.TOLOKA_API_KEY),g=a.found?.credentials,l=await Be(s,i.io),d=await Ae(l),I=ta(s,i,g,d),C=i.injectedClient,m=await Uh({environment:i.environment,showToken:o.showToken,credentialLookup:a,...s.apiKey===void 0?{}:{flagApiKey:s.apiKey},...s.baseUrl===void 0?{}:{flagBaseUrl:s.baseUrl},...C===void 0?{}:{probe:()=>C},...I===void 0?{}:{project:I}});if(i.io.stdout(m.output),!m.authenticated){n.value=1;return}try{let{client:A}=await ki(s,i,d,g);await vi(A,i.analytics)}catch{}})};var zh=(e,t)=>{let i=e.command("config").description("read and write machine CLI settings");i.command("get").argument("[name]","setting name; omit to print every setting").description("print a CLI setting, or every setting").action(async(n)=>{let r=await pr(t.context.environment);t.context.io.stdout(cg(r,n).output)}),i.command("set").argument("<name>","setting name").argument("<value>","setting value").description("write a CLI setting for this machine").action(async(n,r)=>{let o=await BC(t.context.environment,n,r);t.context.io.stdout(o.output)}),i.action(async()=>{let n=await pr(t.context.environment);t.context.io.stdout(cg(n,void 0).output)})};var xI=require("path");var Yn=require("fs/promises"),ro=require("path");var Kh=Symbol("sourceReference"),Lh={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},sS={arguments:!0,await:!0,break:!0,case:!0,catch:!0,class:!0,const:!0,continue:!0,debugger:!0,default:!0,delete:!0,do:!0,else:!0,enum:!0,eval:!0,export:!0,extends:!0,false:!0,finally:!0,for:!0,function:!0,if:!0,implements:!0,import:!0,in:!0,instanceof:!0,interface:!0,let:!0,new:!0,null:!0,package:!0,private:!0,protected:!0,public:!0,return:!0,static:!0,super:!0,switch:!0,this:!0,throw:!0,true:!0,try:!0,typeof:!0,var:!0,void:!0,while:!0,with:!0,yield:!0};function si(e,t){return e<t?-1:e>t?1:0}function jh(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")}function Mh(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function $h(e,t){let[i,...n]=Mh(e),o=`${(i??t).toLowerCase()}${n.map((a)=>`${a.slice(0,1).toUpperCase()}${a.slice(1).toLowerCase()}`).join("")}`,s=/^\d/.test(o)?`_${o}`:o;return Object.hasOwn(sS,s)?`${s}Value`:s}function aS(e,t){return Mh(e).map((i)=>i.toLowerCase()).join("-")||t}function BI(e,t,i){let n=new Map,r=new Set;for(let g of e){R(!r.has(g.key),`Naming key "${g.key}" is duplicated`),r.add(g.key);let l=t(g),d=n.get(l)??[];d.push(g),n.set(l,d)}let o=new Set(n.keys()),s=new Set,a=new Map;for(let[g,l]of[...n.entries()].toSorted(([d],[I])=>si(d,I))){let d=l.toSorted((I,C)=>si(I.key,C.key));for(let I of d){let C=g;if(d.length>1||i!==void 0&&Object.hasOwn(i,C))C=`${g}_${jh(I.key)}`;let m=2;while(s.has(C)||i!==void 0&&Object.hasOwn(i,C)||C!==g&&o.has(C))C=`${g}_${jh(I.key)}_${m}`,m+=1;s.add(C),a.set(I.key,C)}}return a}function gS(e){return typeof e==="object"&&e!==null&&Kh in e}function de(e){return" ".repeat(e)}function qe(e,t=0){if(gS(e))return e.name;if(R(e!==void 0,"Cannot emit an undefined source value"),typeof e==="number")R(Number.isFinite(e),"Cannot emit a non-finite number");if(e===null||typeof e!=="object"){let r=JSON.stringify(e);return R(r!==void 0,`Cannot emit a ${typeof e} source value`),r}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
|
|
277
277
|
${e.map((o)=>`${de(t+1)}${qe(o,t+1)}`).join(`,
|
|
278
278
|
`)}
|
|
279
279
|
${de(t)}]`}let i=Object.entries(e).filter(([,r])=>r!==void 0).toSorted(([r],[o])=>si(r,o));if(i.length===0)return"{}";return`{
|
|
280
280
|
${i.map(([r,o])=>{let s=r==="__proto__"?`[${JSON.stringify(r)}]`:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?r:JSON.stringify(r);return`${de(t+1)}${s}: ${qe(o,t+1)}`}).join(`,
|
|
281
281
|
`)}
|
|
282
|
-
${de(t)}}`}function to(e,t){return{field:t(e.id),optional:e.optional}}function oa(e,t){let{fieldProxyId:i,relations:n,...r}=e;return{...r,field:t(i),...n===void 0?{}:{relations:n.map(({id:o,...s})=>({...s,field:t(o)}))}}}function RI(e,t){let{targetEntity:i,...n}=e;return{...n,targetEntity:t(i)}}function Dh(e,t){return{...e,gradedEntities:e.gradedEntities.map((i)=>RI(i,t))}}var
|
|
282
|
+
${de(t)}}`}function to(e,t){return{field:t(e.id),optional:e.optional}}function oa(e,t){let{fieldProxyId:i,relations:n,...r}=e;return{...r,field:t(i),...n===void 0?{}:{relations:n.map(({id:o,...s})=>({...s,field:t(o)}))}}}function RI(e,t){let{targetEntity:i,...n}=e;return{...n,targetEntity:t(i)}}function Dh(e,t){return{...e,gradedEntities:e.gradedEntities.map((i)=>RI(i,t))}}var lS=["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"],dS=["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"],_h=(e,t)=>{if(e===void 0)return;let i={...e};for(let n of t)i[n]??=[];return i};function IS(e,t){switch(e.type){case"root":{let{datasetId:i,itemFilter:n,startedFieldProxies:r,completedFieldProxies:o,...s}=e.settings;return{...s,started:r.output.map((a)=>to(a,t)),completed:o.input.map((a)=>to(a,t))}}case"code":{let{fieldProxies:i,...n}=e.settings;return{...n,input:i.input.map((r)=>to(r,t)),output:i.output.map((r)=>to(r,t))}}case"generation":{let{entities:i,qualityCriteria:n,exam:r,checks:o,...s}=e.settings,a=_h(o,lS);return{...s,...a===void 0?{}:{checks:a},entities:{input:i.input.map((g)=>oa(g,t)),output:i.output.map((g)=>oa(g,t))},qualityCriteria:n.map((g)=>RI(g,t)),...r===void 0?{}:{exam:Dh(r,t)}}}case"match":{let{conditions:i,fieldProxies:n,...r}=e.settings;return{...r,conditions:i.map(({predicates:o,...s})=>({...s,predicates:o.map(({fieldProxyId:a,...g})=>({...g,field:t(a)}))})),input:n.input.map((o)=>to(o,t))}}case"quorum":{let{entities:i,qualityCriteria:n,exam:r,checks:o,...s}=e.settings,a=_h(o,dS);return{...s,...a===void 0?{}:{checks:a},entities:{input:i.input.map((g)=>oa(g,t)),output:i.output.map((g)=>oa(g,t))},qualityCriteria:n.map((g)=>RI(g,t)),...r===void 0?{}:{exam:Dh(r,t)}}}}}function cS(e,t,i,n){let r=new Set,s=IS(e,(d)=>{let I=n.get(d);return R(I,`Node "${e.id}" references unknown field "${d}"`),r.add(I),{name:I,[Kh]:!0}}),a=[...r].toSorted(si),g=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],l=e.type==="root"?[`${de(1)}${qe(s,1)}`,`${de(1)}${qe({id:e.id},1)}`]:[`${de(1)}${qe(e.settings.about.name,1)}`,`${de(1)}${qe(s,1)}`,`${de(1)}${qe({id:e.id},1)}`];return{binding:t,path:i,source:`${g.join(`
|
|
283
283
|
`)}
|
|
284
284
|
|
|
285
285
|
export const ${t} = ${e.type}(
|
|
@@ -295,7 +295,7 @@ ${o.join(`,
|
|
|
295
295
|
);`}}).toSorted((n,r)=>si(n.binding,r.binding)).map(({source:n})=>n).join(`
|
|
296
296
|
|
|
297
297
|
`)}
|
|
298
|
-
`}function ef(e){let t=new Map(e.map((n)=>[n,`field:${n.options?.id??n.name}`])),i=BI(e.map((n)=>({key:t.get(n)??"",name:n.name,fallback:"field"})),({name:n,fallback:r})=>$h(n,r),Lh);return qh(e,(n)=>{let r=t.get(n);R(r,`Field "${n.name}" has no source key`);let o=i.get(r);return R(o,`Field "${n.name}" has no source binding`),o})}function
|
|
298
|
+
`}function ef(e){let t=new Map(e.map((n)=>[n,`field:${n.options?.id??n.name}`])),i=BI(e.map((n)=>({key:t.get(n)??"",name:n.name,fallback:"field"})),({name:n,fallback:r})=>$h(n,r),Lh);return qh(e,(n)=>{let r=t.get(n);R(r,`Field "${n.name}" has no source key`);let o=i.get(r);return R(o,`Field "${n.name}" has no source binding`),o})}function uS(e,t){return qh(e.fields.map((i)=>({name:i.name,jsonSchema:i.jsonSchema,options:{id:i.id}})),(i)=>{let n=i.options?.id;R(n,`Field "${i.name}" has no source ID`);let r=t.get(n);return R(r,`Field "${n}" has no source binding`),r})}function Qh(e,t,i,n){let r=i.get(e.node);R(r,`Connection references unknown node "${e.node}"`);let o=n.get(r.id);switch(R(o,`Node "${r.id}" has no source binding`),r.type){case"root":return R(e.handle===(t==="output"?"started":"completed"),`Root ${t} handle "${e.handle}" cannot be authored`),`${o}.${t==="output"?"started":"completed"}`;case"code":case"generation":case"quorum":return R(e.handle===t,`${r.type} ${t} handle "${e.handle}" cannot be authored`),`${o}.${t}`;case"match":if(t==="input")return R(e.handle==="input",`Match input handle "${e.handle}" cannot be authored`),`${o}.input`;if(e.handle==="default")return`${o}.default`;let s=/^matched_(\d+)$/.exec(e.handle);R(s,`Match output handle "${e.handle}" cannot be authored`);let a=s[1];return R(a!==void 0,`Match output handle "${e.handle}" has no index`),R(String(Number(a))===a,`Match output handle "${e.handle}" is not canonical`),`${o}.matched(${a})`}}function CS(e,t,i,n,r){let o=new Map(e.nodes.map((I)=>[I.id,I])),s=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...n.values()].toSorted(si).join(", ")} } from './fields';`],...i.toSorted((I,C)=>si(I.path,C.path)).flatMap(({binding:I,path:C})=>[`import { ${I} } from './${C.slice(0,-3)}';`])],a=e.fields.map(({id:I})=>{let C=n.get(I);return R(C,`Field "${I}" has no source binding`),C}),g=e.nodes.map(({id:I})=>{let C=r.get(I);return R(C,`Node "${I}" has no source binding`),C}),l=e.connections.map((I)=>{let C=Qh(I.from,"output",o,r),m=Qh(I.to,"input",o,r);if(Object.keys(I.settings).length===0)return`connect(${C}, ${m})`;return`connect(
|
|
299
299
|
${de(3)}${C},
|
|
300
300
|
${de(3)}${m},
|
|
301
301
|
${de(3)}${qe(I.settings,3)}
|
|
@@ -311,47 +311,47 @@ export default definePipeline({
|
|
|
311
311
|
nodes: ${d(g,1)},
|
|
312
312
|
connections: ${d(l,1)}
|
|
313
313
|
});
|
|
314
|
-
`}function tf(e,t={dataset:"imported-dataset"}){let i=[...e.fields.map((l)=>({key:`field:${l.id}`,name:l.name,fallback:"field"})),...e.nodes.map((l)=>({key:`node:${l.id}`,name:l.type==="root"?"root":l.settings.about.name||l.type,fallback:l.type}))],n=BI(i,({name:l,fallback:d})=>$h(l,d),Lh),r=BI(e.nodes.map((l)=>({key:`node:${l.id}`,name:l.type==="root"?"root":l.settings.about.name||l.type,fallback:l.type})),({name:l,fallback:d})=>
|
|
315
|
-
`)},
|
|
316
|
-
`)}}async function df(e,t){let i=await ga(e,t);b(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."}}),b(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."}}),b(i.missingSecrets.length===0,`Required secrets are missing: ${i.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`,{hint:{disabled:!0}});let n=i.datasets.flatMap((I)=>I.conflictingFields.map((C)=>`${I.name}.${C.name}`));b(n.length===0,`Dataset field schemas conflict with source: ${n.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 r=0,o=new Map;for(let I of i.datasets){let C=I.dataset;if(C===void 0)C=await e.datasets.create({projectId:i.projectId,name:I.name}),r+=1;if(o.set(I.name,C.id),I.missingFields.length>0)await e.datasets.createFields({datasetId:C.id,fields:I.missingFields.map((m)=>({name:m.name,jsonSchema:m.jsonSchema}))}),r+=I.missingFields.length}let s=new Map;for(let I of i.pipelines){let C=o.get(I.source.definition.dataset);b(C,`Dataset ${I.source.definition.dataset} has no resolved ID.`,{hint:P});let m=_r(I.source.definition,{datasetId:C});if(I.pipeline===void 0){let c=await e.pipelines.import({projectId:i.projectId,name:I.source.name,graph:m});await e.pipelines.attachDataset({pipelineId:c.id,datasetId:C}),s.set(I.source.sourceDirectory,c.id),r+=2;continue}if(s.set(I.source.sourceDirectory,I.pipeline.id),I.graphChanges.length===0)continue;let A=I.snapshot;b(A,`Pipeline ${I.pipeline.id} has no graph snapshot.`,{hint:P}),await e.pipelines.replaceGraph({pipelineId:I.pipeline.id,graph:vI(m,A.graph),expectedVersion:A.version}),r+=1}let a={projectId:i.projectId,pipelines:Object.fromEntries(i.source.pipelines.map((I)=>{let C=s.get(I.sourceDirectory);return b(C,`Pipeline ${I.sourceDirectory} has no resolved ID.`,{hint:P}),[I.sourceDirectory,{pipelineId:C}]})),datasets:Object.fromEntries(i.datasets.map((I)=>{let C=o.get(I.name);return b(C,`Dataset ${I.name} has no resolved ID.`,{hint:P}),[I.name,{datasetId:C}]}))};if(Je(i.state)!==Je(a))await ri(t.sourceRoot,a);let g=r===0?"unchanged":"changed",l=i.changes.length,d=r===0?"No changes.":`Applied ${l} planned ${l===1?"change":"changes"} with ${r} platform ${r===1?"write":"writes"} to project ${i.projectId}.`;return{action:g,state:a,changes:i.changes,writes:r,output:d}}var
|
|
317
|
-
`);if(t.has(g))return[];return t.add(g),[a]}),n=i.some((s)=>s.code===HI),o=i.some((s)=>s.severity==="error"&&s.code!==HI)||!e.valid&&!n?"invalid":n?"checks_pending":"valid";return{status:o,report:{...e,valid:o!=="invalid",issues:i}}},
|
|
318
|
-
`)}}var Cf="uploaded",
|
|
319
|
-
`)},mf=async(e)=>{let t=e.source??await Rn(e.sourceRoot),i=aa(t).find((n)=>n.name===e.datasetName);return i===void 0?[]:i.fields.map((n)=>({name:n.name,jsonSchema:n.jsonSchema}))},uf=(e)=>`${e.name} (${e.id})`,pf=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})},NI=async(e,t,i)=>{let n=await Ae(t.sourceRoot),r=t.projectId??n?.projectId;S(r);let o=t.datasetName,s=await pf(e,r),a=(m)=>s.filter((A)=>A.name===m).length<=1,g=
|
|
320
|
-
Run toloka dataset fields ${JSON.stringify(I)} to inspect the inferred schema stored from the first successful upload.`:"";b(d.status==="succeeded",`${d.error??`Dataset upload ${d.id} failed.`}${C}`,{hint:{disabled:!0}});let m=`Uploaded ${d.result.itemsIngested} rows to dataset ${o.name}.`,A=[],c,u;try{A=(await e.datasets.getInferredFields({datasetId:s})).fields,c=
|
|
314
|
+
`}function tf(e,t={dataset:"imported-dataset"}){let i=[...e.fields.map((l)=>({key:`field:${l.id}`,name:l.name,fallback:"field"})),...e.nodes.map((l)=>({key:`node:${l.id}`,name:l.type==="root"?"root":l.settings.about.name||l.type,fallback:l.type}))],n=BI(i,({name:l,fallback:d})=>$h(l,d),Lh),r=BI(e.nodes.map((l)=>({key:`node:${l.id}`,name:l.type==="root"?"root":l.settings.about.name||l.type,fallback:l.type})),({name:l,fallback:d})=>aS(l,d)),o=new Map(e.fields.map((l)=>{let d=n.get(`field:${l.id}`);return R(d,`Field "${l.id}" has no allocated binding`),[l.id,d]})),s=new Map(e.nodes.map((l)=>{let d=n.get(`node:${l.id}`);return R(d,`Node "${l.id}" has no allocated binding`),[l.id,d]})),a=e.nodes.map((l)=>{let d=s.get(l.id),I=r.get(`node:${l.id}`);return R(d&&I,`Node "${l.id}" has no allocated source name`),cS(l,d,`nodes/${I}/node.ts`,o)}),g=[{path:"fields.ts",source:uS(e,o)},...a.map(({path:l,source:d})=>({path:l,source:d})),{path:"pipeline.ts",source:CS(e,t.dataset,a,o,s)}].toSorted((l,d)=>si(l.path,d.path));return Object.fromEntries(g.map(({path:l,source:d})=>[l,d]))}var St=require("fs/promises"),Yi=require("path");function nf(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 mS=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,wI=(e)=>{if(Array.isArray(e))return e.map(wI);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,wI(i)]))},Je=(e)=>JSON.stringify(wI(e)),rf=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),sf=(e,t)=>{if(!rf(e)||!rf(t))return t;return Object.fromEntries(Object.keys(e).map((i)=>[i,sf(e[i],t[i])]))},pS=(e,t)=>Je(e)===Je(sf(e,t)),io=async(e)=>{let t=[];for await(let i of e)t.push(i);return t},FI=(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},AS=(e)=>`${e.name} (${e.id})`,bS=(e,t)=>{let i=t.get(e.from.node),n=t.get(e.to.node),r=i===void 0?e.from.node:FI(i),o=n===void 0?e.to.node:FI(n);return`${r}.${e.from.handle} -> ${o}.${e.to.handle}`},sa=(e)=>new Map(e.map((t)=>[t.id,t])),GI=(e,t,i,n)=>{let r=[];for(let[o,s]of[...e].toSorted(([a],[g])=>a.localeCompare(g))){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],[g])=>a.localeCompare(g)))if(!e.has(o))r.push(n(s,"removed"));return r};function ZS(e,t){let i=sa(e.nodes),n=sa(t.nodes),r=new Map(e.connections.map((s)=>[Je(s),s])),o=new Map(t.connections.map((s)=>[Je(s),s]));return[...GI(sa(e.fields),sa(t.fields),(s,a)=>Je(s)===Je(a),(s,a)=>({kind:"field",action:a,label:AS(s),id:s.id})),...GI(i,n,pS,(s,a)=>({kind:"node",action:a,label:FI(s),id:s.id})),...GI(r,o,()=>!0,(s,a)=>({kind:"connection",action:a,label:bS(s,a==="removed"?n:i)})),...Je(e.layout)===Je(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var vI=(e,t)=>{let i=t.nodes.find((r)=>r.type==="root"),n=i===void 0?{}:{...i.settings.itemFilter===void 0?{}:{itemFilter:i.settings.itemFilter},...i.settings.itemLimit===void 0?{}:{itemLimit:i.settings.itemLimit}};return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((r)=>r.type==="root"?{...r,settings:{...n,...r.settings}}:r)}},aa=(e)=>{let t=new Map;for(let i of e.pipelines){let n=t.get(i.definition.dataset);if(n===void 0)n=new Map,t.set(i.definition.dataset,n);for(let r of i.definition.graph.fields){let o=n.get(r.name);if(b(o===void 0||Je(o.jsonSchema)===Je(r.jsonSchema),`Dataset "${i.definition.dataset}" has conflicting schemas for field "${r.name}".`,{hint:{description:"Give the field one JSON schema across all pipelines that share the dataset."}}),o===void 0)n.set(r.name,r)}}return[...t].toSorted(([i],[n])=>i.localeCompare(n)).map(([i,n])=>({name:i,fields:[...n.values()].toSorted((r,o)=>r.name.localeCompare(o.name))}))},hS=(e)=>{let t=new Set;for(let i of e.pipelines)b(mS.test(i.sourceDirectory),`Invalid pipeline source directory ${i.sourceDirectory}`,{hint:{description:"Use a relative path without backslashes, // or . and .. segments."}}),b(!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),Ss(i.definition);aa(e)},fS=(e,t,i)=>{let n=t===void 0?void 0:i.find((o)=>o.id===t.datasetId);if(n!==void 0)return b(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 b(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]},WS=(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 b(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]},yS=(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}`}},VS=(e,t)=>{if(e.length===0)return"No changes.";let i=e.length===1?"change":"changes",n=[`Plan: ${e.length} ${i}`,...e.map(yS)];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(`
|
|
315
|
+
`)},BS=async(e,t,i,n)=>{let r=t.map((s)=>({desired:s,dataset:fS(s.name,i?.datasets[s.name],n)})),o=await Promise.all(r.map(async({dataset:s})=>s===void 0?[]:io(e.datasets.listAllFields({datasetId:s.id}))));return r.map(({desired:s,dataset:a},g)=>{let l=o[g]??[],d=new Map(l.map((I)=>[I.name,I]));return{...s,...a===void 0?{}:{dataset:a},liveFields:l,missingFields:s.fields.filter((I)=>!d.has(I.name)),conflictingFields:s.fields.filter((I)=>{let C=d.get(I.name);return C!==void 0&&Je(C.jsonSchema)!==Je(I.jsonSchema)})}})},RS=async(e,t,i,n,r)=>{let o=t.pipelines.map((a)=>({source:a,pipeline:WS(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:g},l)=>{let d=s[l],I=n.find((m)=>m.name===a.definition.dataset)?.dataset,C=[];if(g!==void 0&&d!==void 0)C=I===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:ZS(vI(_r(a.definition,{datasetId:I.id}),d.graph),d.graph);return{source:a,...g===void 0?{}:{pipeline:g},...d===void 0?{}:{snapshot:d},graphChanges:C}})},GS=(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},ga=async(e,t)=>{let i=t.source??await Rn(t.sourceRoot);hS(i);let n=await Ae(t.sourceRoot),r=t.projectId??n?.projectId;S(r);let o=n?.projectId===r?n:void 0,s=new Set(i.pipelines.flatMap(({definition:Z})=>nf(Z.graph))),a=t.listAllSecrets===!0||s.size>0,[g,l,d]=await Promise.all([io(e.pipelines.listAll({projectId:r})),io(e.datasets.listAll({projectId:r})),a?e.secrets.list({projectId:r}):Promise.resolve([])]),I=aa(i),C=Object.keys(o?.datasets??{}).filter((Z)=>!I.some((h)=>h.name===Z)).toSorted(),m=Object.keys(o?.pipelines??{}).filter((Z)=>!i.pipelines.some((h)=>h.sourceDirectory===Z)).toSorted(),A=await BS(e,I,o,l),c=await RS(e,i,o,A,g),u=new Set(d.map((Z)=>Z.name)),p=[...s].filter((Z)=>!u.has(Z)).toSorted();return{projectId:r,source:i,state:n,datasets:A,pipelines:c,livePipelines:g,liveDatasets:l,liveSecrets:d,changes:GS(A,c,p,C,m),missingSecrets:p,removedDatasets:C,removedPipelines:m}},of=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",wS=(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")},FS=(e)=>{let t=Map.groupBy(e,(i)=>of(i.name));return new Map(e.map((i)=>{let n=of(i.name),r=(t.get(n)?.length??0)>1;return[i.id,`pipelines/${r?`${n}-${wS(i.id)}`:n}`]}))};async function af(e,t){let i=(await io(e.pipelines.listAll({projectId:t.projectId}))).toSorted((Z,h)=>Z.name.localeCompare(h.name)||Z.id.localeCompare(h.id)),n=await Promise.all(i.map((Z)=>e.pipelines.getGraph({pipelineId:Z.id}))),r=new Set;for(let Z of n){let h=Z.graph.nodes.find((W)=>W.type==="root");b(h?.settings.datasetId,"Every imported pipeline must have a bound dataset.",{hint:{description:"Bind a dataset to the pipeline in the platform, then re-run toloka import."}}),r.add(h.settings.datasetId)}let o=await io(e.datasets.listAll({projectId:t.projectId})),s=[];for(let Z of[...r].toSorted()){let h=o.find((W)=>W.id===Z);b(h,`Project ${t.projectId} has no dataset ${Z}.`,{hint:{description:"Check toloka dataset list; the pipeline's dataset binding must point at a dataset of this project."}}),s.push(h)}let a=new Map(s.map((Z)=>[Z.id,Z])),g=FS(i),l={},d={},I={};for(let[Z,h]of i.entries()){let W=n[Z];b(W,`Pipeline ${h.id} has no graph snapshot.`,{hint:P});let y=W.graph.nodes.find((v)=>v.type==="root");b(y?.settings.datasetId,`Pipeline ${h.id} has no dataset binding.`,{hint:{description:"Bind a dataset to the pipeline in the platform, then re-run toloka import."}});let V=a.get(y.settings.datasetId);b(V,`Pipeline ${h.id} references unknown dataset ${y.settings.datasetId}.`,{hint:{description:"Check toloka dataset list; the pipeline's dataset binding must point at a dataset of this project."}});let H=I[V.name];b(H===void 0||H.datasetId===V.id,`Project has multiple referenced datasets named "${V.name}".`,{hint:{description:"Rename the duplicate datasets in the platform, then re-run toloka import."}}),I[V.name]={datasetId:V.id};let Y=g.get(h.id);b(Y,`Pipeline ${h.id} has no source directory.`,{hint:P}),d[Y]={pipelineId:h.id};for(let[v,K]of Object.entries(tf(W.graph,{dataset:V.name})))l[`${Y}/${v}`]=K}await St.mkdir(t.sourceRoot,{recursive:!0});let C=Yi.join(t.sourceRoot,"pipelines"),m=!1;try{m=(await St.stat(C)).isDirectory()}catch(Z){if(!(Z instanceof Error)||!("code"in Z)||Z.code!=="ENOENT")throw Z}if(b(!m||t.force===!0,`Folder already exists: ${C}. Pass --force to replace it.`,{hint:{disabled:!0}}),m)await St.rm(C,{recursive:!0,force:!0});for(let[Z,h]of Object.entries(l).toSorted(([W],[y])=>W.localeCompare(y))){let W=Yi.join(t.sourceRoot,Z);await St.mkdir(Yi.dirname(W),{recursive:!0}),await St.writeFile(W,h,"utf8")}let A={projectId:t.projectId,pipelines:d,datasets:I};await ri(t.sourceRoot,A);let c=[...Object.keys(l),Gi].toSorted(),u=i.length===1?"pipeline":"pipelines",p=s.length===1?"dataset":"datasets";return{state:A,files:c,output:`Imported project ${t.projectId} with ${i.length} ${u} and ${s.length} ${p} into ${Yi.resolve(t.sourceRoot)}.`}}async function gf(e,t){let i=await ga(e,t);return{projectId:i.projectId,changes:i.changes,missingSecrets:i.missingSecrets,output:VS(i.changes,i.missingSecrets)}}async function lf(e,t){let i=t.projectId;S(i);let n=await e.projects.get({projectId:i}),r=await ga(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(`
|
|
316
|
+
`)}}async function df(e,t){let i=await ga(e,t);b(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."}}),b(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."}}),b(i.missingSecrets.length===0,`Required secrets are missing: ${i.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`,{hint:{disabled:!0}});let n=i.datasets.flatMap((I)=>I.conflictingFields.map((C)=>`${I.name}.${C.name}`));b(n.length===0,`Dataset field schemas conflict with source: ${n.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 r=0,o=new Map;for(let I of i.datasets){let C=I.dataset;if(C===void 0)C=await e.datasets.create({projectId:i.projectId,name:I.name}),r+=1;if(o.set(I.name,C.id),I.missingFields.length>0)await e.datasets.createFields({datasetId:C.id,fields:I.missingFields.map((m)=>({name:m.name,jsonSchema:m.jsonSchema}))}),r+=I.missingFields.length}let s=new Map;for(let I of i.pipelines){let C=o.get(I.source.definition.dataset);b(C,`Dataset ${I.source.definition.dataset} has no resolved ID.`,{hint:P});let m=_r(I.source.definition,{datasetId:C});if(I.pipeline===void 0){let c=await e.pipelines.import({projectId:i.projectId,name:I.source.name,graph:m});await e.pipelines.attachDataset({pipelineId:c.id,datasetId:C}),s.set(I.source.sourceDirectory,c.id),r+=2;continue}if(s.set(I.source.sourceDirectory,I.pipeline.id),I.graphChanges.length===0)continue;let A=I.snapshot;b(A,`Pipeline ${I.pipeline.id} has no graph snapshot.`,{hint:P}),await e.pipelines.replaceGraph({pipelineId:I.pipeline.id,graph:vI(m,A.graph),expectedVersion:A.version}),r+=1}let a={projectId:i.projectId,pipelines:Object.fromEntries(i.source.pipelines.map((I)=>{let C=s.get(I.sourceDirectory);return b(C,`Pipeline ${I.sourceDirectory} has no resolved ID.`,{hint:P}),[I.sourceDirectory,{pipelineId:C}]})),datasets:Object.fromEntries(i.datasets.map((I)=>{let C=o.get(I.name);return b(C,`Dataset ${I.name} has no resolved ID.`,{hint:P}),[I.name,{datasetId:C}]}))};if(Je(i.state)!==Je(a))await ri(t.sourceRoot,a);let g=r===0?"unchanged":"changed",l=i.changes.length,d=r===0?"No changes.":`Applied ${l} planned ${l===1?"change":"changes"} with ${r} platform ${r===1?"write":"writes"} to project ${i.projectId}.`;return{action:g,state:a,changes:i.changes,writes:r,output:d}}var HS=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),HI="not_ran_node_check",vS=(e)=>e.code==="empty_node_checks"?{...e,message:"No stored check cases are configured for this node"}:e,kS=(e)=>{let t=new Set,i=e.issues.flatMap((s)=>{let a=vS(s),g=[a.code,a.severity,a.nodeId??"",a.checkId??"",a.message].join(`
|
|
317
|
+
`);if(t.has(g))return[];return t.add(g),[a]}),n=i.some((s)=>s.code===HI),o=i.some((s)=>s.severity==="error"&&s.code!==HI)||!e.valid&&!n?"invalid":n?"checks_pending":"valid";return{status:o,report:{...e,valid:o!=="invalid",issues:i}}},PS=(e)=>e.issues.map((t)=>{let i=HS(t);return` ${t.code===HI?"pending":t.severity} ${t.code}${i.length===0?"":` ${i}`}: ${t.message}`});async function If(e,t){let i=await ga(e,t),n=[];for(let s of i.pipelines){let a=i.datasets.find((d)=>d.name===s.source.definition.dataset)?.dataset;if(s.pipeline===void 0){n.push({sourceDirectory:s.source.sourceDirectory,skipped:"pipeline is not on the platform yet; run toloka apply first"});continue}if(a===void 0){n.push({sourceDirectory:s.source.sourceDirectory,pipelineId:s.pipeline.id,skipped:`dataset "${s.source.definition.dataset}" is not on the platform yet; run toloka apply first`});continue}let g=s.snapshot===void 0?_r(s.source.definition,{datasetId:a.id}):vI(_r(s.source.definition,{datasetId:a.id}),s.snapshot.graph),l=kS(await e.pipelines.validateGraph({pipelineId:s.pipeline.id,graph:g}));n.push({sourceDirectory:s.source.sourceDirectory,pipelineId:s.pipeline.id,report:l.report,status:l.status})}let r=n.every((s)=>s.status!=="invalid"),o=n.flatMap((s)=>{if(s.skipped!==void 0)return[`- ${s.sourceDirectory}: skipped (${s.skipped})`];return b(s.report,`Pipeline ${s.sourceDirectory} is missing a validation report`,{hint:P}),b(s.status,`Pipeline ${s.sourceDirectory} is missing a validation status`,{hint:P}),[`- ${s.sourceDirectory}: ${s.status.replace("_","-")}`,...PS(s.report)]});return{projectId:i.projectId,results:n,valid:r,output:o.length===0?"No pipelines to validate.":o.join(`
|
|
318
|
+
`)}}var Cf="uploaded",NS=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cf=3;class no extends F{constructor(e,t){super(e,t);this.name="DatasetUploadError"}}var xS=(e)=>NS.test(e)?e.toLowerCase():void 0,YS={json:"application/json",jsonl:"application/x-ndjson",csv:"text/csv"},PI=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),kI=(e)=>{if(!PI(e))return"unknown";if(Array.isArray(e.anyOf)){let n=[...new Set(e.anyOf.map(kI))];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=kI(e.items);return r==="unknown"?"array":`array<${r}>`}).join(" | ")},SS=(e)=>{if(e.length===0)return"No inferred fields are available yet.";return["Inferred fields:",...e.toSorted((t,i)=>t.jsonPath.localeCompare(i.jsonPath)).map((t)=>`${" ".repeat(t.depth)}- ${t.jsonPath}: ${kI(t.jsonSchema)}`)].join(`
|
|
319
|
+
`)},mf=async(e)=>{let t=e.source??await Rn(e.sourceRoot),i=aa(t).find((n)=>n.name===e.datasetName);return i===void 0?[]:i.fields.map((n)=>({name:n.name,jsonSchema:n.jsonSchema}))},uf=(e)=>`${e.name} (${e.id})`,pf=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})},NI=async(e,t,i)=>{let n=await Ae(t.sourceRoot),r=t.projectId??n?.projectId;S(r);let o=t.datasetName,s=await pf(e,r),a=(m)=>s.filter((A)=>A.name===m).length<=1,g=xS(o),l=s.find((m)=>m.id===o||m.id.toLowerCase()===g);if(l!==void 0)return{datasetId:l.id,name:l.name,nameIsUnique:a(l.name)};let d=s.filter((m)=>m.name===o);if(b(d.length<=1,`Project ${r} has multiple datasets named "${o}": ${d.map(uf).join(", ")}.`,{hint:{description:"Pass the dataset id (ds.\u2026) instead of the name."}}),d.length===1){let[m]=d;return b(m,`Dataset "${o}" has no resolved ID.`,{hint:P}),{datasetId:m.id,name:m.name,nameIsUnique:!0}}let I=n?.projectId===r?n.datasets[o]:void 0;if(I!==void 0){let m=s.find((A)=>A.id===I.datasetId);if(m!==void 0)return{datasetId:m.id,name:m.name,nameIsUnique:a(m.name)}}b(i&&g===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: ${s.map(uf).join(", ")}.`,{hint:{disabled:!0}}),b((await mf(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 C=await e.datasets.create({projectId:r,name:o});return{datasetId:C.id,name:C.name,nameIsUnique:!0}},XS=(e)=>{let t=e.toLowerCase();if(t.endsWith(".json"))return"json";if(t.endsWith(".jsonl"))return"jsonl";if(t.endsWith(".csv"))return"csv";b(!1,`${e} must have a .json, .jsonl, or .csv extension`,{hint:{description:"Rename the file with the extension that matches its format."}})},ES=async(e)=>{let t=ro.basename(e),i=XS(t),n=await Yn.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{b(!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."}})}b(PI(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:YS[i]}},la=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 no(`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 no(`Dataset upload ${t} failed and was canceled: ${n}`,{cause:i,hint:{description:"Fix the upload error above, then re-run toloka dataset upload."}})},TS=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(g){return la(e,t.job.id,g)}if(!s.ok)return la(e,t.job.id,new no(`Dataset upload failed with HTTP ${s.status}.`,{hint:Tt}));let a=0;while(!0)try{await e.datasets.finalizeUpload({uploadId:t.job.id});return}catch(g){if(!(g instanceof te&&g.status===503))return la(e,t.job.id,g);if(a+=1,a===cf)return la(e,t.job.id,new no(`Storage remained unavailable after ${cf} finalization attempts.`,{cause:g,hint:Tt}));let{promise:l,resolve:d}=Promise.withResolvers();setTimeout(d,o),await l}};async function Af(e,t){let i=t.name.trim();b(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 bf(e,t){let{payload:i,format:n,contentType:r}=await ES(t.filePath),o=await NI(e,t,!0),s=o.datasetId,a=new Map;for await(let p of e.datasets.listAllFields({datasetId:s})){if(p.internal||p.name===Cf)continue;a.set(p.name,{name:p.name,jsonSchema:p.jsonSchema})}for(let p of await mf({...t,datasetName:o.name}))if(!a.has(p.name))a.set(p.name,p);let g=[...a.values()],l=await e.datasets.startUpload({datasetId:s,filename:ro.basename(t.filePath),format:n,declaredSizeBytes:new TextEncoder().encode(i).byteLength,fields:g});await TS({client:e,started:l,payload:i,contentType:r,fetch:t.fetch??globalThis.fetch,retryIntervalMs:t.waitFor?.intervalMs??1000});let d=await e.waitFor({type:"datasetUpload",uploadId:l.job.id},t.waitFor),I=o.nameIsUnique?o.name:o.datasetId,C=d.status==="failed"&&d.error?.startsWith("Schema incompatible with existing upload")===!0?`
|
|
320
|
+
Run toloka dataset fields ${JSON.stringify(I)} to inspect the inferred schema stored from the first successful upload.`:"";b(d.status==="succeeded",`${d.error??`Dataset upload ${d.id} failed.`}${C}`,{hint:{disabled:!0}});let m=`Uploaded ${d.result.itemsIngested} rows to dataset ${o.name}.`,A=[],c,u;try{A=(await e.datasets.getInferredFields({datasetId:s})).fields,c=SS(A)}catch(p){u=`Upload succeeded, but inferred fields could not be fetched: ${p instanceof Error?p.message:String(p)}`}return{datasetId:s,rowsUploaded:d.result.itemsIngested,inferredFields:A,output:c===void 0?m:`${m}
|
|
321
321
|
${c}`,...u===void 0?{}:{warning:u}}}async function Zf(e,t){let i=await NI(e,t,!1),n=await e.datasets.getInferredFields({datasetId:i.datasetId}),r=n.fields.filter((s)=>s.depth===1),o=ef(r.map(({name:s,jsonSchema:a})=>({name:s,jsonSchema:a})));return{datasetId:i.datasetId,inferredFields:n.fields,declarations:o,output:r.length===0?`Dataset ${i.name} has no inferred fields yet.`:o}}async function hf(e,t){let i=await pf(e,t.projectId);if(i.length===0)return{output:"This project has no datasets."};return{output:i.map((n)=>`${n.name} ${n.id}`).join(`
|
|
322
|
-
`)}}var
|
|
322
|
+
`)}}var JS=async(e)=>{let t=await e.fetch(e.downloadUrl);b(t.ok,`Dataset export download failed with HTTP ${t.status}.`,{hint:Tt});let i=await t.text(),n;try{n=JSON.parse(i)}catch(o){throw new F(`Dataset export ${e.exportId} is not valid JSON.`,{cause:o,hint:P})}b(Array.isArray(n),`Dataset export ${e.exportId} is not a JSON array.`,{hint:P});let r=[];for(let[o,s]of n.entries())b(PI(s),`Dataset export ${e.exportId} row ${o} is not a JSON object.`,{hint:P}),r.push(s);return r};async function ff(e,t){let i=await NI(e,t,!1),n=[];for await(let g of e.datasets.listAllFields({datasetId:i.datasetId})){if(g.internal||g.name===Cf)continue;n.push(g.name)}b(n.length>0,`Dataset ${i.name} has no fields to export.`,{hint:{description:"Upload rows first with toloka dataset upload <name> <file>."}});let r=await e.datasets.startExport({datasetId:i.datasetId,fields:n}),o;try{o=await e.waitFor({type:"datasetExport",exportId:r.id},t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs})}catch(g){throw b(!(g instanceof te&&g.code==="wait_timeout"),`Stopped waiting for dataset export ${r.id}; raise --timeout to wait longer.`,{hint:{disabled:!0}}),g}b(o.result.downloadUrl,`Dataset export ${o.id} succeeded without a download URL.`,{hint:P});let s=await JS({downloadUrl:o.result.downloadUrl,exportId:o.id,fetch:t.fetch??globalThis.fetch}),a=t.limit===void 0?s:s.slice(0,t.limit);return await Yn.mkdir(ro.dirname(t.outPath),{recursive:!0}),await Yn.writeFile(t.outPath,a.length===0?"":`${a.map((g)=>JSON.stringify(g)).join(`
|
|
323
323
|
`)}
|
|
324
324
|
`),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function Wf(e,t){return await e.secrets.set({projectId:t.projectId,name:t.name,value:t.value}),{name:t.name,output:`Set secret ${t.name}.`}}var yf=(e,t)=>{let{context:i,globals:n}=t,r=e.command("dataset").description("inspect and move dataset catalog and rows");r.command("list").description("list live datasets in the selected project").action(async()=>{let{client:o,projectId:s}=await w(n(),i);S(s);let a=await hf(o,{projectId:s});i.io.stdout(a.output)}),r.command("create").argument("<name>","dataset name").description("create an empty dataset in the selected project").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);S(a);let g=await Af(s,{projectId:a,name:o});i.io.stdout(g.output)}),r.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(o)=>{let{sourceRoot:s,client:a,projectId:g}=await w(n(),i),l=await Zf(a,{sourceRoot:s,datasetName:o,...g===void 0?{}:{projectId:g}});i.io.stdout(l.output)}),r.command("load").argument("<name>","dataset name or id").requiredOption("--out <file>","JSONL file to write").option("--limit <n>","how many rows to keep after download",Te).option("--timeout <ms>","how long to wait for the export",Te).description("download live dataset rows into a JSONL file").action(async(o,s)=>{let{sourceRoot:a,client:g,projectId:l}=await w(n(),i),d=await ff(g,{sourceRoot:a,datasetName:o,outPath:xI.resolve(s.out),...l===void 0?{}:{projectId:l},...s.limit===void 0?{}:{limit:s.limit},...s.timeout===void 0?{}:{timeoutMs:s.timeout}});i.io.stdout(d.output)}),r.command("upload").argument("<name>","dataset name or id").argument("<file>","JSON array, JSONL, or CSV file").description("append rows to a dataset").action(async(o,s)=>{let{sourceRoot:a,client:g,projectId:l}=await w(n(),i),d=await bf(g,{sourceRoot:a,datasetName:o,filePath:xI.resolve(s),...l===void 0?{}:{projectId:l}});if(i.io.stdout(d.output),d.warning!==void 0)i.io.stderr(d.warning)})};async function Vf(e){let t;try{t=await e.client.deliveryOrders.list()}catch(i){if(i instanceof te&&i.status===403)throw new F("Delivery orders are available to internal teams only.",{cause:i,hint:{description:"Run toloka whoami; when it prints Internal: false, create the project without --delivery-order-id."}});throw i}if(t.length===0)return{output:"No delivery orders visible."};return{output:["ID\tNAME\tSTATUS\tCLIENT",...t.map((i)=>`${i.id} ${i.name} ${i.status} ${i.clientName??"-"}`)].join(`
|
|
325
|
-
`)}}var Bf=(e,t)=>{let{context:i,globals:n}=t;e.command("delivery-order").description("list Sunday delivery orders for project create").command("list").description("list active Sunday delivery orders this key can attach").action(async()=>{let{client:o}=await w(n(),i),s=await Vf({client:o});i.io.stdout(s.output)})};var da=require("crypto"),oo=require("fs"),et=require("fs/promises"),lt=require("path"),Ia=require("stream"),Rf=require("stream/promises");var JS=["qwen3-4b","qwen3-8b","qwen3-32b","qwen3-235b"],US=(e)=>ge([["ID",e.id],["Name",e.displayName],["Provider",e.provider],["Upstream model",e.upstreamModel],["Upstream revision",e.upstreamRevision],["Upstream snapshot",e.upstreamUrl]]),Gf=(e)=>ge([["ID",e.id],["Project",e.projectId],["Name",e.name],["Base model",e.baseModelId],["Description",e.description??"-"],["Archived at",e.archivedAt??"-"],["Created at",e.createdAt],["Updated at",e.updatedAt]]),Sn=(e)=>{let t=JS.find((i)=>i===e);return b(t,`Unknown base model ${e}.`,{hint:{description:"Run toloka base-model list to see the catalog."}}),t},ca=async(e,t,i)=>{if(i.startsWith("mdl."))return e.models.get({projectId:t,modelId:i});let n=[];for await(let r of e.models.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return b(n.length===1,`Model ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka model list and pass the model id (mdl.\u2026)."}}),n[0]},OS=async(e,t,i)=>{if(i.startsWith("mdv."))return e.models.getVersion({modelVersionId:i});let n=i.lastIndexOf("@");b(n>0,`Model Version ${i} was not found. Use mdv.<id> or Model@name.`,{hint:{disabled:!0}}),b(t,"Select a project to resolve Model Version names.",{hint:{description:"Select a project with toloka project add or toloka project switch, or pass the version id (mdv.\u2026) directly."}});let r=await ca(e,t,i.slice(0,n)),o=i.slice(n+1),s=[];for await(let a of e.models.listAllVersions({projectId:t,modelId:r.id,limit:100}))if(a.name===o)s.push(a);return b(s.length===1,`Model Version ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka model versions <model> and pass the version id (mdv.\u2026)."}}),s[0]},wf=async(e,t,i)=>{let n=await e.baseModels.list();ie(i,t.json,n,n.length===0?"No base models found.":ge([["ID","NAME","PROVIDER","UPSTREAM MODEL","REVISION","UPSTREAM SNAPSHOT"],...n.map((r)=>[r.id,r.displayName,r.provider,r.upstreamModel,r.upstreamRevision.slice(0,12),r.upstreamUrl])]))},Ff=async(e,t,i)=>{let n=await e.baseModels.get({id:t.id});ie(i,t.json,n,US(n))},Hf=async(e,t,i)=>{let n=await e.models.listPage({projectId:t.projectId,limit:100,offset:0});ie(i,t.json,n.models,n.models.length===0?"No models found.":ge([["ID","NAME","BASE MODEL"],...n.models.map((r)=>[r.id,r.name,r.baseModelId])]))},vf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId);ie(i,t.json,n,Gf(n))},kf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId),r=[];for await(let o of e.models.listAllVersions({projectId:t.projectId,modelId:n.id,limit:100}))r.push(o);ie(i,t.json,r,r.length===0?"No Model Versions found.":ge([["REVISION","NAME","ID","CREATED AT"],...r.map((o)=>[String(o.revision),o.name,o.id,o.createdAt])]))},Pf=async(e,t,i)=>{let{json:n,...r}=t,o=await e.models.create(r);ie(i,n,o,Gf(o))},Nf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId),r=await e.models.archive({projectId:t.projectId,modelId:n.id});ie(i,t.json,r,`Archived Model ${r.id}.`)},xf=async(e,t,i)=>{let n=await OS(e,t.projectId,t.modelVersionId),r=await e.models.getVersionContent({modelVersionId:n.id}),o=lt.resolve(t.out);await et.mkdir(o,{recursive:!0});let s=await et.realpath(o);for(let a of r.files){let g=lt.resolve(o,a.path),l=lt.relative(o,g);b(l!==""&&l!==".."&&!l.startsWith(`..${lt.sep}`)&&!lt.isAbsolute(l),`Invalid Model Version file path: ${a.path}`,{hint:P});let d=o;for(let u of a.path.split("/").slice(0,-1)){d=lt.resolve(d,u),await et.mkdir(d,{recursive:!0});let p=await et.realpath(d);b(p===s||p.startsWith(`${s}${lt.sep}`),`Invalid Model Version file path: ${a.path}`,{hint:P})}let I=await fetch(a.url,{redirect:"error"});b(I.ok&&I.body,`Failed to download Model Version file ${a.path}.`,{hint:Tt});let C=da.createHash("sha256"),m=0,A=new Ia.Transform({transform(u,p,Z){m+=u.byteLength,C.update(u),Z(null,u)}}),c=`${g}.${da.randomUUID()}.tmp`;try{let u=await et.open(c,oo.constants.O_CREAT|oo.constants.O_EXCL|oo.constants.O_WRONLY|oo.constants.O_NOFOLLOW,384);await Rf.pipeline(Ia.Readable.from(I.body),A,u.createWriteStream()),b(m===a.byteSize,`Downloaded Model Version file ${a.path} has an unexpected size.`,{hint:{description:"Delete the partial download and retry; if it keeps failing, run toloka report."}}),b(C.digest("hex")===a.sha256,`Downloaded Model Version file ${a.path} has an invalid hash.`,{hint:{description:"Delete the partial download and retry; if it keeps failing, run toloka report."}}),await et.rename(c,g)}catch(u){throw await et.rm(c,{force:!0}),u}}i.stdout(`Downloaded Model Version ${r.id} revision ${r.revision} to ${o}`)};var Yf=(e,t)=>{let{context:i,globals:n}=t,r=e.command("base-model").description("inspect the global base model catalog");r.command("list").option("--json","print JSON",!1).description("list base models").action(async(a)=>{let{client:g}=await w(n(),i);await wf(g,{json:a.json},i.io)}),r.command("get").argument("<id>","base model ID").option("--json","print JSON",!1).description("show one base model").action(async(a,g)=>{let{client:l}=await w(n(),i);await Ff(l,{id:Sn(a),json:g.json},i.io)});let o=e.command("model").description("manage project Models and immutable versions");o.command("list").option("--json","print JSON",!1).description("list Models owned by the selected project").action(async(a)=>{let{client:g,projectId:l}=await w(n(),i);S(l),await Hf(g,{projectId:l,json:a.json},i.io)}),o.command("get").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("show one project Model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await vf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("versions").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("list immutable versions of a model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await kf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("create").argument("<name>","new Model name").requiredOption("--base <id>","base model ID").option("--description <text>","Model description").option("--json","print JSON",!1).description("create project Model metadata without a Model Version").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await Pf(l,{projectId:d,name:a,description:g.description,baseModelId:Sn(g.base),json:g.json},i.io)}),o.command("archive").option("--json","print JSON",!1).argument("<name-or-id>","project Model name or ID").description("archive a project Model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await Nf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("version").description("manage one immutable Model Version").command("download").argument("<model-version>","Model Version ID or Model@name").requiredOption("--out <directory>","output directory").description("download and verify Model Version content").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);await xf(l,{projectId:d,modelVersionId:a,out:g.out},i.io)})};var zS=["emacs","vim"],jS=new Set(zS);function DS(e){return jS.has(e)}function Sf(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(DS)))}var so=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",ua=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var YI=(e)=>e.name==="backspace";var SI=(e)=>"1234567890".includes(e.name),XI=(e)=>e.name==="enter"||e.name==="return";class EI extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class TI extends Error{name="CancelPromptError";message="Prompt was canceled"}class Ca extends Error{name="ExitPromptError"}class JI extends Error{name="HookError"}class ao extends Error{name="ValidationError"}var Jf=require("async_hooks");var ma=require("async_hooks");var Xf=new ma.AsyncLocalStorage;function _S(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Ef(e,t){let i=_S(e);return Xf.run(i,()=>{function n(r){i.handleChange=()=>{i.index=0,r()},i.handleChange()}return t(n)})}function Si(){let e=Xf.getStore();if(!e)throw new JI("[Inquirer] Hook functions can only be called from within a prompt");return e}function UI(){return Si().rl}function OI(e){let t=(...i)=>{let n=Si(),r=!1,o=n.handleChange;n.handleChange=()=>{r=!0};let s=e(...i);if(r)o();return n.handleChange=o,s};return ma.AsyncResource.bind(t)}function Xn(e){let t=Si(),{index:i}=t,n={get(){return t.hooks[i]},set(o){t.hooks[i]=o},initialized:i in t.hooks},r=e(n);return t.index++,r}function Tf(){Si().handleChange()}var Xi={queue(e){let t=Si(),{index:i}=t;t.hooksEffect.push(()=>{t.hooksCleanup[i]?.();let n=e(UI());if(n!=null&&typeof n!=="function")throw new ao("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[i]=n})},run(){let e=Si();OI(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Si();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function QS(e){return typeof e==="function"}function Bt(e){return Xn((t)=>{let i=Jf.AsyncResource.bind(function(o){if(t.get()!==o)t.set(o),Tf()});if(t.initialized)return[t.get(),i];let n=QS(e)?e():e;return t.set(n),[n,i]})}function Ei(e,t){Xn((i)=>{let n=i.get();if(!Array.isArray(n)||t.some((o,s)=>!Object.is(o,n[s])))Xi.queue(e);i.set(t)})}var it=require("util");var tt=Pe(require("process"));function KS(){if(!tt.default.platform.startsWith("win"))return tt.default.env.TERM!=="linux";return Boolean(tt.default.env.CI)||Boolean(tt.default.env.WT_SESSION)||Boolean(tt.default.env.TERMINUS_SUBLIME)||tt.default.env.ConEmuTask==="{cmd::Cmder}"||tt.default.env.TERM_PROGRAM==="Terminus-Sublime"||tt.default.env.TERM_PROGRAM==="vscode"||tt.default.env.TERM==="xterm-256color"||tt.default.env.TERM==="alacritty"||tt.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Uf={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Of={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},LS={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},MS={...Uf,...Of},$S={...Uf,...LS},qS=KS(),eX=qS?MS:$S,En=eX,D8=Object.entries(Of);var tX={prefix:{idle:it.styleText("blue","?"),done:it.styleText("green",En.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>it.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>it.styleText("cyan",e),message:(e)=>it.styleText("bold",e),error:(e)=>it.styleText("red",`> ${e}`),defaultAnswer:(e)=>it.styleText("dim",`(${e})`),help:(e)=>it.styleText("dim",e),highlight:(e)=>it.styleText("cyan",e),key:(e)=>it.styleText("cyan",it.styleText("bold",`<${e}>`))}};function zf(){return{...tX,keybindings:Sf()}}function jf(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Df(...e){let t={};for(let i of e)for(let[n,r]of Object.entries(i)){let o=t[n];t[n]=jf(o)&&jf(r)?Df(o,r):r}return t}function go(...e){let t=[zf(),...e.filter((i)=>i!=null)];return Df(...t)}function zI({status:e="idle",theme:t}){let[i,n]=Bt(!1),[r,o]=Bt(0),{prefix:s,spinner:a}=go(t);if(Ei(()=>{if(e==="loading"){let l,d=-1,I=setTimeout(()=>{n(!0),l=setInterval(()=>{d=d+1,o(d%a.frames.length)},a.interval)},300);return()=>{clearTimeout(I),clearInterval(l)}}else n(!1)},[e]),i)return a.frames[r];return typeof s==="string"?s:s[e==="loading"?"idle":e]??s.idle}function lo(e,t){return Xn((i)=>{let n=i.get();if(!n||n.dependencies.length!==t.length||n.dependencies.some((r,o)=>r!==t[o])){let r=e();return i.set({value:r,dependencies:t}),r}return n.value})}function Ti(e){return Bt({current:e})[0]}function jI(e){let t=Ti(e);t.current=e,Ei((i)=>{let n=!1,r=OI((o,s)=>{if(n)return;t.current(s,i)});return i.input.on("keypress",r),()=>{n=!0,i.input.removeListener("keypress",r)}},[])}var dW=Pe(Qf(),1);var Kf=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let i=0;e.lastIndex=0;while(e.test(t))i+=1;return t.length-i}})(),Lf=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Mf=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var rX=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,oX=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,$f=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,sX=/\t{1,1000}/y,qf=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,aX=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,gX=/\p{M}+/gu,lX={limit:1/0,ellipsis:""},eW=(e,t={},i={})=>{let n=t.limit??1/0,r=t.ellipsis??"",o=t?.ellipsisWidth??(r?eW(r,lX,i).width:0),s=0,a=i.controlWidth??0,g=i.tabWidth??8,l=i.emojiWidth??2,d=2,I=i.regularWidth??1,C=i.wideWidth??2,m=[[aX,I],[rX,0],[oX,a],[sX,g],[qf,l],[$f,C]],A=0,c=0,u=e.length,p=0,Z=!1,h=u,W=Math.max(0,n-o),y=0,V=0,H=0,Y=0;e:while(!0){if(V>y||c>=u&&c>A){let v=e.slice(y,V)||e.slice(A,c);p=0;for(let K of v.replaceAll(gX,"")){let re=K.codePointAt(0)||0;if(Lf(re))Y=2;else if(Mf(re))Y=C;else Y=I;if(H+Y>W)h=Math.min(h,Math.max(y,A)+p);if(H+Y>n){Z=!0;break e}p+=K.length,H+=Y}y=V=0}if(c>=u)break e;for(let v=0,K=m.length;v<K;v++){let[re,le]=m[v];if(re.lastIndex=c,re.test(e)){if(p=re===$f?Kf(e.slice(c,re.lastIndex)):re===qf?1:re.lastIndex-c,Y=p*le,H+Y>W)h=Math.min(h,c+Math.floor((W-H)/le));if(H+Y>n){Z=!0;break e}H+=Y,y=A,V=c,c=A=re.lastIndex;continue e}}c+=1}return{width:Z?W:H,index:Z?h:u,truncated:Z,ellipsed:Z&&n>=o}},tW=eW;var dX={limit:1/0,ellipsis:"",ellipsisWidth:0},IX=(e,t={})=>tW(e,dX,t).width,Xt=IX;var pa="\x1B",sW="\x9B",cX=39,_I="\x07",aW="[",uX="]",gW="m",QI=`${uX}8;;`,iW=new RegExp(`(?:\\${aW}(?<code>\\d+)m|\\${QI}(?<uri>.*)${_I})`,"y"),nW=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},rW=(e)=>`${pa}${aW}${e}${gW}`,oW=(e)=>`${pa}${QI}${e}${_I}`,DI=(e,t,i)=>{let n=t[Symbol.iterator](),r=!1,o=!1,s=e.at(-1),a=s===void 0?0:Xt(s),g=n.next(),l=n.next(),d=0;while(!g.done){let I=g.value,C=Xt(I);if(a+C<=i)e[e.length-1]+=I;else e.push(I),a=0;if(I===pa||I===sW)r=!0,o=t.startsWith(QI,d+1);if(r){if(o){if(I===_I)r=!1,o=!1}else if(I===gW)r=!1}else if(a+=C,a===i&&!l.done)e.push(""),a=0;g=l,l=n.next(),d+=I.length}if(s=e.at(-1),!a&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},CX=(e)=>{let t=e.split(" "),i=t.length;while(i){if(Xt(t[i-1]))break;i--}if(i===t.length)return e;return t.slice(0,i).join(" ")+t.slice(i).join("")},mX=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let n="",r,o,s=e.split(" "),a=[""],g=0;for(let I=0;I<s.length;I++){let C=s[I];if(i.trim!==!1){let A=a.at(-1)??"",c=A.trimStart();if(A.length!==c.length)a[a.length-1]=c,g=Xt(c)}if(I!==0){if(g>=t&&(i.wordWrap===!1||i.trim===!1))a.push(""),g=0;if(g||i.trim===!1)a[a.length-1]+=" ",g++}let m=Xt(C);if(i.hard&&m>t){let A=t-g,c=1+Math.floor((m-A-1)/t);if(Math.floor((m-1)/t)<c)a.push("");DI(a,C,t),g=Xt(a.at(-1)??"");continue}if(g+m>t&&g&&m){if(i.wordWrap===!1&&g<t){DI(a,C,t),g=Xt(a.at(-1)??"");continue}a.push(""),g=0}if(g+m>t&&i.wordWrap===!1){DI(a,C,t),g=Xt(a.at(-1)??"");continue}a[a.length-1]+=C,g+=m}if(i.trim!==!1)a=a.map((I)=>CX(I));let l=a.join(`
|
|
326
|
-
`),d=!1;for(let I=0;I<l.length;I++){let C=l[I];if(n+=C,!d){if(d=C>="\uD800"&&C<="\uDBFF",d)continue}else d=!1;if(C===pa||C===sW){iW.lastIndex=I+1;let A=iW.exec(l)?.groups;if(A?.code!==void 0){let c=Number.parseFloat(A.code);r=c===
|
|
325
|
+
`)}}var Bf=(e,t)=>{let{context:i,globals:n}=t;e.command("delivery-order").description("list Sunday delivery orders for project create").command("list").description("list active Sunday delivery orders this key can attach").action(async()=>{let{client:o}=await w(n(),i),s=await Vf({client:o});i.io.stdout(s.output)})};var da=require("crypto"),oo=require("fs"),et=require("fs/promises"),lt=require("path"),Ia=require("stream"),Rf=require("stream/promises");var US=["qwen3-4b","qwen3-8b","qwen3-32b","qwen3-235b"],OS=(e)=>ge([["ID",e.id],["Name",e.displayName],["Provider",e.provider],["Upstream model",e.upstreamModel],["Upstream revision",e.upstreamRevision],["Upstream snapshot",e.upstreamUrl]]),Gf=(e)=>ge([["ID",e.id],["Project",e.projectId],["Name",e.name],["Base model",e.baseModelId],["Description",e.description??"-"],["Archived at",e.archivedAt??"-"],["Created at",e.createdAt],["Updated at",e.updatedAt]]),Sn=(e)=>{let t=US.find((i)=>i===e);return b(t,`Unknown base model ${e}.`,{hint:{description:"Run toloka base-model list to see the catalog."}}),t},ca=async(e,t,i)=>{if(i.startsWith("mdl."))return e.models.get({projectId:t,modelId:i});let n=[];for await(let r of e.models.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return b(n.length===1,`Model ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka model list and pass the model id (mdl.\u2026)."}}),n[0]},zS=async(e,t,i)=>{if(i.startsWith("mdv."))return e.models.getVersion({modelVersionId:i});let n=i.lastIndexOf("@");b(n>0,`Model Version ${i} was not found. Use mdv.<id> or Model@name.`,{hint:{disabled:!0}}),b(t,"Select a project to resolve Model Version names.",{hint:{description:"Select a project with toloka project add or toloka project switch, or pass the version id (mdv.\u2026) directly."}});let r=await ca(e,t,i.slice(0,n)),o=i.slice(n+1),s=[];for await(let a of e.models.listAllVersions({projectId:t,modelId:r.id,limit:100}))if(a.name===o)s.push(a);return b(s.length===1,`Model Version ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka model versions <model> and pass the version id (mdv.\u2026)."}}),s[0]},wf=async(e,t,i)=>{let n=await e.baseModels.list();ie(i,t.json,n,n.length===0?"No base models found.":ge([["ID","NAME","PROVIDER","UPSTREAM MODEL","REVISION","UPSTREAM SNAPSHOT"],...n.map((r)=>[r.id,r.displayName,r.provider,r.upstreamModel,r.upstreamRevision.slice(0,12),r.upstreamUrl])]))},Ff=async(e,t,i)=>{let n=await e.baseModels.get({id:t.id});ie(i,t.json,n,OS(n))},Hf=async(e,t,i)=>{let n=await e.models.listPage({projectId:t.projectId,limit:100,offset:0});ie(i,t.json,n.models,n.models.length===0?"No models found.":ge([["ID","NAME","BASE MODEL"],...n.models.map((r)=>[r.id,r.name,r.baseModelId])]))},vf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId);ie(i,t.json,n,Gf(n))},kf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId),r=[];for await(let o of e.models.listAllVersions({projectId:t.projectId,modelId:n.id,limit:100}))r.push(o);ie(i,t.json,r,r.length===0?"No Model Versions found.":ge([["REVISION","NAME","ID","CREATED AT"],...r.map((o)=>[String(o.revision),o.name,o.id,o.createdAt])]))},Pf=async(e,t,i)=>{let{json:n,...r}=t,o=await e.models.create(r);ie(i,n,o,Gf(o))},Nf=async(e,t,i)=>{let n=await ca(e,t.projectId,t.nameOrId),r=await e.models.archive({projectId:t.projectId,modelId:n.id});ie(i,t.json,r,`Archived Model ${r.id}.`)},xf=async(e,t,i)=>{let n=await zS(e,t.projectId,t.modelVersionId),r=await e.models.getVersionContent({modelVersionId:n.id}),o=lt.resolve(t.out);await et.mkdir(o,{recursive:!0});let s=await et.realpath(o);for(let a of r.files){let g=lt.resolve(o,a.path),l=lt.relative(o,g);b(l!==""&&l!==".."&&!l.startsWith(`..${lt.sep}`)&&!lt.isAbsolute(l),`Invalid Model Version file path: ${a.path}`,{hint:P});let d=o;for(let u of a.path.split("/").slice(0,-1)){d=lt.resolve(d,u),await et.mkdir(d,{recursive:!0});let p=await et.realpath(d);b(p===s||p.startsWith(`${s}${lt.sep}`),`Invalid Model Version file path: ${a.path}`,{hint:P})}let I=await fetch(a.url,{redirect:"error"});b(I.ok&&I.body,`Failed to download Model Version file ${a.path}.`,{hint:Tt});let C=da.createHash("sha256"),m=0,A=new Ia.Transform({transform(u,p,Z){m+=u.byteLength,C.update(u),Z(null,u)}}),c=`${g}.${da.randomUUID()}.tmp`;try{let u=await et.open(c,oo.constants.O_CREAT|oo.constants.O_EXCL|oo.constants.O_WRONLY|oo.constants.O_NOFOLLOW,384);await Rf.pipeline(Ia.Readable.from(I.body),A,u.createWriteStream()),b(m===a.byteSize,`Downloaded Model Version file ${a.path} has an unexpected size.`,{hint:{description:"Delete the partial download and retry; if it keeps failing, run toloka report."}}),b(C.digest("hex")===a.sha256,`Downloaded Model Version file ${a.path} has an invalid hash.`,{hint:{description:"Delete the partial download and retry; if it keeps failing, run toloka report."}}),await et.rename(c,g)}catch(u){throw await et.rm(c,{force:!0}),u}}i.stdout(`Downloaded Model Version ${r.id} revision ${r.revision} to ${o}`)};var Yf=(e,t)=>{let{context:i,globals:n}=t,r=e.command("base-model").description("inspect the global base model catalog");r.command("list").option("--json","print JSON",!1).description("list base models").action(async(a)=>{let{client:g}=await w(n(),i);await wf(g,{json:a.json},i.io)}),r.command("get").argument("<id>","base model ID").option("--json","print JSON",!1).description("show one base model").action(async(a,g)=>{let{client:l}=await w(n(),i);await Ff(l,{id:Sn(a),json:g.json},i.io)});let o=e.command("model").description("manage project Models and immutable versions");o.command("list").option("--json","print JSON",!1).description("list Models owned by the selected project").action(async(a)=>{let{client:g,projectId:l}=await w(n(),i);S(l),await Hf(g,{projectId:l,json:a.json},i.io)}),o.command("get").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("show one project Model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await vf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("versions").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("list immutable versions of a model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await kf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("create").argument("<name>","new Model name").requiredOption("--base <id>","base model ID").option("--description <text>","Model description").option("--json","print JSON",!1).description("create project Model metadata without a Model Version").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await Pf(l,{projectId:d,name:a,description:g.description,baseModelId:Sn(g.base),json:g.json},i.io)}),o.command("archive").option("--json","print JSON",!1).argument("<name-or-id>","project Model name or ID").description("archive a project Model").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);S(d),await Nf(l,{projectId:d,nameOrId:a,json:g.json},i.io)}),o.command("version").description("manage one immutable Model Version").command("download").argument("<model-version>","Model Version ID or Model@name").requiredOption("--out <directory>","output directory").description("download and verify Model Version content").action(async(a,g)=>{let{client:l,projectId:d}=await w(n(),i);await xf(l,{projectId:d,modelVersionId:a,out:g.out},i.io)})};var jS=["emacs","vim"],DS=new Set(jS);function _S(e){return DS.has(e)}function Sf(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(_S)))}var so=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",ua=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var YI=(e)=>e.name==="backspace";var SI=(e)=>"1234567890".includes(e.name),XI=(e)=>e.name==="enter"||e.name==="return";class EI extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class TI extends Error{name="CancelPromptError";message="Prompt was canceled"}class Ca extends Error{name="ExitPromptError"}class JI extends Error{name="HookError"}class ao extends Error{name="ValidationError"}var Jf=require("async_hooks");var ma=require("async_hooks");var Xf=new ma.AsyncLocalStorage;function QS(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Ef(e,t){let i=QS(e);return Xf.run(i,()=>{function n(r){i.handleChange=()=>{i.index=0,r()},i.handleChange()}return t(n)})}function Si(){let e=Xf.getStore();if(!e)throw new JI("[Inquirer] Hook functions can only be called from within a prompt");return e}function UI(){return Si().rl}function OI(e){let t=(...i)=>{let n=Si(),r=!1,o=n.handleChange;n.handleChange=()=>{r=!0};let s=e(...i);if(r)o();return n.handleChange=o,s};return ma.AsyncResource.bind(t)}function Xn(e){let t=Si(),{index:i}=t,n={get(){return t.hooks[i]},set(o){t.hooks[i]=o},initialized:i in t.hooks},r=e(n);return t.index++,r}function Tf(){Si().handleChange()}var Xi={queue(e){let t=Si(),{index:i}=t;t.hooksEffect.push(()=>{t.hooksCleanup[i]?.();let n=e(UI());if(n!=null&&typeof n!=="function")throw new ao("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[i]=n})},run(){let e=Si();OI(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Si();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function KS(e){return typeof e==="function"}function Bt(e){return Xn((t)=>{let i=Jf.AsyncResource.bind(function(o){if(t.get()!==o)t.set(o),Tf()});if(t.initialized)return[t.get(),i];let n=KS(e)?e():e;return t.set(n),[n,i]})}function Ei(e,t){Xn((i)=>{let n=i.get();if(!Array.isArray(n)||t.some((o,s)=>!Object.is(o,n[s])))Xi.queue(e);i.set(t)})}var it=require("util");var tt=Pe(require("process"));function LS(){if(!tt.default.platform.startsWith("win"))return tt.default.env.TERM!=="linux";return Boolean(tt.default.env.CI)||Boolean(tt.default.env.WT_SESSION)||Boolean(tt.default.env.TERMINUS_SUBLIME)||tt.default.env.ConEmuTask==="{cmd::Cmder}"||tt.default.env.TERM_PROGRAM==="Terminus-Sublime"||tt.default.env.TERM_PROGRAM==="vscode"||tt.default.env.TERM==="xterm-256color"||tt.default.env.TERM==="alacritty"||tt.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Uf={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Of={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},MS={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},$S={...Uf,...Of},qS={...Uf,...MS},eX=LS(),tX=eX?$S:qS,En=tX,_8=Object.entries(Of);var iX={prefix:{idle:it.styleText("blue","?"),done:it.styleText("green",En.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>it.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>it.styleText("cyan",e),message:(e)=>it.styleText("bold",e),error:(e)=>it.styleText("red",`> ${e}`),defaultAnswer:(e)=>it.styleText("dim",`(${e})`),help:(e)=>it.styleText("dim",e),highlight:(e)=>it.styleText("cyan",e),key:(e)=>it.styleText("cyan",it.styleText("bold",`<${e}>`))}};function zf(){return{...iX,keybindings:Sf()}}function jf(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Df(...e){let t={};for(let i of e)for(let[n,r]of Object.entries(i)){let o=t[n];t[n]=jf(o)&&jf(r)?Df(o,r):r}return t}function go(...e){let t=[zf(),...e.filter((i)=>i!=null)];return Df(...t)}function zI({status:e="idle",theme:t}){let[i,n]=Bt(!1),[r,o]=Bt(0),{prefix:s,spinner:a}=go(t);if(Ei(()=>{if(e==="loading"){let l,d=-1,I=setTimeout(()=>{n(!0),l=setInterval(()=>{d=d+1,o(d%a.frames.length)},a.interval)},300);return()=>{clearTimeout(I),clearInterval(l)}}else n(!1)},[e]),i)return a.frames[r];return typeof s==="string"?s:s[e==="loading"?"idle":e]??s.idle}function lo(e,t){return Xn((i)=>{let n=i.get();if(!n||n.dependencies.length!==t.length||n.dependencies.some((r,o)=>r!==t[o])){let r=e();return i.set({value:r,dependencies:t}),r}return n.value})}function Ti(e){return Bt({current:e})[0]}function jI(e){let t=Ti(e);t.current=e,Ei((i)=>{let n=!1,r=OI((o,s)=>{if(n)return;t.current(s,i)});return i.input.on("keypress",r),()=>{n=!0,i.input.removeListener("keypress",r)}},[])}var dW=Pe(Qf(),1);var Kf=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let i=0;e.lastIndex=0;while(e.test(t))i+=1;return t.length-i}})(),Lf=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Mf=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var oX=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,sX=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,$f=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,aX=/\t{1,1000}/y,qf=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,gX=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,lX=/\p{M}+/gu,dX={limit:1/0,ellipsis:""},eW=(e,t={},i={})=>{let n=t.limit??1/0,r=t.ellipsis??"",o=t?.ellipsisWidth??(r?eW(r,dX,i).width:0),s=0,a=i.controlWidth??0,g=i.tabWidth??8,l=i.emojiWidth??2,d=2,I=i.regularWidth??1,C=i.wideWidth??2,m=[[gX,I],[oX,0],[sX,a],[aX,g],[qf,l],[$f,C]],A=0,c=0,u=e.length,p=0,Z=!1,h=u,W=Math.max(0,n-o),y=0,V=0,H=0,Y=0;e:while(!0){if(V>y||c>=u&&c>A){let v=e.slice(y,V)||e.slice(A,c);p=0;for(let K of v.replaceAll(lX,"")){let re=K.codePointAt(0)||0;if(Lf(re))Y=2;else if(Mf(re))Y=C;else Y=I;if(H+Y>W)h=Math.min(h,Math.max(y,A)+p);if(H+Y>n){Z=!0;break e}p+=K.length,H+=Y}y=V=0}if(c>=u)break e;for(let v=0,K=m.length;v<K;v++){let[re,le]=m[v];if(re.lastIndex=c,re.test(e)){if(p=re===$f?Kf(e.slice(c,re.lastIndex)):re===qf?1:re.lastIndex-c,Y=p*le,H+Y>W)h=Math.min(h,c+Math.floor((W-H)/le));if(H+Y>n){Z=!0;break e}H+=Y,y=A,V=c,c=A=re.lastIndex;continue e}}c+=1}return{width:Z?W:H,index:Z?h:u,truncated:Z,ellipsed:Z&&n>=o}},tW=eW;var IX={limit:1/0,ellipsis:"",ellipsisWidth:0},cX=(e,t={})=>tW(e,IX,t).width,Xt=cX;var pa="\x1B",sW="\x9B",uX=39,_I="\x07",aW="[",CX="]",gW="m",QI=`${CX}8;;`,iW=new RegExp(`(?:\\${aW}(?<code>\\d+)m|\\${QI}(?<uri>.*)${_I})`,"y"),nW=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},rW=(e)=>`${pa}${aW}${e}${gW}`,oW=(e)=>`${pa}${QI}${e}${_I}`,DI=(e,t,i)=>{let n=t[Symbol.iterator](),r=!1,o=!1,s=e.at(-1),a=s===void 0?0:Xt(s),g=n.next(),l=n.next(),d=0;while(!g.done){let I=g.value,C=Xt(I);if(a+C<=i)e[e.length-1]+=I;else e.push(I),a=0;if(I===pa||I===sW)r=!0,o=t.startsWith(QI,d+1);if(r){if(o){if(I===_I)r=!1,o=!1}else if(I===gW)r=!1}else if(a+=C,a===i&&!l.done)e.push(""),a=0;g=l,l=n.next(),d+=I.length}if(s=e.at(-1),!a&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},mX=(e)=>{let t=e.split(" "),i=t.length;while(i){if(Xt(t[i-1]))break;i--}if(i===t.length)return e;return t.slice(0,i).join(" ")+t.slice(i).join("")},pX=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let n="",r,o,s=e.split(" "),a=[""],g=0;for(let I=0;I<s.length;I++){let C=s[I];if(i.trim!==!1){let A=a.at(-1)??"",c=A.trimStart();if(A.length!==c.length)a[a.length-1]=c,g=Xt(c)}if(I!==0){if(g>=t&&(i.wordWrap===!1||i.trim===!1))a.push(""),g=0;if(g||i.trim===!1)a[a.length-1]+=" ",g++}let m=Xt(C);if(i.hard&&m>t){let A=t-g,c=1+Math.floor((m-A-1)/t);if(Math.floor((m-1)/t)<c)a.push("");DI(a,C,t),g=Xt(a.at(-1)??"");continue}if(g+m>t&&g&&m){if(i.wordWrap===!1&&g<t){DI(a,C,t),g=Xt(a.at(-1)??"");continue}a.push(""),g=0}if(g+m>t&&i.wordWrap===!1){DI(a,C,t),g=Xt(a.at(-1)??"");continue}a[a.length-1]+=C,g+=m}if(i.trim!==!1)a=a.map((I)=>mX(I));let l=a.join(`
|
|
326
|
+
`),d=!1;for(let I=0;I<l.length;I++){let C=l[I];if(n+=C,!d){if(d=C>="\uD800"&&C<="\uDBFF",d)continue}else d=!1;if(C===pa||C===sW){iW.lastIndex=I+1;let A=iW.exec(l)?.groups;if(A?.code!==void 0){let c=Number.parseFloat(A.code);r=c===uX?void 0:c}else if(A?.uri!==void 0)o=A.uri.length===0?void 0:A.uri}if(l[I+1]===`
|
|
327
327
|
`){if(o)n+=oW("");let m=r?nW(r):void 0;if(r&&m)n+=rW(m)}else if(C===`
|
|
328
|
-
`){if(r&&nW(r))n+=rW(r);if(o)n+=oW(o)}}return n},
|
|
328
|
+
`){if(r&&nW(r))n+=rW(r);if(o)n+=oW(o)}}return n},AX=/\r?\n/;function lW(e,t,i){return String(e).normalize().split(AX).map((n)=>pX(n,t,i)).join(`
|
|
329
329
|
`)}function Io(e,t){return e.split(`
|
|
330
330
|
`).flatMap((i)=>lW(i,t,{trim:!1,wordWrap:!1}).split(`
|
|
331
331
|
`).map((n)=>n.trimEnd())).join(`
|
|
332
|
-
`)}function Aa(){return dW.default({defaultWidth:80,output:UI().output})}function
|
|
333
|
-
`)}),g=a.reduce((p,Z)=>p+Z.length,0),l=(p)=>a[p]??[],d=
|
|
334
|
-
`)}var yW=Pe(require("readline")),VW=require("async_hooks"),BW=Pe(uW(),1);var Ji=[];Ji.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")Ji.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Ji.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var ba=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",LI=Symbol.for("signal-exit emitter"),MI=globalThis,
|
|
335
|
-
`).length,
|
|
336
|
-
`).pop()??"";class Za{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let i=
|
|
332
|
+
`)}function Aa(){return dW.default({defaultWidth:80,output:UI().output})}function bX({active:e,renderedItems:t,pageSize:i,loop:n}){let r=Ti({lastPointer:e,lastActive:void 0}),{lastPointer:o,lastActive:s}=r.current,a=Math.floor(i/2),g=t.reduce((I,C)=>I+C.length,0),l=t.slice(0,e).reduce((I,C)=>I+C.length,0),d=l;if(g>i)if(n){if(d=o,s!=null&&s<e&&e-s<i)d=Math.min(a,Math.abs(e-s)===1?Math.min(o+(t[s]?.length??0),Math.max(l,o)):o+e-s)}else{let I=t.slice(e).reduce((C,m)=>C+m.length,0);d=I<i-a?i-I:Math.min(l,a)}return r.current.lastPointer=d,r.current.lastActive=e,d}function KI({items:e,active:t,renderItem:i,pageSize:n,loop:r=!0}){let o=Aa(),s=(p)=>(p%e.length+e.length)%e.length,a=e.map((p,Z)=>{if(p==null)return[];return Io(i({item:p,index:Z,isActive:Z===t}),o).split(`
|
|
333
|
+
`)}),g=a.reduce((p,Z)=>p+Z.length,0),l=(p)=>a[p]??[],d=bX({active:t,renderedItems:a,pageSize:n,loop:r}),I=l(t).slice(0,n),C=d+I.length<=n?d:n-I.length,m=Array.from({length:n});m.splice(C,I.length,...I);let A=new Set([t]),c=C+I.length,u=s(t+1);while(c<n&&!A.has(u)&&(r&&g>n?u!==t:u>t)){let Z=l(u).slice(0,n-c);m.splice(c,Z.length,...Z),A.add(u),c+=Z.length,u=s(u+1)}c=C-1,u=s(t-1);while(c>=0&&!A.has(u)&&(r&&g>n?u!==t:u<t)){let p=l(u),Z=p.slice(Math.max(0,p.length-c-1));m.splice(c-Z.length+1,Z.length,...Z),A.add(u),c-=Z.length,u=s(u-1)}return m.filter((p)=>typeof p==="string").join(`
|
|
334
|
+
`)}var yW=Pe(require("readline")),VW=require("async_hooks"),BW=Pe(uW(),1);var Ji=[];Ji.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")Ji.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Ji.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var ba=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",LI=Symbol.for("signal-exit emitter"),MI=globalThis,hX=Object.defineProperty.bind(Object);class CW{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(MI[LI])return MI[LI];hX(MI,LI,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let i=this.listeners[e],n=i.indexOf(t);if(n===-1)return;if(n===0&&i.length===1)i.length=0;else i.splice(n,1)}emit(e,t,i){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,i)===!0||n;if(e==="exit")n=this.emit("afterExit",t,i)||n;return n}}class qI{}var fX=(e)=>({onExit(t,i){return e.onExit(t,i)},load(){return e.load()},unload(){return e.unload()}});class mW extends qI{onExit(){return()=>{}}load(){}unload(){}}class pW extends qI{#i=$I.platform==="win32"?"SIGINT":"SIGHUP";#t=new CW;#e;#o;#s;#r={};#n=!1;constructor(e){super();this.#e=e,this.#r={};for(let t of Ji)this.#r[t]=()=>{let i=this.#e.listeners(t),{count:n}=this.#t,r=e;if(typeof r.__signal_exit_emitter__==="object"&&typeof r.__signal_exit_emitter__.count==="number")n+=r.__signal_exit_emitter__.count;if(i.length===n){this.unload();let o=this.#t.emit("exit",null,t),s=t==="SIGHUP"?this.#i:t;if(!o)e.kill(e.pid,s)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,t){if(!ba(this.#e))return()=>{};if(this.#n===!1)this.load();let i=t?.alwaysLast?"afterExit":"exit";return this.#t.on(i,e),()=>{if(this.#t.removeListener(i,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#n)return;this.#n=!0,this.#t.count+=1;for(let e of Ji)try{let t=this.#r[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#g(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#n)return;this.#n=!1,Ji.forEach((e)=>{let t=this.#r[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(i){}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#s,this.#t.count-=1}#a(e){if(!ba(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)}#g(e,...t){let i=this.#o;if(e==="exit"&&ba(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let n=i.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),n}else return i.call(this.#e,e,...t)}}var $I=globalThis.process,{onExit:AW,load:F_,unload:H_}=fX(ba($I)?new pW($I):new mW);var WW=require("util");var ec="\x1B[G",ZW="\x1B[?25l",hW="\x1B[?25h",tc=(e=1)=>e>0?`\x1B[${e}A`:"",ic=(e=1)=>e>0?`\x1B[${e}B`:"",nc=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},bW="\x1B[2K",rc=(e)=>e>0?(bW+tc(1)).repeat(e-1)+bW+ec:"";var fW=(e)=>e.split(`
|
|
335
|
+
`).length,WX=(e)=>e.split(`
|
|
336
|
+
`).pop()??"";class Za{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let i=WX(e),n=WW.stripVTControlCharacters(i),r=n;if(this.rl.line.length>0)r=r.slice(0,-this.rl.line.length);this.rl.setPrompt(r),this.cursorPos=this.rl.getCursorPos();let o=Aa();if(e=Io(e,o),t=Io(t,o),n.length%o===0)e+=`
|
|
337
337
|
`;let s=e+(t?`
|
|
338
338
|
`+t:""),g=Math.floor(n.length/o)-this.cursorPos.rows+(t?fW(t):0);if(g>0)s+=tc(g);s+=nc(this.cursorPos.cols),this.write(ic(this.extraLinesUnderPrompt)+rc(this.height)+s),this.extraLinesUnderPrompt=g,this.height=fW(s)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write(nc(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=ic(this.extraLinesUnderPrompt);t+=e?rc(this.height):`
|
|
339
|
-
`,t+=ec,t+=hW,this.write(t),this.rl.close()}}class oc extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}}var RW=Pe(require("path")),
|
|
340
|
-
at ${v}`)}let[H,Y]=typeof V==="string"?[V]:V;d.render(H,Y),Xi.run()}catch(V){m(V)}if(y=!0,W!==null){let{value:V}=W;W=null,C(V)}})};if("readableFlowing"in o)
|
|
341
|
-
`).trimEnd()}${ZW}`});var
|
|
342
|
-
`)}}var
|
|
339
|
+
`,t+=ec,t+=hW,this.write(t),this.rl.close()}}class oc extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}}var RW=Pe(require("path")),yX=globalThis.setImmediate;function VX(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(i,n)=>{let r=n.slice(1);return t=r,r},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function sc(e){let t=VX();return(n,r={})=>{let{input:o=process.stdin,signal:s}=r,a=new Set,g=new BW.default;g.pipe(r.output??process.stdout);let l=yW.createInterface({terminal:!0,input:o,output:g});g.mute();let d=new Za(l),{promise:I,resolve:C,reject:m}=oc.withResolver(),A=()=>m(new TI);if(s){let u=()=>m(new EI({cause:s.reason}));if(s.aborted)return u(),Object.assign(I,{cancel:A});s.addEventListener("abort",u),a.add(()=>s.removeEventListener("abort",u))}a.add(AW((u,p)=>{m(new Ca(`User force closed the prompt with ${u} ${p}`))}));let c=()=>m(new Ca("User force closed the prompt with SIGINT"));return l.on("SIGINT",c),a.add(()=>l.removeListener("SIGINT",c)),Ef(l,(u)=>{let p=VW.AsyncResource.bind(()=>Xi.clearAll());l.on("close",p),a.add(()=>l.removeListener("close",p));let Z=()=>{let h=()=>d.checkCursorPos();l.input.on("keypress",h),a.add(()=>l.input.removeListener("keypress",h));let W=null;u(()=>{let y=!1;try{let V=e(n,(v)=>{if(y)C(v);else W={value:v}});if(V===void 0){let v=t[1]?.getFileName();if(v&&!v.startsWith("file://"))v=RW.default.resolve(v);throw Error(`Prompt functions must return a string.
|
|
340
|
+
at ${v}`)}let[H,Y]=typeof V==="string"?[V]:V;d.render(H,Y),Xi.run()}catch(V){m(V)}if(y=!0,W!==null){let{value:V}=W;W=null,C(V)}})};if("readableFlowing"in o)yX(Z);else Z();return Object.assign(I.then((h)=>(Xi.clearAll(),h),(h)=>{throw Xi.clearAll(),h}).finally(()=>{a.forEach((h)=>h()),d.done({clearContent:Boolean(r.clearPromptOnDone)}),g.end()}).then(()=>I),{cancel:A})})}}var GW=require("util");class Rt{separator=GW.styleText("dim",Array.from({length:15}).join(En.line));type="separator";constructor(e){if(e)this.separator=e}static isSeparator(e){return Boolean(e&&typeof e==="object"&&"type"in e&&e.type==="separator")}}var Tn=require("util");var BX={icon:{cursor:En.pointer},style:{disabled:(e)=>Tn.styleText("dim",e),description:(e)=>Tn.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,i])=>`${Tn.styleText("bold",t)} ${Tn.styleText("dim",i)}`).join(Tn.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function ac(e){return!Rt.isSeparator(e)&&!e.disabled}function gc(e){return!Rt.isSeparator(e)}function RX(e){return e.map((t)=>{if(Rt.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let r=String(t);return{value:t,name:r,short:r,disabled:!1}}let i=t.name??String(t.value),n={value:t.value,name:i,short:t.short??i,disabled:t.disabled??!1};if(t.description)n.description=t.description;return n})}var ha=sc((e,t)=>{let{loop:i=!0,pageSize:n=7}=e,r=go(BX,e.theme),{keybindings:o}=r,[s,a]=Bt("idle"),g=zI({status:s,theme:r}),l=Ti(),d=!o.includes("vim"),I=lo(()=>RX(e.choices),[e.choices]),C=lo(()=>{let v=I.findIndex(gc),K=I.findLastIndex(gc);if(v===-1)throw new ao("[select prompt] No selectable choices. All choices are disabled.");return{first:v,last:K}},[I]),m=lo(()=>{if(!("default"in e))return-1;return I.findIndex((v)=>ac(v)&&v.value===e.default)},[e.default,I]),[A,c]=Bt(m===-1?C.first:m),u=I[A];if(u==null||Rt.isSeparator(u))throw Error("Active index does not point to a choice");let[p,Z]=Bt();jI((v,K)=>{if(clearTimeout(l.current),p)Z(void 0);if(XI(v))if(u.disabled)Z(r.i18n.disabledError);else a("done"),t(u.value);else if(so(v,o)||ua(v,o)){if(K.clearLine(0),i||so(v,o)&&A!==C.first||ua(v,o)&&A!==C.last){let re=so(v,o)?-1:1,le=A;do le=(le+re+I.length)%I.length;while(!gc(I[le]));c(le)}}else if(SI(v)&&!Number.isNaN(Number(K.line))){let re=Number(K.line)-1,le=-1,je=I.findIndex((Qn)=>{if(Rt.isSeparator(Qn))return!1;return le++,le===re}),_n=I[je];if(_n!=null&&ac(_n))c(je);l.current=setTimeout(()=>{K.clearLine(0)},700)}else if(YI(v))K.clearLine(0);else if(d){let re=K.line.toLowerCase(),le=I.findIndex((je)=>{if(Rt.isSeparator(je)||!ac(je))return!1;return je.name.toLowerCase().startsWith(re)});if(le!==-1)c(le);l.current=setTimeout(()=>{K.clearLine(0)},700)}}),Ei(()=>()=>{clearTimeout(l.current)},[]);let h=r.style.message(e.message,s),W=r.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),y=0,V=KI({items:I,active:A,renderItem({item:v,isActive:K,index:re}){if(Rt.isSeparator(v))return y++,` ${v.separator}`;let le=K?r.icon.cursor:" ",je=r.indexMode==="number"?`${re+1-y}. `:"";if(v.disabled){let Qn=typeof v.disabled==="string"?v.disabled:"(disabled)",$y=K?r.icon.cursor:"-";return r.style.disabled(`${$y} ${je}${v.name} ${Qn}`)}return(K?r.style.highlight:(Qn)=>Qn)(`${le} ${je}${v.name}`)},pageSize:n,loop:i});if(s==="done")return[g,h,r.style.answer(u.short)].filter(Boolean).join(" ");let{description:H}=u;return`${[[g,h].filter(Boolean).join(" "),V," ",H?r.style.description(H):"",p?r.style.error(p):"",W].filter(Boolean).join(`
|
|
341
|
+
`).trimEnd()}${ZW}`});var GX="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",wX=async(e)=>{let t=[];for await(let i of e)t.push(i);return t},FW=(e,t)=>{if(t===void 0||t.projectId!==e)return new Map;let i=new Map;for(let[r,o]of Object.entries(t.pipelines)){let s=i.get(o.pipelineId)??[];s.push(r),i.set(o.pipelineId,s)}let n=new Map;for(let[r,o]of i){let[s,...a]=o;if(s!==void 0&&a.length===0)n.set(r,s)}return n},HW=(e,t)=>{let i=t.get(e.id);return{pipelineId:e.id,name:e.name,...i===void 0?{}:{sourceDirectory:i}}},Jn=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,FX=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(Jn).join(", ")}.`;async function vW(e){return ha({message:"This project tracks several pipelines. Select one",choices:e})}async function kW(e){let t=e.limit??20,i=await e.client.pipelines.listPage({projectId:e.projectId,limit:t}),n=FW(e.projectId,e.state),r=i.pipelines.map((s)=>HW(s,n)).toSorted((s,a)=>{let g=s.name.localeCompare(a.name);return g===0?s.pipelineId.localeCompare(a.pipelineId):g});if(r.length===0)return{outcome:"reported",output:"This project has no pipelines."};let o=r.map((s)=>s.sourceDirectory===void 0?`${s.name} ${s.pipelineId}`:`${s.name} ${s.pipelineId} ${s.sourceDirectory}`);if(i.pagination.hasMore)o.push(`Showing ${r.length} of ${i.pagination.total} pipelines. Raise --limit to see more.`);return{outcome:"reported",output:o.join(`
|
|
342
|
+
`)}}var HX=async(e,t,i)=>{let n=await wX(e.pipelines.listAll({projectId:t})),r=FW(t,i);return n.map((o)=>HW(o,r)).toSorted((o,s)=>{let a=o.name.localeCompare(s.name);return a===0?o.pipelineId.localeCompare(s.pipelineId):a})},fa=(e,t,i)=>{if(b(e.length<=1,t,{hint:{description:"Pass the pipeline id shown by toloka pipeline list instead of the name."}}),e.length!==1)return;let[n]=e;return b(n,i,{hint:{description:"Run toloka pipeline list to see the pipelines of this project."}}),n},wW=(e,t)=>{let i=FX(t),n=fa(t.filter((l)=>l.pipelineId===e),i,i);if(n!==void 0)return n;let r=t.filter((l)=>l.name===e),o=fa(r,`Multiple pipelines are named ${e}: ${r.map(Jn).join(", ")}.`,i);if(o!==void 0)return o;let s=fa(t.filter((l)=>l.sourceDirectory===e),i,i);if(s!==void 0)return s;let a=t.filter((l)=>{if(l.sourceDirectory===void 0)return!1;let d=l.sourceDirectory.split("/");return d[d.length-1]===e}),g=fa(a,`Multiple pipelines match ${e}: ${a.map(Jn).join(", ")}.`,i);if(g!==void 0)return g;b(!1,i,{hint:{description:"Run toloka pipeline list to see the pipelines of this project."}})};async function co(e){let t=await HX(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return wW(e.pipeline,t);if(b(t.length>0,"This project has no pipelines.",{hint:{description:"Run toloka apply to create the pipelines declared in source."}}),t.length>1&&e.select!==void 0){let i=await e.select(t.map((n)=>({name:Jn(n),value:n.pipelineId})));return wW(i,t)}if(t.length===1){let[i]=t;b(i,"This project has no pipelines.",{hint:{description:"Run toloka apply to create the pipelines declared in source."}}),b(!1,`Pass a pipeline name. This project has: ${Jn(i)}.`,{hint:{disabled:!0}})}b(!1,`This project tracks several pipelines, so name one: ${t.map(Jn).join(", ")}.`,{hint:{disabled:!0}})}var PW=(e)=>`run ${e.id} is ${e.status}`,NW=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function xW(e,t){let i=await co({client:e,...t}),n=await e.runs.start({pipelineId:i.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${PW(n)} for ${i.name}.`,`Follow it with toloka pipeline status ${i.pipelineId}, or re-run with --wait.`].join(`
|
|
343
343
|
`)};try{let r=await e.waitFor({type:"pipelineRun",runId:n.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),o=NW(r);return{outcome:o,output:o==="failed"?[`Run ${r.id} failed.`,`Inspect items with toloka pipeline results ${r.id} --failed.`].join(`
|
|
344
344
|
`):`Run ${r.id} succeeded.`}}catch(r){if(r instanceof te&&r.code==="wait_timeout")return{outcome:"timedOut",output:[`Stopped waiting for run ${n.id}; it has not reached a terminal state yet and may still be running.`,`Check it with toloka pipeline status ${i.pipelineId}.`].join(`
|
|
345
345
|
`)};throw r}}async function YW(e,t){let i=await co({client:e,...t}),n=await e.runs.listPage({pipelineId:i.pipelineId,limit:t.limit??10});if(n.runs.length===0)return{outcome:"reported",output:`No runs yet for ${i.name}.`};let r=[];for(let o of n.runs){let s=await e.runs.get({runId:o.id});r.push(` ${s.id} ${s.status.padEnd(9)} ${o.createdAt}`)}return{outcome:"reported",output:[`Runs for ${i.name} (${n.pagination.total} total):`,...r].join(`
|
|
346
346
|
`)}}async function SW(e,t){let i=await co({client:e,...t}),r=(await e.runs.listPage({pipelineId:i.pipelineId,limit:1})).runs[0];if(r===void 0)return{outcome:"reported",output:`No runs yet for ${i.name}.`};let o=await e.runs.get({runId:r.id}),s=t.itemScanLimit??500,a=new Map,g=0;for await(let d of e.runs.listAllItems({runId:o.id}))if(a.set(d.state.status,(a.get(d.state.status)??0)+1),g+=1,g>=s)break;let l=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([d],[I])=>d.localeCompare(I)).map(([d,I])=>` ${d.padEnd(12)} ${I}`);return{outcome:NW(o),output:[`Latest ${PW(o)} (started ${r.createdAt}).`,g>=s?`Items (first ${s}):`:"Items:",...l].join(`
|
|
347
|
-
`)}}async function XW(e,t){let i=await e.runs.cancel({runId:t.runId});return{outcome:"canceled",output:`Requested cancellation of run ${i.id}; it is now ${i.status}.`}}var
|
|
348
|
-
${
|
|
349
|
-
${e.state.error}`};async function EW(e,t){let i=t.limit??20,n=t.itemScanLimit??Math.max(500,i),r=[],o=0;for await(let g of e.runs.listAllItems({runId:t.runId})){if(o+=1,t.failedOnly!==!0||g.state.status==="failed")r.push(g);if(r.length>=i||o>=n)break}if(r.length===0)return{outcome:"reported",output:t.failedOnly===!0&&o>=n?`No failed items in the first ${n} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[o>=n&&r.length<i?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length} after scanning ${n}, limit ${i}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length}, limit ${i}):`,...r.map(
|
|
350
|
-
`)}}var TW=(e)=>{if(typeof e!=="object"||e===null)return!1;if(!("label"in e)||typeof e.label!=="string")return!1;if(!("expectedTotal"in e)||typeof e.expectedTotal!=="string")return!1;if(!("maxTotal"in e)||typeof e.maxTotal!=="string")return!1;if("subLines"in e&&e.subLines!==void 0&&!Array.isArray(e.subLines))return!1;return!0},
|
|
351
|
-
`)};async function UW(e,t){let i=await co({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:i.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:NX(n,i.name)}}var OW=(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",Te).description("list live pipelines in the selected project").action(async(a)=>{let{client:g,projectId:l,state:d}=await w(r(),i);S(l);let I=await kW({client:g,projectId:l,state:d,...a.limit===void 0?{}:{limit:a.limit}});i.io.stdout(I.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 to wait",Te).description("start a run on a deployed pipeline").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await xW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},wait:g.wait,...g.timeout===void 0?{}:{timeoutMs:g.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.output),n.value=qs(C.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:g,state:l,projectId:d}=await w(r(),i);S(d);let I=await SW(g,{projectId:d,state:l,...a===void 0?{}:{pipeline:a},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output),n.value=qs(I.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",Te).description("list recent runs").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await YW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},...g.limit===void 0?{}:{limit:g.limit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.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",Te).description("forecast what a run of this pipeline would bill").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await UW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},...g.itemLimit===void 0?{}:{itemLimit:g.itemLimit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.output)}),s.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(a)=>{let{client:g}=await w(r(),i),l=await XW(g,{runId:a});i.io.stdout(l.output)}),s.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Te).option("--failed","only report failed items",!1).description("report a run's items").action(async(a,g)=>{let{client:l}=await w(r(),i),d=await EW(l,{runId:a,failedOnly:g.failed,...g.limit===void 0?{}:{limit:g.limit}});i.io.stdout(d.output),n.value=qs(d.outcome)})};var xX=["read","write","deploy","labeling-read","labeling-write","labeling-deploy"],zW=(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",Te).description("list remote projects this key can see").action(async(a)=>{let g=r(),{client:l,stored:d,state:I}=await w(g,i),C=ta(g,i,d,I);await lh({client:l,io:i.io,...C===void 0?{}:{context:C},...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,g)=>{let l=r(),d=await Jt(i.environment),{client:I}=await ki(l,i,void 0,d.credentials);await Ih({environment:i.environment,flags:l,client:I,io:i.io,afterPreflight:async()=>vi(I,i.analytics),...a===void 0?{}:{alias:a},...g===void 0?{}:{projectId:g}})}),o.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(a)=>{await ch({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(),g=await fI(a,i),l=await Be(a,i.io),d=await Ae(l);if(Ch({flags:a,environment:i.environment,stored:g,...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:g,projectId:l}=await w(r(),i);S(l);let d=await g.projects.get({projectId:l}),I=new URL(`/teams/${encodeURIComponent(d.teamId)}/projects/${encodeURIComponent(d.id)}`,a);i.io.stdout(I.href)}),o.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(a)=>{await uh({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,g,l)=>{b(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 dh({sourceRoot:d,type:a,name:g,confirm:l.confirm,io:i.io})}),o.command("token").addOption(new ai("--preset <name>","permission preset").choices(xX).default("write")).option("--permissions <list>","comma-separated resource:operation pairs instead of a preset").option("--expires-in <seconds>","lifetime in seconds (60..21600)",Te).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:g,projectId:l}=await w(r(),i);S(l);let d=a.permissions===void 0?{preset:a.preset}:{permissions:a.permissions.split(",").map((m)=>m.trim())},{token:I,expiresAt:C}=await g.projects.createToken({projectId:l,...d,...a.expiresIn===void 0?{}:{expiresInSeconds:a.expiresIn},...a.projects===void 0?{}:{projectIds:a.projects.split(",").map((m)=>m.trim())}});i.io.stdout(I),i.io.stderr(`Token expires at ${C}. Use it as TOLOKA_API_KEY or --api-key.`)}),o.command("tokens").description("list live project-scoped tokens").action(async()=>{let{client:a,projectId:g}=await w(r(),i);S(g);let l=[];for await(let d of a.projects.listAllTokens({projectId:g}))l.push(d);i.io.stdout(l.length===0?"No live tokens.":ge([["Id","User","Expires","Projects","Permissions"],...l.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:g,projectId:l}=await w(r(),i);S(l),await g.projects.revokeToken({projectId:l,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:g}=await w(r(),i);S(g);let{revokedCount:l}=await a.projects.revokeAllTokens({projectId:g});i.io.stdout(`Revoked ${l} token${l===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,g)=>{let l=r(),d=await Jt(i.environment),{client:I}=await ki(l,i,void 0,d.credentials),C=await Be(l,i.io);await mh({environment:i.environment,flags:l,client:I,io:i.io,sourceRoot:C,afterPreflight:async()=>vi(I,i.analytics),...a===void 0?{}:{alias:a},...g.name===void 0?{}:{name:g.name},...g.teamId===void 0?{}:{teamId:g.teamId},...g.deliveryOrderId===void 0?{}:{deliveryOrderId:g.deliveryOrderId}})})};var jW=require("crypto"),lc=require("fs"),Wa=require("fs/promises"),dt=require("path");var YX=262144,SX=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),XX=async(e,t)=>{let i=dt.relative(t,e);if(i===""||i===".."||i.startsWith(`..${dt.sep}`)||dt.isAbsolute(i))return;let n=i.split(dt.sep);for(let r=1;r<n.length;r+=1){let o=dt.join(t,...n.slice(0,r)),s=await Wa.lstat(o);b(!s.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${o}; select a path that does not traverse symbolic links.`,{hint:{disabled:!0}})}},EX=async(e,t,i)=>{let n=dt.resolve(i,e);await XX(n,t);let r;try{r=await Wa.open(n,lc.constants.O_RDONLY|lc.constants.O_NOFOLLOW)}catch(o){throw b(!(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 b(o.isFile(),`Report file ${n} is not a regular file.`,{hint:{description:"Pass the path of a Markdown or text file."}}),b(o.size>0,`Report file ${n} is empty.`,{hint:{description:"Write the report first; the toloka-report-issue skill describes the format."}}),b(o.size<=YX,`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}},TX=async(e,t,i)=>{let n=await EX(e,t,i);try{let r=await n.handle.readFile();b(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 SX.decode(r)}catch{throw new F(`Report file ${n.absolutePath} is not valid UTF-8.`,{hint:{description:"Save the report as UTF-8 text."}})}}finally{await n.handle.close()}},JX=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 DW(e){let{analytics:t,io:i}=e;b(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}});let n=await TX(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 JX(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=jW.randomUUID();return await t.submitIssueReport({reportId:r,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),i.stdout(`Submitted issue report: ${r}`),0}var _W=(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",Zh,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(o,s)=>{b(i.analytics,"Issue reporting requires CLI analytics.",{hint:{description:"Set TOLOKA_TELEMETRY=1 to enable analytics, then re-run toloka report."}});let a=ea(r()),g=r().baseUrl??i.environment.TOLOKA_BASE_URL??oi(i.environment)??Hi;n.value=await DW({path:o,authoredBy:s.authoredBy,platform:new URL(g).origin,confirm:s.confirm,sourceRoot:a,cwd:process.cwd(),analytics:i.analytics,io:i.io})})};var QW=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(s,a)=>{let{client:g,projectId:l}=await w(r(),i);S(l);let d=a.fromEnv===void 0?(await i.io.readStdin()).replace(/\r?\n$/u,""):i.environment[a.fromEnv];b(d!==void 0,`Missing secret value. Set ${a.fromEnv??"the named environment variable"} or pipe it to stdin.`,{hint:{disabled:!0}});try{let I=await Wf(g,{projectId:l,name:s,value:d});i.io.stdout(I.output)}catch{i.io.stderr(`Failed to set secret ${s}.`),n.value=1}})};var ey=require("crypto"),ne=require("fs/promises"),be=require("path");var KW=require("fs/promises"),LW=require("path");var ya=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),Va=(e)=>ya(e,"ENOENT"),Un=async(e)=>{try{return await KW.lstat(e)}catch(t){if(Va(t))return;throw t}},uo=async(e,t,i="write")=>{let n=e;for(let r of t.split("/")){n=LW.join(n,r);let o=await Un(n);if(o===void 0)return;b(!o.isSymbolicLink(),`Refusing to ${i} through symbolic link ${n}.`,{hint:{description:"Replace the symbolic link with a regular directory, or point the command at the real path."}})}};var Ba="catalog.json",zn=".agents/skills",On="SKILL.md",Ic="skills",MW=500,$W=1048576,ty=64,UX=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,OX=/^[a-f0-9]{64}$/u,iy="rerun the CLI installer to update",ny=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),qW=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),dc=(e)=>typeof e==="string"&&e.trim().length>0,zX=(e)=>typeof e==="string"&&e.length<=ty&&UX.test(e),jX=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),DX=(e,t)=>{b(ny(e),t("every skill must be an object."),{hint:Ce});let{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}=e;return b(zX(i),t(`skill id ${JSON.stringify(i)} must be at most ${ty} lowercase letters, digits, and single hyphens.`),{hint:Ce}),b(dc(n),t(`skill ${i} needs a name.`),{hint:Ce}),b(dc(r),t(`skill ${i} needs a description.`),{hint:Ce}),b(qW(o),t(`skill ${i} tags must be strings.`),{hint:Ce}),b(dc(s),t(`skill ${i} needs a version.`),{hint:Ce}),b(typeof a==="string"&&OX.test(a),t(`skill ${i} digest must be the sha256 hex digest of its files.`),{hint:Ce}),b(qW(g)&&g.includes(On),t(`skill ${i} files must include ${On}.`),{hint:Ce}),b(g.every(jX),t(`skill ${i} files must be relative paths inside its directory.`),{hint:Ce}),b(new Set(g).size===g.length,t(`skill ${i} lists a file more than once.`),{hint:Ce}),{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}},_X=(e,t)=>{try{return JSON.parse(e)}catch(i){throw new F(`Invalid skill catalog ${t}: ${Ut(i)}`,{cause:i,hint:Ce})}},QX=async(e)=>{try{return(await ne.stat(e)).isFile()}catch(t){if(ya(t,"ENOENT","ENOTDIR"))return!1;throw t}},cc=async(e)=>{let t=be.join(e,Ic);if(await QX(be.join(t,Ba)))return t;let i=be.dirname(e);return i===e?void 0:cc(i)};async function KX(e=process.argv[1]){if(Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0)return be.join(be.dirname(process.argv[1]),"skills");let t=e===void 0?void 0:await ne.realpath(e),i=t===void 0?void 0:await cc(be.dirname(t));if(i!==void 0)return i;let n=await cc(process.cwd()),r=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return b(n!==void 0,`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${Ic}/${Ba} in a directory above its runtime entry, but ${r}, and no ${Ic}/${Ba} exists above ${process.cwd()} either. Reinstall @toloka-platform/sdk.`,{hint:{disabled:!0}}),n}var uc=async()=>LX(await KX());async function LX(e){let t=be.join(e,Ba),i=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:n}=await ne.stat(t);b(n<=$W,i(`the manifest is ${n} bytes; the limit is ${$W} bytes.`),{hint:Ce});let r=_X(await ne.readFile(t,"utf8"),t);b(ny(r)&&Array.isArray(r.skills),i("expected an object with a skills array."),{hint:Ce}),b(r.skills.length<=MW,i(`${r.skills.length} skills exceed the limit of ${MW}.`),{hint:Ce});let o=r.skills.map((a)=>DX(a,i)),s=new Set;for(let a of o)b(!s.has(a.id),i(`skill id ${a.id} appears more than once.`),{hint:Ce}),s.add(a.id);return{root:e,manifestPath:t,skills:o}}async function ry(e,t){let i=ey.createHash("sha256");for(let n of t.toSorted())i.update(n),i.update("\x00"),i.update(await ne.readFile(be.join(e,n))),i.update("\x00");return i.digest("hex")}var MX=(e,t)=>{let i=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);if(i.length===0)return[];return e.map((n,r)=>{let o=[n.id,n.name,n.description,...n.tags].join(`
|
|
352
|
-
`).toLowerCase();return{skill:n,index:r,score:i.filter((s)=>o.includes(s)).length}}).filter(({score:n})=>n>0).toSorted((n,r)=>r.score-n.score||n.index-r.index).map(({skill:n})=>n)};async function
|
|
353
|
-
`)};async function ay({sourceRoot:e,json:t,io:i}){let n=await uc();i.stdout(sy(await oy({sourceRoot:e,skills:n.skills}),t))}async function gy({sourceRoot:e,query:t,json:i,io:n}){let r=await uc(),o=await oy({sourceRoot:e,skills
|
|
354
|
-
<!-- toloka:sdk-version ${oe} -->`,
|
|
347
|
+
`)}}async function XW(e,t){let i=await e.runs.cancel({runId:t.runId});return{outcome:"canceled",output:`Requested cancellation of run ${i.id}; it is now ${i.status}.`}}var vX=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
|
|
348
|
+
${GX}`;return e.state.error===null?t:`${t}
|
|
349
|
+
${e.state.error}`};async function EW(e,t){let i=t.limit??20,n=t.itemScanLimit??Math.max(500,i),r=[],o=0;for await(let g of e.runs.listAllItems({runId:t.runId})){if(o+=1,t.failedOnly!==!0||g.state.status==="failed")r.push(g);if(r.length>=i||o>=n)break}if(r.length===0)return{outcome:"reported",output:t.failedOnly===!0&&o>=n?`No failed items in the first ${n} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[o>=n&&r.length<i?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length} after scanning ${n}, limit ${i}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length}, limit ${i}):`,...r.map(vX)].join(`
|
|
350
|
+
`)}}var TW=(e)=>{if(typeof e!=="object"||e===null)return!1;if(!("label"in e)||typeof e.label!=="string")return!1;if(!("expectedTotal"in e)||typeof e.expectedTotal!=="string")return!1;if(!("maxTotal"in e)||typeof e.maxTotal!=="string")return!1;if("subLines"in e&&e.subLines!==void 0&&!Array.isArray(e.subLines))return!1;return!0},kX=(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(" "))},JW=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let r of e.subLines??[])if(TW(r))n.push(...JW(r,t+1));return n},PX=(e)=>{let t=[],i=[],n=[];for(let r of e){if(r.kind==="priced"){t.push([r.nodeNameDisplay,r.expectedTotal,r.maxTotal]);for(let o of r.displayBreakdown)if(TW(o))t.push(...JW(o,1));if(r.warning!==void 0)n.push(` ${r.nodeNameDisplay}: ${r.warning}`);continue}i.push(r.kind==="validation-errors"?` ${r.nodeNameDisplay} skipped (validation errors)`:` ${r.nodeNameDisplay} not billed`)}return{billed:t,unpriced:i,warnings:n}},NX=(e)=>{let t=e.expected===e.worstCase?[["Run cost",e.expected,""]]:[["Expected run cost",e.expected,""],["Maximum run cost","",e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,"N/A"]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},xX=(e,t)=>{let{billed:i,unpriced:n,warnings:r}=PX(e.nodes),o=NX(e.total),s=kX([["Item","Expected","Maximum"],...i,...o]),a=s.slice(0,1+i.length),g=s.slice(1+i.length),l=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...a];if(i.length===0)l.push(" (no billed nodes)");if(l.push("",...g),n.length>0)l.push("","Not billed",...n);if(r.length>0)l.push("","Warnings",...r);if(e.isInternalPricing===!0)l.push("","Internal-team pricing.");return l.push("",e.disclaimer),l.join(`
|
|
351
|
+
`)};async function UW(e,t){let i=await co({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:i.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:xX(n,i.name)}}var OW=(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",Te).description("list live pipelines in the selected project").action(async(a)=>{let{client:g,projectId:l,state:d}=await w(r(),i);S(l);let I=await kW({client:g,projectId:l,state:d,...a.limit===void 0?{}:{limit:a.limit}});i.io.stdout(I.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 to wait",Te).description("start a run on a deployed pipeline").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await xW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},wait:g.wait,...g.timeout===void 0?{}:{timeoutMs:g.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.output),n.value=qs(C.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:g,state:l,projectId:d}=await w(r(),i);S(d);let I=await SW(g,{projectId:d,state:l,...a===void 0?{}:{pipeline:a},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(I.output),n.value=qs(I.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",Te).description("list recent runs").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await YW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},...g.limit===void 0?{}:{limit:g.limit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.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",Te).description("forecast what a run of this pipeline would bill").action(async(a,g)=>{let{client:l,state:d,projectId:I}=await w(r(),i);S(I);let C=await UW(l,{projectId:I,state:d,...a===void 0?{}:{pipeline:a},...g.itemLimit===void 0?{}:{itemLimit:g.itemLimit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(C.output)}),s.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(a)=>{let{client:g}=await w(r(),i),l=await XW(g,{runId:a});i.io.stdout(l.output)}),s.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Te).option("--failed","only report failed items",!1).description("report a run's items").action(async(a,g)=>{let{client:l}=await w(r(),i),d=await EW(l,{runId:a,failedOnly:g.failed,...g.limit===void 0?{}:{limit:g.limit}});i.io.stdout(d.output),n.value=qs(d.outcome)})};var YX=["read","write","deploy","labeling-read","labeling-write","labeling-deploy"],zW=(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",Te).description("list remote projects this key can see").action(async(a)=>{let g=r(),{client:l,stored:d,state:I}=await w(g,i),C=ta(g,i,d,I);await lh({client:l,io:i.io,...C===void 0?{}:{context:C},...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,g)=>{let l=r(),d=await Jt(i.environment),{client:I}=await ki(l,i,void 0,d.credentials);await Ih({environment:i.environment,flags:l,client:I,io:i.io,afterPreflight:async()=>vi(I,i.analytics),...a===void 0?{}:{alias:a},...g===void 0?{}:{projectId:g}})}),o.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(a)=>{await ch({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(),g=await fI(a,i),l=await Be(a,i.io),d=await Ae(l);if(Ch({flags:a,environment:i.environment,stored:g,...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:g,projectId:l}=await w(r(),i);S(l);let d=await g.projects.get({projectId:l}),I=new URL(`/teams/${encodeURIComponent(d.teamId)}/projects/${encodeURIComponent(d.id)}`,a);i.io.stdout(I.href)}),o.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(a)=>{await uh({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,g,l)=>{b(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 dh({sourceRoot:d,type:a,name:g,confirm:l.confirm,io:i.io})}),o.command("token").addOption(new ai("--preset <name>","permission preset").choices(YX).default("write")).option("--permissions <list>","comma-separated resource:operation pairs instead of a preset").option("--expires-in <seconds>","lifetime in seconds (60..21600)",Te).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:g,projectId:l}=await w(r(),i);S(l);let d=a.permissions===void 0?{preset:a.preset}:{permissions:a.permissions.split(",").map((m)=>m.trim())},{token:I,expiresAt:C}=await g.projects.createToken({projectId:l,...d,...a.expiresIn===void 0?{}:{expiresInSeconds:a.expiresIn},...a.projects===void 0?{}:{projectIds:a.projects.split(",").map((m)=>m.trim())}});i.io.stdout(I),i.io.stderr(`Token expires at ${C}. Use it as TOLOKA_API_KEY or --api-key.`)}),o.command("tokens").description("list live project-scoped tokens").action(async()=>{let{client:a,projectId:g}=await w(r(),i);S(g);let l=[];for await(let d of a.projects.listAllTokens({projectId:g}))l.push(d);i.io.stdout(l.length===0?"No live tokens.":ge([["Id","User","Expires","Projects","Permissions"],...l.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:g,projectId:l}=await w(r(),i);S(l),await g.projects.revokeToken({projectId:l,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:g}=await w(r(),i);S(g);let{revokedCount:l}=await a.projects.revokeAllTokens({projectId:g});i.io.stdout(`Revoked ${l} token${l===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,g)=>{let l=r(),d=await Jt(i.environment),{client:I}=await ki(l,i,void 0,d.credentials),C=await Be(l,i.io);await mh({environment:i.environment,flags:l,client:I,io:i.io,sourceRoot:C,afterPreflight:async()=>vi(I,i.analytics),...a===void 0?{}:{alias:a},...g.name===void 0?{}:{name:g.name},...g.teamId===void 0?{}:{teamId:g.teamId},...g.deliveryOrderId===void 0?{}:{deliveryOrderId:g.deliveryOrderId}})})};var jW=require("crypto"),lc=require("fs"),Wa=require("fs/promises"),dt=require("path");var SX=262144,XX=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),EX=async(e,t)=>{let i=dt.relative(t,e);if(i===""||i===".."||i.startsWith(`..${dt.sep}`)||dt.isAbsolute(i))return;let n=i.split(dt.sep);for(let r=1;r<n.length;r+=1){let o=dt.join(t,...n.slice(0,r)),s=await Wa.lstat(o);b(!s.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${o}; select a path that does not traverse symbolic links.`,{hint:{disabled:!0}})}},TX=async(e,t,i)=>{let n=dt.resolve(i,e);await EX(n,t);let r;try{r=await Wa.open(n,lc.constants.O_RDONLY|lc.constants.O_NOFOLLOW)}catch(o){throw b(!(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 b(o.isFile(),`Report file ${n} is not a regular file.`,{hint:{description:"Pass the path of a Markdown or text file."}}),b(o.size>0,`Report file ${n} is empty.`,{hint:{description:"Write the report first; the toloka-report-issue skill describes the format."}}),b(o.size<=SX,`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}},JX=async(e,t,i)=>{let n=await TX(e,t,i);try{let r=await n.handle.readFile();b(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 XX.decode(r)}catch{throw new F(`Report file ${n.absolutePath} is not valid UTF-8.`,{hint:{description:"Save the report as UTF-8 text."}})}}finally{await n.handle.close()}},UX=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 DW(e){let{analytics:t,io:i}=e;b(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}});let n=await JX(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 UX(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=jW.randomUUID();return await t.submitIssueReport({reportId:r,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),i.stdout(`Submitted issue report: ${r}`),0}var _W=(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",Zh,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(o,s)=>{b(i.analytics,"Issue reporting requires CLI analytics.",{hint:{description:"Set TOLOKA_TELEMETRY=1 to enable analytics, then re-run toloka report."}});let a=ea(r()),g=r().baseUrl??i.environment.TOLOKA_BASE_URL??oi(i.environment)??Hi;n.value=await DW({path:o,authoredBy:s.authoredBy,platform:new URL(g).origin,confirm:s.confirm,sourceRoot:a,cwd:process.cwd(),analytics:i.analytics,io:i.io})})};var QW=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(s,a)=>{let{client:g,projectId:l}=await w(r(),i);S(l);let d=a.fromEnv===void 0?(await i.io.readStdin()).replace(/\r?\n$/u,""):i.environment[a.fromEnv];b(d!==void 0,`Missing secret value. Set ${a.fromEnv??"the named environment variable"} or pipe it to stdin.`,{hint:{disabled:!0}});try{let I=await Wf(g,{projectId:l,name:s,value:d});i.io.stdout(I.output)}catch{i.io.stderr(`Failed to set secret ${s}.`),n.value=1}})};var ey=require("crypto"),ne=require("fs/promises"),be=require("path");var KW=require("fs/promises"),LW=require("path");var ya=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),Va=(e)=>ya(e,"ENOENT"),Un=async(e)=>{try{return await KW.lstat(e)}catch(t){if(Va(t))return;throw t}},uo=async(e,t,i="write")=>{let n=e;for(let r of t.split("/")){n=LW.join(n,r);let o=await Un(n);if(o===void 0)return;b(!o.isSymbolicLink(),`Refusing to ${i} through symbolic link ${n}.`,{hint:{description:"Replace the symbolic link with a regular directory, or point the command at the real path."}})}};var Ba="catalog.json",zn=".agents/skills",On="SKILL.md",Ic="skills",MW=500,$W=1048576,ty=64,OX=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,zX=/^[a-f0-9]{64}$/u,iy="rerun the CLI installer to update",ny=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),qW=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),dc=(e)=>typeof e==="string"&&e.trim().length>0,jX=(e)=>typeof e==="string"&&e.length<=ty&&OX.test(e),DX=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),_X=(e,t)=>{b(ny(e),t("every skill must be an object."),{hint:Ce});let{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}=e;return b(jX(i),t(`skill id ${JSON.stringify(i)} must be at most ${ty} lowercase letters, digits, and single hyphens.`),{hint:Ce}),b(dc(n),t(`skill ${i} needs a name.`),{hint:Ce}),b(dc(r),t(`skill ${i} needs a description.`),{hint:Ce}),b(qW(o),t(`skill ${i} tags must be strings.`),{hint:Ce}),b(dc(s),t(`skill ${i} needs a version.`),{hint:Ce}),b(typeof a==="string"&&zX.test(a),t(`skill ${i} digest must be the sha256 hex digest of its files.`),{hint:Ce}),b(qW(g)&&g.includes(On),t(`skill ${i} files must include ${On}.`),{hint:Ce}),b(g.every(DX),t(`skill ${i} files must be relative paths inside its directory.`),{hint:Ce}),b(new Set(g).size===g.length,t(`skill ${i} lists a file more than once.`),{hint:Ce}),{id:i,name:n,description:r,tags:o,version:s,digest:a,files:g}},QX=(e,t)=>{try{return JSON.parse(e)}catch(i){throw new F(`Invalid skill catalog ${t}: ${Ut(i)}`,{cause:i,hint:Ce})}},KX=async(e)=>{try{return(await ne.stat(e)).isFile()}catch(t){if(ya(t,"ENOENT","ENOTDIR"))return!1;throw t}},cc=async(e)=>{let t=be.join(e,Ic);if(await KX(be.join(t,Ba)))return t;let i=be.dirname(e);return i===e?void 0:cc(i)};async function LX(e=process.argv[1]){if(Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0)return be.join(be.dirname(process.argv[1]),"skills");let t=e===void 0?void 0:await ne.realpath(e),i=t===void 0?void 0:await cc(be.dirname(t));if(i!==void 0)return i;let n=await cc(process.cwd()),r=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return b(n!==void 0,`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${Ic}/${Ba} in a directory above its runtime entry, but ${r}, and no ${Ic}/${Ba} exists above ${process.cwd()} either. Reinstall @toloka-platform/sdk.`,{hint:{disabled:!0}}),n}var uc=async()=>MX(await LX());async function MX(e){let t=be.join(e,Ba),i=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:n}=await ne.stat(t);b(n<=$W,i(`the manifest is ${n} bytes; the limit is ${$W} bytes.`),{hint:Ce});let r=QX(await ne.readFile(t,"utf8"),t);b(ny(r)&&Array.isArray(r.skills),i("expected an object with a skills array."),{hint:Ce}),b(r.skills.length<=MW,i(`${r.skills.length} skills exceed the limit of ${MW}.`),{hint:Ce});let o=r.skills.map((a)=>_X(a,i)),s=new Set;for(let a of o)b(!s.has(a.id),i(`skill id ${a.id} appears more than once.`),{hint:Ce}),s.add(a.id);return{root:e,manifestPath:t,skills:o}}async function ry(e,t){let i=ey.createHash("sha256");for(let n of t.toSorted())i.update(n),i.update("\x00"),i.update(await ne.readFile(be.join(e,n))),i.update("\x00");return i.digest("hex")}var $X=(e,t)=>{let i=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);if(i.length===0)return[];return e.map((n,r)=>{let o=[n.id,n.name,n.description,...n.tags].join(`
|
|
352
|
+
`).toLowerCase();return{skill:n,index:r,score:i.filter((s)=>o.includes(s)).length}}).filter(({score:n})=>n>0).toSorted((n,r)=>r.score-n.score||n.index-r.index).map(({skill:n})=>n)};async function qX(e,t){let i=be.join(e,zn,t.id);if(await Un(i)===void 0)return"not-installed";try{return await ry(i,t.files)===t.digest?"current":"stale"}catch(n){if(ya(n,"ENOENT","ENOTDIR"))return"stale";throw n}}var oy=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(i)=>({...i,status:await qX(e,i)}))),eE=async(e,t,i,n)=>{await e(i,n);try{await e(t,i)}catch(r){try{await e(n,i)}catch(o){throw new F(`Failed to replace ${i}; the previous version is preserved at ${n}. ${Ut(o)}`,{cause:r,hint:{description:`Move ${n} back to ${i} by hand, then re-run toloka skill install <skill-id> --force.`}})}throw r}await ne.rm(n,{recursive:!0,force:!0})};async function tE({catalog:e,sourceRoot:t,skillId:i,force:n=!1,rename:r=ne.rename}){let o=e.skills.find((I)=>I.id===i);b(o,`Skill ${JSON.stringify(i)} is not in the catalog bundled with ${fe} ${oe}. Run \`toloka skill list\` to see the available skills; a newer release may ship it (${iy}).`,{hint:{disabled:!0}});let s=`${zn}/${o.id}`;await uo(t,s);let a=be.join(t,s),g=await Un(a);b(g===void 0||n,`${s} already exists. Re-run with --force to replace it with the catalog version of ${o.id}.`,{hint:{disabled:!0}});let l=be.dirname(a);await ne.mkdir(l,{recursive:!0});let d=await ne.mkdtemp(be.join(l,`.${o.id}.tmp-`));try{for(let I of o.files){let C=be.join(d,I);await ne.mkdir(be.dirname(C),{recursive:!0});let m=be.join(e.root,o.id,I);if(Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0)await ne.writeFile(C,await ne.readFile(m));else await ne.copyFile(m,C)}if(b(await ry(d,o.files)===o.digest,`Skill ${o.id} failed its digest check: the packaged files do not match the catalog digest ${o.digest}. Nothing was installed.`,{hint:Ce}),g===void 0)await r(d,a);else await eE(r,d,a,`${d}.backup`)}catch(I){throw await ne.rm(d,{recursive:!0,force:!0}),I}return{skill:o,directory:a,replaced:g!==void 0}}var sy=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let i=Math.max(...e.map((r)=>r.id.length)),n=Math.max(...e.map((r)=>r.status.length));return e.flatMap((r)=>[`${r.id.padEnd(i)} ${r.status.padEnd(n)} ${r.name}`,` ${r.description}`]).join(`
|
|
353
|
+
`)};async function ay({sourceRoot:e,json:t,io:i}){let n=await uc();i.stdout(sy(await oy({sourceRoot:e,skills:n.skills}),t))}async function gy({sourceRoot:e,query:t,json:i,io:n}){let r=await uc(),o=await oy({sourceRoot:e,skills:$X(r.skills,t)});if(i||o.length>0){n.stdout(sy(o,i));return}n.stdout(`No skills match ${JSON.stringify(t)} in the catalog bundled with ${fe} ${oe}. Run \`toloka skill list\` to see it; a newer release may add more (${iy}).`)}async function ly({sourceRoot:e,skillId:t,force:i,io:n}){let r=await uc(),o=await tE({catalog:r,sourceRoot:e,skillId:t,force:i}),s=`${zn}/${o.skill.id}`,a=o.skill.files.length;n.stdout(`${o.replaced?"Replaced":"Installed"} ${o.skill.id} in ${s} (${a} ${a===1?"file":"files"}). Start with ${s}/${On}.`)}var dy=(e,t)=>{let{context:i,globals:n}=t,r=e.command("skill").description("discover bundled agent skills and install them into .agents/skills");r.command("list").option("--json","print Skill Descriptors with their status as JSON",!1).description("list bundled skills as not-installed, current, or stale").action(async(o)=>{let s=await Be(n(),i.io);await ay({sourceRoot:s,json:o.json,io:i.io})}),r.command("search").argument("<query>","text matched case-insensitively against id, name, description, and tags").option("--json","print matching Skill Descriptors with their status as JSON",!1).description("find bundled skills for a task").action(async(o,s)=>{let a=await Be(n(),i.io);await gy({sourceRoot:a,query:o,json:s.json,io:i.io})}),r.command("install").argument("<skillId>","skill id from toloka skill list").option("-f, --force","replace an existing .agents/skills/<skillId> directory",!1).description("copy one bundled skill into .agents/skills/<skillId>").action(async(o,s)=>{let a=await Be(n(),i.io);await ly({sourceRoot:a,skillId:o,force:s.force,io:i.io})})};var hy=require("fs/promises");var Ie=require("fs/promises"),Re=require("path");var Ac="toloka-bootstrap",cy=`.claude/skills/${Ac}/SKILL.md`,uy=`.cursor/rules/${Ac}.mdc`,Ui="AGENTS.md",iE=[cy,uy,Ui],jn={begin:"<toloka>",end:"</toloka>"},Cc={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},mc=/<!-- toloka:sdk-version ([^\s>]+) -->/u,Cy=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),Dn=async(e)=>{try{return await Ie.readFile(e,"utf8")}catch(t){if(Va(t))return;throw t}},pc=async(e)=>{try{return(await Ie.lstat(e)).isDirectory()}catch(t){if(Va(t))return!1;throw t}},bc=(e)=>mc.test(e),my=`Generated by \`${fe}\` version \`${oe}\`.
|
|
354
|
+
<!-- toloka:sdk-version ${oe} -->`,nE=`${jn.begin}
|
|
355
355
|
|
|
356
356
|
## Toloka Agent Bootstrap
|
|
357
357
|
|
|
@@ -371,30 +371,30 @@ ${jn.end}`,py=`# Toloka Agent Bootstrap pointer
|
|
|
371
371
|
${my}
|
|
372
372
|
|
|
373
373
|
Read the \`${jn.begin}\` block in \`${Ui}\` at the source root and follow it before doing Toloka work. It tells you to run \`toloka --help\`, search the bundled Skill Catalog with \`toloka skill search <query>\`, install the match with \`toloka skill install <skill-id>\`, and read \`${zn}/<skill-id>/${On}\` before acting.
|
|
374
|
-
`,
|
|
374
|
+
`,rE=`---
|
|
375
375
|
name: ${Ac}
|
|
376
376
|
description: Toloka platform work with the toloka CLI and ${fe}, such as pipeline projects, datasets, runs, secrets, and issue reporting. Use when the user mentions Toloka or the toloka CLI. Start by reading the ${jn.begin} Agent Bootstrap block in ${Ui}, then find and install the matching skill.
|
|
377
377
|
---
|
|
378
378
|
|
|
379
|
-
${py}`,
|
|
379
|
+
${py}`,oE=`---
|
|
380
380
|
description: Toloka Agent Bootstrap pointer for the toloka CLI and ${fe}
|
|
381
381
|
alwaysApply: true
|
|
382
382
|
---
|
|
383
383
|
|
|
384
|
-
${py}`,Iy=(e,t,i)=>{let n=e.indexOf(t.begin),r=e.indexOf(t.end);if(n===-1&&r===-1)return;return b(n!==-1&&r!==-1&&n<r,`Malformed Toloka block in ${i}: expected one ${t.begin} followed by one ${t.end}. Repair the file by hand, then re-run \`toloka init\`.`,{hint:{disabled:!0}}),b(!e.includes(t.begin,n+t.begin.length)&&!e.includes(t.end,r+t.end.length),`Multiple Toloka blocks in ${i}: keep exactly one ${t.begin} ... ${t.end} block, then re-run \`toloka init\`.`,{hint:{disabled:!0}}),{beginIndex:n,endIndex:r+t.end.length}},
|
|
384
|
+
${py}`,Iy=(e,t,i)=>{let n=e.indexOf(t.begin),r=e.indexOf(t.end);if(n===-1&&r===-1)return;return b(n!==-1&&r!==-1&&n<r,`Malformed Toloka block in ${i}: expected one ${t.begin} followed by one ${t.end}. Repair the file by hand, then re-run \`toloka init\`.`,{hint:{disabled:!0}}),b(!e.includes(t.begin,n+t.begin.length)&&!e.includes(t.end,r+t.end.length),`Multiple Toloka blocks in ${i}: keep exactly one ${t.begin} ... ${t.end} block, then re-run \`toloka init\`.`,{hint:{disabled:!0}}),{beginIndex:n,endIndex:r+t.end.length}},sE=(e,t)=>{let i=Iy(e,jn,t),n=Iy(e,Cc,t);b(i===void 0||n===void 0,`Ambiguous Toloka blocks in ${t}: both ${jn.begin} and ${Cc.begin} are present. Keep one, then re-run \`toloka init\`.`,{hint:{disabled:!0}});let r=e.includes(`\r
|
|
385
385
|
`)?`\r
|
|
386
386
|
`:`
|
|
387
|
-
`,o=
|
|
388
|
-
`,r),s=i??n;if(s!==void 0)return`${e.slice(0,s.beginIndex)}${o}${e.slice(s.endIndex)}`;if(e.length===0)return`${o}${r}`;let a=e.endsWith(`${r}${r}`)?"":e.endsWith(r)?r:`${r}${r}`;return`${e}${a}${o}${r}`},
|
|
389
|
-
`),
|
|
390
|
-
`);return ge([["Training",e.trainingId],["Training rows",String(e.inputs.training.report?.validCount??0)],["Training tokens",String(e.inputs.training.report?.tokens.total??0)],["Maximum GPU seconds",String(e.budget.maximumGpuSeconds)],["Maximum charge",`$${e.maximumCharge} ${e.currency}`],["Fingerprint",e.fingerprint]])},po=async(e,t,i)=>{if(i.startsWith("trg.")){let r=await e.trainings.get({trainingId:i});return b(r.projectId===t,`Training ${i} was not found in project ${t}.`,{hint:{description:"Run toloka training list; a Training belongs to one project."}}),r}let n=[];for await(let r of e.trainings.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return b(n.length===1,`Training ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka training list and pass the training id (trg.\u2026)."}}),n[0]},mE=(e)=>{if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return e.trim()!==""&&Number.isFinite(t)?t:e},Vy=async(e,t,i)=>{if(b(t,"A Dataset is required when specifying a filter.",{hint:{description:"Pass --dataset together with --train-filter, and --validation-dataset together with --validation-filter."}}),i===void 0)return{datasetId:t};let n=i.indexOf("=");b(n>0&&n<i.length-1,"Dataset filters must use FIELD=VALUE syntax.",{hint:{description:"Write the filter as field=value, for example split=train."}});let r=i.slice(0,n),o=i.slice(n+1),s=[];for await(let g of e.datasets.listAllFields({datasetId:t}))if(g.name===r)s.push(g);let[a]=s;return b(a&&s.length===1,`Dataset field ${r} was not found or is ambiguous.`,{hint:{description:"Run toloka dataset fields <dataset> to see the field names."}}),{datasetId:t,itemFilter:{fieldValues:[{fieldId:a.id,jsonPath:"$",operator:"text_eq",value:mE(o),latestOnly:!0,sources:[]}],fieldSources:[],missingRevisionFields:[]}}},pE=(e,t)=>{if(b(!(e.baseModelId&&e.modelVersionId),"Choose exactly one of --base-model and --model-version.",{hint:{disabled:!0}}),e.baseModelId)return{type:"base_model",baseModelId:e.baseModelId};if(e.modelVersionId)return{type:"model_version",modelVersionId:e.modelVersionId};return b(t,"Choose exactly one of --base-model and --model-version.",{hint:{disabled:!0}}),t},AE=async(e,t,i,n)=>{let r=await mo.stat(i);b(r.isFile(),"--prompt-file must point to a file.",{hint:{description:"Pass the absolute path of the prompt text file."}}),b(r.size>0,"The gisting prompt file is empty.",{hint:{description:"Put the full prompt text into the file before creating the Training."}}),b(r.size<=uE,"The gisting prompt file exceeds the 256 KiB limit.",{hint:{description:"Shorten the prompt to under 256 KiB."}});let o=await mo.readFile(i),s;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new F("The gisting prompt file must contain valid UTF-8 text.",{hint:{description:"Save the prompt file as UTF-8 text."}})}b(s.trim().length>0,"The gisting prompt file is empty.",{hint:{description:"Put the full prompt text into the file before creating the Training."}});let a=await e.files.startUpload({projectId:t,filename:By.basename(i),declaredSizeBytes:o.byteLength});try{let g=await n(a.uploadUrl,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/plain; charset=utf-8"},body:o});return b(g.ok,`Failed to upload gisting prompt: HTTP ${g.status}.`,{hint:Tt}),(await e.files.finalizeUpload({projectId:t,fileId:a.file.id})).id}catch(g){throw await e.files.delete({projectId:t,fileId:a.file.id}).catch(()=>{return}),g}},bE=async({client:e,current:t,options:i})=>{let n=i.datasetId??t?.training.datasetId;b(n,"--dataset is required.",{hint:{description:"Pass --dataset <dataset-id>; toloka dataset list shows the ids."}});let r=i.datasetId===void 0&&i.trainingFilter===void 0&&t?t.training:await Vy(e,n,i.trainingFilter),o=i.validationDatasetId===void 0&&i.validationFilter===void 0?t?.validation:await Vy(e,i.validationDatasetId??t?.validation?.datasetId??"",i.validationFilter);return{training:r,validation:o}},Ry=(e)=>({...e.learningRate===void 0?{}:{learningRate:e.learningRate},...e.batchSize===void 0?{}:{batchSize:e.batchSize},...e.maxSequenceLength===void 0?{}:{maxSequenceLength:e.maxSequenceLength}}),ZE=({source:e,selections:t,current:i,options:n})=>(b(n.promptFilePath===void 0,"--prompt-file applies to gisting only.",{hint:{description:"Pass --method gisting to use --prompt-file, or omit --prompt-file for SFT."}}),b(n.gistTokens===void 0,"--gist-tokens applies to gisting; SFT takes --lora-rank.",{hint:{description:"Use --lora-rank for SFT, or pass --method gisting to use --gist-tokens."}}),{...i,method:"sft",source:e,...t,...n.loraRank===void 0?{}:{loraRank:n.loraRank},...n.epochs===void 0?{}:{epochs:n.epochs},...Ry(n)}),hE=async({client:e,projectId:t,source:i,selections:n,current:r,options:o})=>{b(o.loraRank===void 0,"--lora-rank applies to SFT; gisting takes --gist-tokens.",{hint:{description:"Use --gist-tokens for gisting, or omit --method gisting to create SFT."}});let s=o.promptFilePath?await AE(e,t,o.promptFilePath,o.fetch??globalThis.fetch):r?.promptFileId;return b(s,"--prompt-file is required for gisting.",{hint:{description:"Pass --prompt-file <absolute-path> with the prompt text."}}),{...r,method:"gisting",source:i,...n,promptFileId:s,...o.gistTokens===void 0?{}:{gistTokens:o.gistTokens},...o.epochs===void 0?{}:{epochs:o.epochs},...Ry(o)}},Gy=async({client:e,projectId:t,current:i,options:n})=>{let r=pE(n,i?.source),o=await bE({client:e,current:i,options:n});return(n.method??i?.method??"sft")==="sft"?ZE({source:r,selections:o,current:i?.method==="sft"?i:void 0,options:n}):hE({client:e,projectId:t,source:r,selections:o,current:i?.method==="gisting"?i:void 0,options:n})},wy=async(e,t,i)=>{let n=await e.trainings.listPage({projectId:t.projectId,limit:100,offset:0});ie(i,t.json,n.trainings,n.trainings.length===0?"No Trainings found.":ge([["ID","NAME","METHOD","OUTPUT MODEL"],...n.trainings.map((r)=>[r.id,r.name,r.configuration.method==="sft"?"SFT":"GISTING",r.modelId??"-"])]))},Fy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId);ie(i,t.json,n,CE(n))},Hy=async(e,t,i)=>{b(t.datasetId,"--dataset is required.",{hint:{description:"Pass --dataset <dataset-id>; toloka dataset list shows the ids."}}),b(!t.validationFilter||t.validationDatasetId,"--validation-filter requires --validation-dataset.",{hint:{disabled:!0}});let n=await Gy({client:e,projectId:t.projectId,options:t}),r=await e.trainings.create({projectId:t.projectId,name:t.name,configuration:n});ie(i,t.json,r,`Created training ${r.id}`)},vy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=await e.trainings.replaceConfiguration({trainingId:n.id,configuration:await Gy({client:e,projectId:t.projectId,current:n.configuration,options:t})});ie(i,t.json,r,`Updated training ${r.id}`)},ky=async(e,t)=>{let i=await po(e,t.projectId,t.nameOrId),n=await e.trainings.prepareCostEstimateInputs({trainingId:i.id,idempotencyKey:t.idempotencyKey??hc.randomUUID()}),r=[n.exports.training,n.exports.validation].filter((o)=>o!==null);return await Promise.all(r.map((o)=>e.waitFor({type:"datasetExport",exportId:o}))),{training:i,estimate:await e.trainings.estimateCost({trainingId:i.id,inputSetId:n.id})}},Py=async(e,t,i)=>{let{estimate:n}=await ky(e,t);b(n.status==="ready",Zc(n),{hint:{description:"Fix the blocked issues above, then run toloka training cost again."}}),ie(i,t.json,n,Zc(n))},Ny=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=t.estimateFile?yy(JSON.parse(await mo.readFile(t.estimateFile,"utf8"))):await(async()=>{let s=await ky(e,{projectId:t.projectId,nameOrId:t.nameOrId,idempotencyKey:t.idempotencyKey});return b(s.estimate.status==="ready",Zc(s.estimate),{hint:{description:"Fix the blocked issues above, then run toloka training cost again."}}),yy(s.estimate)})();b(r.trainingId===n.id,"The estimate file belongs to another Training.",{hint:{description:"Run toloka training cost <training> --json > <file> for this Training, get its maximumCharge approved, then re-run with that file."}});let o=await e.trainings.createRun({trainingId:n.id,inputSetId:r.inputSetId,estimateFingerprint:r.fingerprint,versionName:t.versionName??n.name,idempotencyKey:t.idempotencyKey??hc.randomUUID()});ie(i,t.json,o,Ra(o))},xy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=await e.trainings.listRunsPage({trainingId:n.id,limit:100,offset:0});ie(i,t.json,r.trainingRuns,r.trainingRuns.length===0?"No Training Runs found.":ge([["ID","STATUS","VERSION","MAXIMUM CHARGE","OUTPUT MODEL VERSION"],...r.trainingRuns.map((o)=>[o.id,o.status,o.outputModelVersionName,`$${o.quote.maximumCharge}`,o.outputModelVersionId])]))},Yy=async(e,t,i)=>{let n=await e.trainings.getRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Sy=async(e,t,i)=>{let n=await e.trainings.resumeRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Xy=async(e,t,i)=>{let n=await e.trainings.cancelRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Ey=async(e,t,i)=>{let n=null;for(;;){let r=await e.trainings.getRunLogs({trainingRunId:t.trainingRunId,cursor:n??void 0,limit:100});for(let o of r.entries)i.stdout(`${o.timestamp} ${o.level.toUpperCase()} ${o.message}`);if(!t.follow||r.complete){if(r.truncated)i.stdout("Training logs were truncated by the server.");return}n=r.nextCursor,await new Promise((o)=>{setTimeout(o,t.pollIntervalMs??1000)})}},Ty=(e)=>{if(e.nonFinite==="nan")return"NaN";if(e.nonFinite==="positive_infinity")return"Infinity";if(e.nonFinite==="negative_infinity")return"-Infinity";return e.value===null?"-":String(e.value)},fE={not_configured:"This Training Run has no metrics: it started before metrics were available, or the server records none.",unresolved:"Metrics are temporarily unreachable. The Training Run itself is unaffected; try again later."},WE=(e)=>{if(!e.available)return e.unavailableReason===null?"No metrics are available for this Training Run.":fE[e.unavailableReason];if(e.metrics.length===0)return"No metrics have been reported yet.";let t=e.metrics.map((n)=>[n.key,n.metric??"-",Ty(n.latest),String(n.latest.step)]),i=ge([["Metric","Meaning","Latest","Step"],...t]);return e.truncated?`${i}
|
|
387
|
+
`,o=nE.replaceAll(`
|
|
388
|
+
`,r),s=i??n;if(s!==void 0)return`${e.slice(0,s.beginIndex)}${o}${e.slice(s.endIndex)}`;if(e.length===0)return`${o}${r}`;let a=e.endsWith(`${r}${r}`)?"":e.endsWith(r)?r:`${r}${r}`;return`${e}${a}${o}${r}`},aE=async(e)=>{if(await pc(Re.join(e,"node_modules",fe)))return!0;let t=await Dn(Re.join(e,"package.json"));if(t===void 0)return!1;let i=JSON.parse(t);return b(typeof i==="object"&&i!==null,"package.json must contain a JSON object.",{hint:{description:"Fix package.json in the source root, then re-run toloka init."}}),["dependencies","devDependencies"].some((n)=>{let r=Reflect.get(i,n);return typeof r==="object"&&r!==null&&typeof Reflect.get(r,fe)==="string"})},gE=async(e,t)=>{if(await Dn(e)===t)return!1;return await Ie.mkdir(Re.dirname(e),{recursive:!0}),await Ie.writeFile(e,t,"utf8"),!0},lE=async(e,t)=>{let i=Re.join(e,t),n=await Dn(i);b(n===void 0||bc(n),`Refusing to overwrite ${i}: it carries no \`<!-- toloka:sdk-version ... -->\` marker, so it is not a pointer generated by ${fe}. Move it aside, then re-run \`toloka init\`.`,{hint:{disabled:!0}})},dE=async(e)=>(await Promise.all(Cy.map(async(i)=>{let n=Re.join(e,i.file);if(await Un(n)===void 0)return;return await uo(e,i.file,"remove legacy agent entry point"),bc(await Ie.readFile(n,"utf8"))?i:void 0}))).filter((i)=>i!==void 0),IE=async(e,t)=>{if(await Ie.rm(Re.join(e,t.file),{force:!0}),t.directory===void 0)return;let i=Re.join(e,t.directory);if((await Ie.readdir(i)).length===0)await Ie.rmdir(i)},cE=(e,t,i,n)=>[`${i.length===0&&n.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${fe} ${oe} in ${e}:`,...t.map((r)=>` ${r}`),...n.map((r)=>` removed ${r} (replaced by the ${Ui} Agent Bootstrap)`)].join(`
|
|
389
|
+
`),uE=async(e,t)=>{if(t===void 0)return;let i=await Ae(e);if(b(i===void 0||i.projectId===t,`This directory is already bound to ${i?.projectId}.`,{hint:{description:"Run toloka init without --project-id to keep the current binding, or remove toloka.json to bind another project."}}),i!==void 0)return;return await ri(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function Ay(e,t={}){await Ie.mkdir(e,{recursive:!0});let i=await Ie.realpath(e),n=Re.join(i,Ui),r=await Dn(n),o=sE(r??"",n),[s,a]=await Promise.all([pc(Re.join(i,".claude")),pc(Re.join(i,".cursor","rules"))]),l=[...s||!s&&!a&&r===void 0?[{relativePath:cy,source:rE}]:[],...a?[{relativePath:uy,source:oE}]:[]],d=[...l,{relativePath:Ui,source:o}];await Promise.all(d.map((Z)=>uo(i,Z.relativePath))),await Promise.all(l.map((Z)=>lE(i,Z.relativePath)));let I=await dE(i),C=await uE(i,t.projectId),m=C===void 0?[]:[C];for(let Z of d)if(await gE(Re.join(i,Z.relativePath),Z.source))m.push(Z.relativePath);for(let Z of I)await IE(i,Z);let A=I.map((Z)=>Z.file),c=await aE(i),u=[...d.map((Z)=>Z.relativePath),...C===void 0?[]:[C]],p=c?void 0:`Warning: ${fe} is not listed in dependencies or devDependencies in ${Re.join(i,"package.json")}. Install it with npm or Bun before authoring pipelines, then re-run \`toloka init\`. Training commands do not require it.`;return{targetDirectory:i,files:u,writtenFiles:m,removedFiles:A,sdkVersion:oe,dependencyReady:c,output:cE(i,u,m,A),...p===void 0?{}:{warning:p}}}async function by(e){let t=[],i=new Set,n=(o,s)=>{t.push(o);let a=mc.exec(s)?.[1];if(a!==void 0)i.add(a)};for(let{file:o}of Cy){let s=await Dn(Re.join(e,o));if(s!==void 0&&bc(s))n(o,s)}for(let o of iE){let s=await Dn(Re.join(e,o));if(s===void 0)continue;let a=mc.exec(s)?.[1];if(s.includes(Cc.begin)||a!==void 0&&a!==oe)n(o,s)}if(t.length===0)return;return`Warning: Agent instructions generated by ${i.size===0?`an earlier ${fe} build`:`${fe} ${[...i].toSorted().join(", ")}`} are out of date (${t.join(", ")}). The installed ${oe} manages one Agent Bootstrap in ${Ui} plus pointer files. Re-run \`toloka init\`.`}var Zy=async(e,t)=>{let i=new AbortController,n,r=(a)=>{n=a,i.abort()},o=()=>r(130),s=()=>r(143);process.on("SIGINT",o),process.on("SIGTERM",s);try{return{result:await t({...e,signal:i.signal}),...n===void 0?{}:{interruptedExitCode:n}}}finally{process.off("SIGINT",o),process.off("SIGTERM",s)}},fy=(e,t)=>{let{context:i,exitCode:n,globals:r}=t,o=i.runChecks??Yd;e.command("init").description("initialize this project directory and install the agent bootstrap").action(async()=>{let s=r(),a=ea(s),g=await Ae(a),l=Fi({flags:s,environment:i.environment,...g===void 0?{}:{state:g}}),d=await Ay(a,l===void 0?{}:{projectId:l.id});if(i.io.stdout(d.output),d.warning!==void 0)i.io.stderr(d.warning)}),e.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(s,a)=>{let{sourceRoot:g,client:l,projectId:d}=await w(r(),i),I=s??d;S(I);let C=await af(l,{sourceRoot:g,projectId:I,...a?.force===!0?{force:!0}:{}});i.io.stdout(C.output)}),e.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:s,client:a,projectId:g}=await w(r(),i),l=await gf(a,{sourceRoot:s,...g===void 0?{}:{projectId:g}});i.io.stdout(l.output)}),e.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:s,client:a,projectId:g}=await w(r(),i),l=await If(a,{sourceRoot:s,...g===void 0?{}:{projectId:g}});if(i.io.stdout(l.output),!l.valid)n.value=1}),e.command("check").argument("[pipeline]","pipeline source directory or name").option("--node <node>","check one code or human-work node by name or id").option("--json","print the structured check report",!1).option("--watch","rerun checks when project files change",!1).description("run the complete local source, type, and test gate").action(async(s,a)=>{let g=await Be(r(),i.io),l={environment:i.environment,sourceRoot:g,...s===void 0?{}:{pipeline:s},...a.node===void 0?{}:{node:a.node},...a.json?{json:!0}:{}},d=async(A)=>{let c=i.environment[ii];if(c===void 0)i.io.stdout(A);else await hy.writeFile(c,A,"utf8")},I=i.runChecks===void 0&&i.environment[ii]===void 0?Sd:o;if(a.watch){let A=new AbortController,c=()=>A.abort();process.on("SIGINT",c),process.on("SIGTERM",c);try{await Pb(l,async(u)=>{await d(u.output),n.value=u.exitCode},void 0,A.signal)}finally{process.off("SIGINT",c),process.off("SIGTERM",c)}return}let{result:C,interruptedExitCode:m}=await Zy(l,I);await d(C.output),n.value=m??C.exitCode}),e.command("apply").description("check source, then make the platform match it").action(async()=>{let s=await Be(r(),i.io),{result:a,interruptedExitCode:g}=await Zy({sourceRoot:s,environment:i.environment},o);if(i.io.stdout(a.output),g!==void 0){n.value=g;return}if(a.exitCode!==0){n.value=a.exitCode;return}b(a.source,"Passing checks must return project source",{hint:P});let{client:l,projectId:d}=await w(r(),i),I=await df(l,{sourceRoot:s,source:a.source,...d===void 0?{}:{projectId:d}});i.io.stdout(I.output)})};var Wy=(e,t)=>{let{context:i,globals:n}=t;e.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:r,client:o,projectId:s}=await w(n(),i);S(s);let a=await lf(o,{sourceRoot:r,projectId:s});i.io.stdout(a.output)})};var By=require("path"),mo=require("fs/promises"),hc=require("crypto");var Co={description:"Regenerate it with toloka training cost <training> --json > <file>."},CE=262144,mE=(e)=>ge([["ID",e.id],["Project",e.projectId],["Method",e.configuration.method==="sft"?"Supervised fine-tuning (SFT)":"Prompt gisting"],e.configuration.method==="sft"?["LoRA rank",String(e.configuration.loraRank)]:["Gist tokens",String(e.configuration.gistTokens)],["Epochs",String(e.configuration.epochs)],["Learning rate",String(e.configuration.learningRate)],["Batch size",String(e.configuration.batchSize)],["Max sequence length",String(e.configuration.maxSequenceLength)],["Output Model",e.modelId??"-"],["Archived at",e.archivedAt??"-"],["Created at",e.createdAt],["Updated at",e.updatedAt]]),Ra=(e)=>ge([["ID",e.id],["Training",e.trainingId],["Status",e.status],["Blocked reason",e.blockedReason??"-"],["Message",e.message??"-"],["Error code",e.error?.code??"-"],["Billing status",e.billingStatus],["Charged amount",e.chargedAmount===null?"-":`$${e.chargedAmount} ${e.quote.currency}`],["Progress",e.progress?`${e.progress.phase}${e.progress.step===null?"":` ${e.progress.step}${e.progress.total===null?"":`/${e.progress.total}`}`}`:"-"],["Model Version name",e.outputModelVersionName],["Model Version revision",e.outputModelVersionRevision===null?"-":String(e.outputModelVersionRevision)],["Future Model Version",e.outputModelVersionId],["Maximum charge",`$${e.quote.maximumCharge} ${e.quote.currency}`],["Created at",e.createdAt]]),yy=(e)=>(b(typeof e==="object"&&e!==null&&!Array.isArray(e),"The estimate file must contain a JSON object.",{hint:Co}),b("status"in e&&e.status==="ready","The estimate file is not a ready Training Cost Estimate.",{hint:Co}),b("trainingId"in e&&typeof e.trainingId==="string","The estimate file has no Training ID.",{hint:Co}),b("inputSetId"in e&&typeof e.inputSetId==="string","The estimate file has no Input Set ID.",{hint:Co}),b("fingerprint"in e&&typeof e.fingerprint==="string"&&/^[0-9a-f]{64}$/.test(e.fingerprint),"The estimate file has no valid fingerprint.",{hint:Co}),{status:"ready",trainingId:e.trainingId,inputSetId:e.inputSetId,fingerprint:e.fingerprint}),Zc=(e)=>{if(e.status==="blocked")return["Training cannot run with these inputs:",...e.issues.map((t)=>`- ${t.message}`)].join(`
|
|
390
|
+
`);return ge([["Training",e.trainingId],["Training rows",String(e.inputs.training.report?.validCount??0)],["Training tokens",String(e.inputs.training.report?.tokens.total??0)],["Maximum GPU seconds",String(e.budget.maximumGpuSeconds)],["Maximum charge",`$${e.maximumCharge} ${e.currency}`],["Fingerprint",e.fingerprint]])},po=async(e,t,i)=>{if(i.startsWith("trg.")){let r=await e.trainings.get({trainingId:i});return b(r.projectId===t,`Training ${i} was not found in project ${t}.`,{hint:{description:"Run toloka training list; a Training belongs to one project."}}),r}let n=[];for await(let r of e.trainings.listAll({projectId:t,limit:100}))if(r.name===i)n.push(r);return b(n.length===1,`Training ${i} was not found or is ambiguous.`,{hint:{description:"Run toloka training list and pass the training id (trg.\u2026)."}}),n[0]},pE=(e)=>{if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return e.trim()!==""&&Number.isFinite(t)?t:e},Vy=async(e,t,i)=>{if(b(t,"A Dataset is required when specifying a filter.",{hint:{description:"Pass --dataset together with --train-filter, and --validation-dataset together with --validation-filter."}}),i===void 0)return{datasetId:t};let n=i.indexOf("=");b(n>0&&n<i.length-1,"Dataset filters must use FIELD=VALUE syntax.",{hint:{description:"Write the filter as field=value, for example split=train."}});let r=i.slice(0,n),o=i.slice(n+1),s=[];for await(let g of e.datasets.listAllFields({datasetId:t}))if(g.name===r)s.push(g);let[a]=s;return b(a&&s.length===1,`Dataset field ${r} was not found or is ambiguous.`,{hint:{description:"Run toloka dataset fields <dataset> to see the field names."}}),{datasetId:t,itemFilter:{fieldValues:[{fieldId:a.id,jsonPath:"$",operator:"text_eq",value:pE(o),latestOnly:!0,sources:[]}],fieldSources:[],missingRevisionFields:[]}}},AE=(e,t)=>{if(b(!(e.baseModelId&&e.modelVersionId),"Choose exactly one of --base-model and --model-version.",{hint:{disabled:!0}}),e.baseModelId)return{type:"base_model",baseModelId:e.baseModelId};if(e.modelVersionId)return{type:"model_version",modelVersionId:e.modelVersionId};return b(t,"Choose exactly one of --base-model and --model-version.",{hint:{disabled:!0}}),t},bE=async(e,t,i,n)=>{let r=await mo.stat(i);b(r.isFile(),"--prompt-file must point to a file.",{hint:{description:"Pass the absolute path of the prompt text file."}}),b(r.size>0,"The gisting prompt file is empty.",{hint:{description:"Put the full prompt text into the file before creating the Training."}}),b(r.size<=CE,"The gisting prompt file exceeds the 256 KiB limit.",{hint:{description:"Shorten the prompt to under 256 KiB."}});let o=await mo.readFile(i),s;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new F("The gisting prompt file must contain valid UTF-8 text.",{hint:{description:"Save the prompt file as UTF-8 text."}})}b(s.trim().length>0,"The gisting prompt file is empty.",{hint:{description:"Put the full prompt text into the file before creating the Training."}});let a=await e.files.startUpload({projectId:t,filename:By.basename(i),declaredSizeBytes:o.byteLength});try{let g=await n(a.uploadUrl,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/plain; charset=utf-8"},body:o});return b(g.ok,`Failed to upload gisting prompt: HTTP ${g.status}.`,{hint:Tt}),(await e.files.finalizeUpload({projectId:t,fileId:a.file.id})).id}catch(g){throw await e.files.delete({projectId:t,fileId:a.file.id}).catch(()=>{return}),g}},ZE=async({client:e,current:t,options:i})=>{let n=i.datasetId??t?.training.datasetId;b(n,"--dataset is required.",{hint:{description:"Pass --dataset <dataset-id>; toloka dataset list shows the ids."}});let r=i.datasetId===void 0&&i.trainingFilter===void 0&&t?t.training:await Vy(e,n,i.trainingFilter),o=i.validationDatasetId===void 0&&i.validationFilter===void 0?t?.validation:await Vy(e,i.validationDatasetId??t?.validation?.datasetId??"",i.validationFilter);return{training:r,validation:o}},Ry=(e)=>({...e.learningRate===void 0?{}:{learningRate:e.learningRate},...e.batchSize===void 0?{}:{batchSize:e.batchSize},...e.maxSequenceLength===void 0?{}:{maxSequenceLength:e.maxSequenceLength}}),hE=({source:e,selections:t,current:i,options:n})=>(b(n.promptFilePath===void 0,"--prompt-file applies to gisting only.",{hint:{description:"Pass --method gisting to use --prompt-file, or omit --prompt-file for SFT."}}),b(n.gistTokens===void 0,"--gist-tokens applies to gisting; SFT takes --lora-rank.",{hint:{description:"Use --lora-rank for SFT, or pass --method gisting to use --gist-tokens."}}),{...i,method:"sft",source:e,...t,...n.loraRank===void 0?{}:{loraRank:n.loraRank},...n.epochs===void 0?{}:{epochs:n.epochs},...Ry(n)}),fE=async({client:e,projectId:t,source:i,selections:n,current:r,options:o})=>{b(o.loraRank===void 0,"--lora-rank applies to SFT; gisting takes --gist-tokens.",{hint:{description:"Use --gist-tokens for gisting, or omit --method gisting to create SFT."}});let s=o.promptFilePath?await bE(e,t,o.promptFilePath,o.fetch??globalThis.fetch):r?.promptFileId;return b(s,"--prompt-file is required for gisting.",{hint:{description:"Pass --prompt-file <absolute-path> with the prompt text."}}),{...r,method:"gisting",source:i,...n,promptFileId:s,...o.gistTokens===void 0?{}:{gistTokens:o.gistTokens},...o.epochs===void 0?{}:{epochs:o.epochs},...Ry(o)}},Gy=async({client:e,projectId:t,current:i,options:n})=>{let r=AE(n,i?.source),o=await ZE({client:e,current:i,options:n});return(n.method??i?.method??"sft")==="sft"?hE({source:r,selections:o,current:i?.method==="sft"?i:void 0,options:n}):fE({client:e,projectId:t,source:r,selections:o,current:i?.method==="gisting"?i:void 0,options:n})},wy=async(e,t,i)=>{let n=await e.trainings.listPage({projectId:t.projectId,limit:100,offset:0});ie(i,t.json,n.trainings,n.trainings.length===0?"No Trainings found.":ge([["ID","NAME","METHOD","OUTPUT MODEL"],...n.trainings.map((r)=>[r.id,r.name,r.configuration.method==="sft"?"SFT":"GISTING",r.modelId??"-"])]))},Fy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId);ie(i,t.json,n,mE(n))},Hy=async(e,t,i)=>{b(t.datasetId,"--dataset is required.",{hint:{description:"Pass --dataset <dataset-id>; toloka dataset list shows the ids."}}),b(!t.validationFilter||t.validationDatasetId,"--validation-filter requires --validation-dataset.",{hint:{disabled:!0}});let n=await Gy({client:e,projectId:t.projectId,options:t}),r=await e.trainings.create({projectId:t.projectId,name:t.name,configuration:n});ie(i,t.json,r,`Created training ${r.id}`)},vy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=await e.trainings.replaceConfiguration({trainingId:n.id,configuration:await Gy({client:e,projectId:t.projectId,current:n.configuration,options:t})});ie(i,t.json,r,`Updated training ${r.id}`)},ky=async(e,t)=>{let i=await po(e,t.projectId,t.nameOrId),n=await e.trainings.prepareCostEstimateInputs({trainingId:i.id,idempotencyKey:t.idempotencyKey??hc.randomUUID()}),r=[n.exports.training,n.exports.validation].filter((o)=>o!==null);return await Promise.all(r.map((o)=>e.waitFor({type:"datasetExport",exportId:o}))),{training:i,estimate:await e.trainings.estimateCost({trainingId:i.id,inputSetId:n.id})}},Py=async(e,t,i)=>{let{estimate:n}=await ky(e,t);b(n.status==="ready",Zc(n),{hint:{description:"Fix the blocked issues above, then run toloka training cost again."}}),ie(i,t.json,n,Zc(n))},Ny=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=t.estimateFile?yy(JSON.parse(await mo.readFile(t.estimateFile,"utf8"))):await(async()=>{let s=await ky(e,{projectId:t.projectId,nameOrId:t.nameOrId,idempotencyKey:t.idempotencyKey});return b(s.estimate.status==="ready",Zc(s.estimate),{hint:{description:"Fix the blocked issues above, then run toloka training cost again."}}),yy(s.estimate)})();b(r.trainingId===n.id,"The estimate file belongs to another Training.",{hint:{description:"Run toloka training cost <training> --json > <file> for this Training, get its maximumCharge approved, then re-run with that file."}});let o=await e.trainings.createRun({trainingId:n.id,inputSetId:r.inputSetId,estimateFingerprint:r.fingerprint,versionName:t.versionName??n.name,idempotencyKey:t.idempotencyKey??hc.randomUUID()});ie(i,t.json,o,Ra(o))},xy=async(e,t,i)=>{let n=await po(e,t.projectId,t.nameOrId),r=await e.trainings.listRunsPage({trainingId:n.id,limit:100,offset:0});ie(i,t.json,r.trainingRuns,r.trainingRuns.length===0?"No Training Runs found.":ge([["ID","STATUS","VERSION","MAXIMUM CHARGE","OUTPUT MODEL VERSION"],...r.trainingRuns.map((o)=>[o.id,o.status,o.outputModelVersionName,`$${o.quote.maximumCharge}`,o.outputModelVersionId])]))},Yy=async(e,t,i)=>{let n=await e.trainings.getRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Sy=async(e,t,i)=>{let n=await e.trainings.resumeRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Xy=async(e,t,i)=>{let n=await e.trainings.cancelRun({trainingRunId:t.trainingRunId});ie(i,t.json,n,Ra(n))},Ey=async(e,t,i)=>{let n=null;for(;;){let r=await e.trainings.getRunLogs({trainingRunId:t.trainingRunId,cursor:n??void 0,limit:100});for(let o of r.entries)i.stdout(`${o.timestamp} ${o.level.toUpperCase()} ${o.message}`);if(!t.follow||r.complete){if(r.truncated)i.stdout("Training logs were truncated by the server.");return}n=r.nextCursor,await new Promise((o)=>{setTimeout(o,t.pollIntervalMs??1000)})}},Ty=(e)=>{if(e.nonFinite==="nan")return"NaN";if(e.nonFinite==="positive_infinity")return"Infinity";if(e.nonFinite==="negative_infinity")return"-Infinity";return e.value===null?"-":String(e.value)},WE={not_configured:"This Training Run has no metrics: it started before metrics were available, or the server records none.",unresolved:"Metrics are temporarily unreachable. The Training Run itself is unaffected; try again later."},yE=(e)=>{if(!e.available)return e.unavailableReason===null?"No metrics are available for this Training Run.":WE[e.unavailableReason];if(e.metrics.length===0)return"No metrics have been reported yet.";let t=e.metrics.map((n)=>[n.key,n.metric??"-",Ty(n.latest),String(n.latest.step)]),i=ge([["Metric","Meaning","Latest","Step"],...t]);return e.truncated?`${i}
|
|
391
391
|
|
|
392
|
-
More metrics exist than the server returns.`:i},
|
|
392
|
+
More metrics exist than the server returns.`:i},VE=(e)=>{let t=ge([["Metric",e.key],["Meaning",e.metric??"-"],["Points",String(e.points.length)]]),i=ge([["Step","Value"],...e.points.map((r)=>[String(r.step),Ty(r)])]),n=e.truncated?`
|
|
393
393
|
|
|
394
394
|
Not every recorded point is shown: the series is thinned to fit --resolution, and a very long run keeps only its most recent points.`:"";return`${t}
|
|
395
395
|
|
|
396
|
-
${i}${n}`},Jy=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunId:t.trainingRunId});ie(i,t.json,n,
|
|
396
|
+
${i}${n}`},Jy=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunId:t.trainingRunId});ie(i,t.json,n,yE(n))},Uy=async(e,t,i)=>{let n=await e.trainings.getRunMetricHistory({trainingRunId:t.trainingRunId,metricKey:t.metricKey,resolution:t.resolution});ie(i,t.json,n,VE(n))};var Oy=(e,t)=>{let{context:i,globals:n}=t,r=e.command("training").description("manage project Training drafts");r.command("list").option("--json","print JSON",!1).description("list active Trainings owned by the selected project").action(async(o)=>{let{client:s,projectId:a}=await w(n(),i);S(a),await wy(s,{projectId:a,json:o.json},i.io)}),r.command("get").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("show one Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Fy(a,{projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("create").argument("<name>","new Training name").option("--method <method>","Training method",hh,"sft").option("--base-model <id>","catalog Base Model source",Sn).option("--model-version <id>","exact Model Version source").requiredOption("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","optional validation Dataset ID").option("--train-filter <field=value>","training Dataset field equality filter").option("--validation-filter <field=value>","validation Dataset field equality filter").option("--lora-rank <rank>","SFT LoRA adapter rank: 8, 16, or 32 (default 16)",CI).option("--gist-tokens <count>",'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',mI).option("--epochs <count>","training epochs, 1 through 5 (default 3)",pI).option("--learning-rate <rate>","optimizer learning rate (default 0.00015 for SFT, 0.03 for gisting)",AI).option("--batch-size <count>","sequences per optimizer step: 8, 16, 32, or 64 (default 8)",bI).option("--max-sequence-length <tokens>","token budget per example, 64 through 16384 (default 12288 for SFT, 3072 for gisting)",ZI).option("--prompt-file <path>","gisting prompt text file").option("--json","print JSON",!1).description("create a normalized Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Hy(a,{...hI(s),projectId:g,name:o,json:s.json},i.io)}),r.command("update").argument("<name-or-id>","Training name or ID").option("--base-model <id>","catalog Base Model source",Sn).option("--model-version <id>","exact Model Version source").option("--dataset <id>","required training Dataset ID").option("--validation-dataset <id>","replacement validation Dataset ID").option("--train-filter <field=value>","replacement training Dataset field equality filter").option("--validation-filter <field=value>","replacement validation Dataset field equality filter").option("--lora-rank <rank>","SFT LoRA adapter rank: 8, 16, or 32 (default 16)",CI).option("--gist-tokens <count>",'gisting soft tokens: 8, 32, or 64, or a fraction of the prompt "1/4", "1/8", "1/16", "1/32" (default "1/8")',mI).option("--epochs <count>","training epochs, 1 through 5 (default 3)",pI).option("--learning-rate <rate>","optimizer learning rate (default 0.00015 for SFT, 0.03 for gisting)",AI).option("--batch-size <count>","sequences per optimizer step: 8, 16, 32, or 64 (default 8)",bI).option("--max-sequence-length <tokens>","token budget per example, 64 through 16384 (default 12288 for SFT, 3072 for gisting)",ZI).option("--prompt-file <path>","replacement gisting prompt text file").option("--json","print JSON",!1).description("replace the complete Training draft").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await vy(a,{...hI(s),projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("cost").argument("<name-or-id>","Training name or ID").option("--idempotency-key <key>","reuse one Cost Estimate input preparation").option("--json","print JSON",!1).description("validate Training inputs and calculate the maximum charge").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Py(a,{projectId:g,nameOrId:o,idempotencyKey:s.idempotencyKey,json:s.json},i.io)}),r.command("run").argument("<name-or-id>","Training name or ID").option("--estimate-file <path>","ready Training Cost Estimate JSON").option("--version-name <name>","unique Model Version name for this run").option("--idempotency-key <key>","reuse one Training Run creation").option("--json","print JSON",!1).description("calculate a ready Cost Estimate and create one queued Training Run").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await Ny(a,{projectId:g,nameOrId:o,...s},i.io)}),r.command("runs").argument("<name-or-id>","Training name or ID").option("--json","print JSON",!1).description("list Training Run history").action(async(o,s)=>{let{client:a,projectId:g}=await w(n(),i);S(g),await xy(a,{projectId:g,nameOrId:o,json:s.json},i.io)}),r.command("status").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("show one Training Run").action(async(o,s)=>{let{client:a}=await w(n(),i);await Yy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("resume").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("resume a Training Run blocked on funds or payment").action(async(o,s)=>{let{client:a}=await w(n(),i);await Sy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("cancel").argument("<training-run-id>","Training Run ID").option("--json","print JSON",!1).description("cancel a Training Run before provider work completes").action(async(o,s)=>{let{client:a}=await w(n(),i);await Xy(a,{trainingRunId:o,json:s.json},i.io)}),r.command("metrics").argument("<training-run-id>","Training Run ID").option("--key <metric>","read the point history of one metric instead of the summary").option("--resolution <count>","history points to return, 2 to 500 (default 200)",Te).option("--json","print JSON",!1).description("read Training Run metrics").action(async(o,s)=>{let{client:a}=await w(n(),i);if(s.key===void 0){await Jy(a,{trainingRunId:o,json:s.json},i.io);return}await Uy(a,{trainingRunId:o,metricKey:s.key,resolution:s.resolution,json:s.json},i.io)}),r.command("logs").argument("<training-run-id>","Training Run ID").option("--follow","wait for new log entries until complete",!1).description("read sanitized Training Run logs").action(async(o,s)=>{let{client:a}=await w(n(),i);await Ey(a,{trainingRunId:o,follow:s.follow},i.io)})};var zy=require("fs"),jy=require("os"),ke=require("path");var BE=`${ke.sep}install${ke.sep}global${ke.sep}`,Ga=(e)=>{try{return zy.realpathSync(e)}catch{return e}},RE=(e,t,i,n)=>{if(Ga(e).includes(BE))return"global-registry";if(Ga(n)===t)return"linked";if(ke.dirname(ke.resolve(e))===ke.resolve(i))return"linked";return"project-local"},Dy=(e=process.argv[1],t={})=>{if(t.native??pi())return{version:oe,commit:"62d9c4558758",channel:"native",path:Ga(t.executablePath??process.execPath)};b(e,"CLI entry path is unavailable",{hint:P});let i=t.globalBinDirectory??ke.resolve(process.env.BUN_INSTALL??ke.join(jy.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??ke.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=ke.resolve(ke.dirname(Ga(e)),".."),o=RE(e,r,i,n);return{version:oe,commit:"62d9c4558758",channel:o,...o==="linked"?{path:r}:{}}};var _y=(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(Dy()):oe))};var Ky=require("readline/promises");var Qy=()=>new F("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."}}),GE=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},wE=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",g),process.stdin.off("error",l),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
|
|
397
397
|
`)},g=()=>{a(),r(Qy())},l=(I)=>{a(),r(I)},d=(I)=>{for(let C of I){if(C==="\r"||C===`
|
|
398
|
-
`){a(),n(o);return}if(C==="\x03"||C==="\x04"){a(),r(C==="\x03"?new F("Canceled.",{hint:{disabled:!0}}):Qy());return}if(C==="\x7F"||C==="\b"){if(o.length>0)o=o.slice(0,-1),process.stdout.write("\b \b");continue}o+=C,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",g),process.stdin.once("error",l);try{return await i}finally{s()}},
|
|
399
|
-
${bh}`).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 g=[];for(let I=a;I!==null;I=I.parent)g.push(I.name());if(g.includes("init")||g.includes("help")||g.includes("report")||g.includes("url")||g.includes("version")||g.includes("config"))return;let l=await Be(r(),e.io),d=await by(l).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),_y(t,o),zh(t,o),Oh(t,o),zW(t,o),Bf(t,o),fh(t,o),fy(t,o),QW(t,o),Yf(t,o),Oy(t,o),yf(t,o),OW(t,o),Wy(t,o),_W(t,o),dy(t,o),{program:t,exitCode:i}}var
|
|
400
|
-
toloka ${oe} does not have it. Run toloka --help to list its commands; a runbook that uses it may need a newer release.`),{code:1,outcome:"usage_error"};try{await e.parseAsync([...i],{from:"user"});let o=t.value;return{code:o,outcome:o===0?"succeeded":"failed"}}catch(o){if(o instanceof Gt){let s=o.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:o}}return n.stderr(Ut(o)),{code:1,outcome:"failed",error:o}}},Ly=async({analytics:e,argv:t,startedAt:i,result:n})=>{if(e===void 0)return;try{e.captureCommand({command:Qo(t),durationMs:Date.now()-i,exitCode:n.code,outcome:n.outcome,...n.error===void 0?{}:{error:n.error}}),await e.shutdown()}catch{}};async function My(e,t=process.env,i=fc(),n,r,o,s,a){let{environment:g,warnings:l}=JC(t);for(let u of l)i.stderr(u);let d=await Xb({argv:e,environment:g,io:i,...s===void 0?{}:{hooks:s}});if(d.status==="reexec")return d.exitCode;let I=g[ii]===void 0?r??bC({environment:g}):void 0,C={environment:g,io:i,...I===void 0?{}:{analytics:I},...n===void 0?{}:{injectedClient:n},...a===void 0?{}:{browserLogin:a},...o===void 0?{}:{runChecks:o}},{program:m,exitCode:A}=
|
|
398
|
+
`){a(),n(o);return}if(C==="\x03"||C==="\x04"){a(),r(C==="\x03"?new F("Canceled.",{hint:{disabled:!0}}):Qy());return}if(C==="\x7F"||C==="\b"){if(o.length>0)o=o.slice(0,-1),process.stdout.write("\b \b");continue}o+=C,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",g),process.stdin.once("error",l);try{return await i}finally{s()}},FE=async(e,t={})=>{if(t.mask===!0)return wE(e);let i=Ky.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await i.question(e)}finally{i.close()}},HE=(e,t)=>ha({message:e,choices:t}),fc=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:GE,style:Rh(process.env,process.stdout.isTTY),...process.stdin.isTTY?{prompt:FE,choose:HE,select:vW}:{}});function vE(e){let t=new Oi("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(oe,"-v, --version","output the current version").option("--source-root <directory>","project root; discovered from the working directory when omitted").option("--api-key <key>","API key for this command only").option("--base-url <url>","platform base URL for this command only").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
|
|
399
|
+
${bh}`).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 g=[];for(let I=a;I!==null;I=I.parent)g.push(I.name());if(g.includes("init")||g.includes("help")||g.includes("report")||g.includes("url")||g.includes("version")||g.includes("config"))return;let l=await Be(r(),e.io),d=await by(l).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),_y(t,o),zh(t,o),Oh(t,o),zW(t,o),Bf(t,o),fh(t,o),fy(t,o),QW(t,o),Yf(t,o),Oy(t,o),yf(t,o),OW(t,o),Wy(t,o),_W(t,o),dy(t,o),{program:t,exitCode:i}}var kE=(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},PE=(e,t)=>{let i=kE(e,t);if(i===void 0||i==="help")return;return e.commands.some((r)=>r.name()===i||r.aliases().includes(i))?void 0:i},NE=async(e,t,i,n)=>{let r=PE(e,i);if(r!==void 0)return n.stderr(`error: unknown command '${r}'
|
|
400
|
+
toloka ${oe} does not have it. Run toloka --help to list its commands; a runbook that uses it may need a newer release.`),{code:1,outcome:"usage_error"};try{await e.parseAsync([...i],{from:"user"});let o=t.value;return{code:o,outcome:o===0?"succeeded":"failed"}}catch(o){if(o instanceof Gt){let s=o.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:o}}return n.stderr(Ut(o)),{code:1,outcome:"failed",error:o}}},Ly=async({analytics:e,argv:t,startedAt:i,result:n})=>{if(e===void 0)return;try{e.captureCommand({command:Qo(t),durationMs:Date.now()-i,exitCode:n.code,outcome:n.outcome,...n.error===void 0?{}:{error:n.error}}),await e.shutdown()}catch{}};async function My(e,t=process.env,i=fc(),n,r,o,s,a){let{environment:g,warnings:l}=JC(t);for(let u of l)i.stderr(u);let d=await Xb({argv:e,environment:g,io:i,...s===void 0?{}:{hooks:s}});if(d.status==="reexec")return d.exitCode;let I=g[ii]===void 0?r??bC({environment:g}):void 0,C={environment:g,io:i,...I===void 0?{}:{analytics:I},...n===void 0?{}:{injectedClient:n},...a===void 0?{}:{browserLogin:a},...o===void 0?{}:{runChecks:o}},{program:m,exitCode:A}=vE(C),c=Date.now();try{let u=await NE(m,A,e,i);return await Ly({analytics:I,argv:e,startedAt:c,result:u}),u.code}catch(u){throw await Ly({analytics:I,argv:e,startedAt:c,result:{code:1,outcome:"failed",error:u}}),u}}My(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
|