@toloka-platform/sdk 0.1.0-preview.3 → 0.1.0-preview.5
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 -2
- package/bin/toloka.js +7 -0
- package/dist/cli/toloka.js +119 -114
- 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/docs/cli-v2.md +4 -0
- package/docs/cli.md +56 -5
- package/docs/getting-started.md +3 -3
- package/docs/limitations.md +1 -1
- package/openapi/gen/api.ts +22 -0
- package/openapi/gen/models/createDatasetBody.ts +2 -0
- package/openapi/gen/models/createDatasetBodyProfile.ts +2 -0
- package/openapi/gen/models/createDatasetUploadBodyFormat.ts +1 -1
- package/openapi/gen/models/dataset.ts +2 -0
- package/openapi/gen/models/datasetProfile.ts +3 -0
- package/openapi/gen/models/datasetProfileStamp.ts +6 -0
- package/openapi/gen/models/datasetProfileStampName.ts +2 -0
- package/openapi/gen/models/index.ts +5 -0
- package/openapi/gen/models/runCost.ts +7 -0
- package/package.json +4 -2
- package/skills/catalog.json +22 -0
- package/skills/{SKILL.md → toloka-build/SKILL.md} +1 -1
- package/skills/{references → toloka-build/references}/workflow-and-cli.md +14 -4
- package/skills/toloka-report-issue/SKILL.md +25 -0
- package/skills/toloka-report-issue/references/report-template.md +34 -0
- package/src/authoring/index.ts +216 -171
- package/src/cli/analytics.ts +53 -1
- package/src/cli/auth.ts +5 -5
- package/src/cli/credentials.ts +8 -2
- package/src/cli/file-system.ts +34 -0
- package/src/cli/format-error.ts +19 -0
- package/src/cli/init.ts +149 -194
- package/src/cli/program.ts +103 -21
- package/src/cli/report.ts +144 -0
- package/src/cli/skill.ts +363 -0
- package/src/pipeline-graph-v1.contract.json +5 -1
- /package/skills/{references → toloka-build/references}/node-semantics.md +0 -0
package/dist/cli/toloka.js
CHANGED
|
@@ -1,167 +1,172 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun @bytecode @bun-cjs
|
|
3
|
-
(function(exports, require, module, __filename, __dirname) {var Qy=Object.create;var{getPrototypeOf:Yy,defineProperty:ks,getOwnPropertyNames:Xy}=Object;var Zy=Object.prototype.hasOwnProperty;function e_(e){return this[e]}var t_,r_,xe=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?t_??=new WeakMap:r_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?Qy(Yy(e)):{};let o=t||!e||!e.__esModule?ks(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Xy(e))if(!Zy.call(o,a))ks(o,a,{get:e_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var i_=(e)=>e;function n_(e,t){this[e]=i_.bind(null,t)}var s_=(e,t)=>{for(var r in t)ks(e,r,{get:t[r],enumerable:!0,configurable:!0,set:n_.bind(t,r)})};var Kr=b(function(M){Object.defineProperty(M,"__esModule",{value:!0});M.regexpCode=M.getEsmExportName=M.getProperty=M.safeStringify=M.stringify=M.strConcat=M.addCodeArg=M.str=M._=M.nil=M._Code=M.Name=M.IDENTIFIER=M._CodeOrName=void 0;class en{}M._CodeOrName=en;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class tr extends en{constructor(e){super();if(!M.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}M.Name=tr;class De extends en{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof tr)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=De;M.nil=new De("");function _d(e,...t){let r=[e[0]],i=0;while(i<t.length)Zs(r,t[i]),r.push(e[++i]);return new De(r)}M._=_d;var Xs=new De("+");function Pd(e,...t){let r=[Vr(e[0])],i=0;while(i<t.length)r.push(Xs),Zs(r,t[i]),r.push(Xs,Vr(e[++i]));return hv(r),new De(r)}M.str=Pd;function Zs(e,t){if(t instanceof De)e.push(...t._items);else if(t instanceof tr)e.push(t);else e.push(_v(t))}M.addCodeArg=Zs;function hv(e){let t=1;while(t<e.length-1){if(e[t]===Xs){let r=gv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function gv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof tr||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof tr))return`"${e}${t.slice(1)}`;return}function yv(e,t){return t.emptyStr()?e:e.emptyStr()?t:Pd`${e}${t}`}M.strConcat=yv;function _v(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Vr(Array.isArray(e)?e.join(","):e)}function Pv(e){return new De(Vr(e))}M.stringify=Pv;function Vr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Vr;function bv(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new De(`.${e}`):_d`[${e}]`}M.getProperty=bv;function vv(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new De(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=vv;function wv(e){return new De(e.toString())}M.regexpCode=wv});var ro=b(function(_e){Object.defineProperty(_e,"__esModule",{value:!0});_e.ValueScope=_e.ValueScopeName=_e.Scope=_e.varKinds=_e.UsedValueState=void 0;var ye=Kr();class bd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var tn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(tn||(_e.UsedValueState=tn={}));_e.varKinds={const:new ye.Name("const"),let:new ye.Name("let"),var:new ye.Name("var")};class eo{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ye.Name?e:this.name(e)}name(e){return new ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}_e.Scope=eo;class to extends ye.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=ye._`.${new ye.Name(t)}[${r}]`}}_e.ValueScopeName=to;var $v=ye._`\n`;class vd extends eo{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$v:ye.nil}}get(){return this._scope}name(e){return new to(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:n}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[n];if(o){let u=o.get(s);if(u)return u}else o=this._values[n]=new Map;o.set(s,i);let a=this._scope[n]||(this._scope[n]=[]),c=a.length;return a[c]=t.ref,i.setValue(t,{property:n,itemIndex:c}),i}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return ye._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(i)=>{if(i.value===void 0)throw Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let n=ye.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((c)=>{if(a.has(c))return;a.set(c,tn.Started);let u=t(c);if(u){let l=this.opts.es5?_e.varKinds.var:_e.varKinds.const;n=ye._`${n}${l} ${c} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(c))n=ye._`${n}${u}${this.opts._n}`;else throw new bd(c);a.set(c,tn.Completed)})}return n}}_e.ValueScope=vd});var F=b(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=Kr(),Ne=ro(),mt=Kr();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return mt._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return mt.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return mt.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return mt.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return mt.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return mt.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return mt.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return mt.Name}});var ln=ro();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return ln.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return ln.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return ln.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return ln.varKinds}});A.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};class ht{optimizeNodes(){return this}optimizeNames(e,t){return this}}class wd extends ht{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?Ne.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ir(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class so extends ht{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ir(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return an(e,this.rhs)}}class $d extends so{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Ed extends ht{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Id extends ht{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Sd extends ht{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class xd extends ht{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ir(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class cn extends ht{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;while(i--){let n=r[i];if(n.optimizeNames(e,t))continue;Ev(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Ct(e,t.names),{})}}class gt extends cn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Rd extends cn{}class zr extends gt{}zr.kind="else";class st extends gt{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new zr(r):r}if(t){if(e===!1)return t instanceof st?t:t.nodes;if(this.nodes.length)return this;return new st(Td(e),t instanceof st?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ir(this.condition,e,t),this}get names(){let e=super.names;if(an(e,this.condition),this.else)Ct(e,this.else.names);return e}}st.kind="if";class rr extends gt{}rr.kind="for";class Cd extends rr{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ir(this.iteration,e,t),this}get names(){return Ct(super.names,this.iteration.names)}}class jd extends rr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?Ne.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=an(super.names,this.from);return an(e,this.to)}}class io extends rr{constructor(e,t,r,i){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ir(this.iterable,e,t),this}get names(){return Ct(super.names,this.iterable.names)}}class rn extends gt{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}rn.kind="func";class nn extends cn{render(e){return"return "+super.render(e)}}nn.kind="return";class Fd extends gt{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)Ct(e,this.catch.names);if(this.finally)Ct(e,this.finally.names);return e}}class sn extends gt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}sn.kind="catch";class on extends gt{render(e){return"finally"+super.render(e)}}on.kind="finally";class Od{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
4
|
-
`:""},this._extScope=e,this._scope=new Ne.Scope({parent:e}),this._nodes=[new Rd]}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 r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}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,r,i){let n=this._scope.toName(t);if(r!==void 0&&i)this._constants[n.str]=r;return this._leafNode(new wd(e,n,r)),n}const(e,t,r){return this._def(Ne.varKinds.const,e,t,r)}let(e,t,r){return this._def(Ne.varKinds.let,e,t,r)}var(e,t,r){return this._def(Ne.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new so(e,t,r))}add(e,t){return this._leafNode(new $d(e,A.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new xd(e));return this}object(...e){let t=["{"];for(let[r,i]of e){if(t.length>1)t.push(",");if(t.push(r),r!==i||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,i)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new st(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new st(e))}else(){return this._elseNode(new zr)}endIf(){return this._endBlockNode(st,zr)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Cd(e),t)}forRange(e,t,r,i,n=this.opts.es5?Ne.varKinds.var:Ne.varKinds.let){let s=this._scope.toName(e);return this._for(new jd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=Ne.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let s=t instanceof N.Name?t:this.var("_arr",t);return this.forRange("_i",0,N._`${s}.length`,(o)=>{this.var(n,N._`${s}[${o}]`),r(n)})}return this._for(new io("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let n=this._scope.toName(e);return this._for(new io("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Ed(e))}break(e){return this._leafNode(new Id(e))}return(e){let t=new nn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(nn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Fd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new sn(n),t(n)}if(r)this._currNode=i.finally=new on,this.code(r);return this._endBlockNode(sn,on)}throw(e){return this._leafNode(new Sd(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 r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=N.nil,r,i){if(this._blockNode(new rn(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(rn)}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 r=this._currNode;if(r instanceof e||t&&r 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 st))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}}A.CodeGen=Od;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function an(e,t){return t instanceof N._CodeOrName?Ct(e,t.names):e}function ir(e,t,r){if(e instanceof N.Name)return i(e);if(!n(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=i(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function i(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function n(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Ev(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Td(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${no(e)}`}A.not=Td;var Iv=Ad(A.operators.AND);function Sv(...e){return e.reduce(Iv)}A.and=Sv;var xv=Ad(A.operators.OR);function Rv(...e){return e.reduce(xv)}A.or=Rv;function Ad(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${no(t)} ${e} ${no(r)}`}function no(e){return e instanceof N.Name?e:N._`(${e})`}});var D=b(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.checkStrictMode=k.getErrorPath=k.Type=k.useFunc=k.setEvaluated=k.evaluatedPropsToName=k.mergeEvaluated=k.eachItem=k.unescapeJsonPointer=k.escapeJsonPointer=k.escapeFragment=k.unescapeFragment=k.schemaRefOrVal=k.schemaHasRulesButRef=k.schemaHasRules=k.checkUnknownRules=k.alwaysValidSchema=k.toHash=void 0;var G=F(),Cv=Kr();function jv(e){let t={};for(let r of e)t[r]=!0;return t}k.toHash=jv;function Fv(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Nd(e,t),!Ld(t,e.self.RULES.all)}k.alwaysValidSchema=Fv;function Nd(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let n=i.RULES.keywords;for(let s in t)if(!n[s])Ud(e,`unknown keyword: "${s}"`)}k.checkUnknownRules=Nd;function Ld(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}k.schemaHasRules=Ld;function Ov(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}k.schemaHasRulesButRef=Ov;function Tv({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(i)}`}k.schemaRefOrVal=Tv;function Av(e){return qd(decodeURIComponent(e))}k.unescapeFragment=Av;function kv(e){return encodeURIComponent(ao(e))}k.escapeFragment=kv;function ao(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}k.escapeJsonPointer=ao;function qd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}k.unescapeJsonPointer=qd;function Dv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}k.eachItem=Dv;function kd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let c=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(n,s,o):t(n,s,o),o):s instanceof G.Name?(t(n,o,s),s):r(s,o);return a===G.Name&&!(c instanceof G.Name)?i(n,c):c}}k.mergeEvaluated={props:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>{e.if(G._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,G._`${r} || {}`).code(G._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,G._`${r} || {}`),lo(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Md}),items:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,G._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>e.assign(r,t===!0?!0:G._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Md(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)lo(e,r,t);return r}k.evaluatedPropsToName=Md;function lo(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}k.setEvaluated=lo;var Dd={};function Nv(e,t){return e.scopeValue("func",{ref:t,code:Dd[t.code]||(Dd[t.code]=new Cv._Code(t.code))})}k.useFunc=Nv;var oo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oo||(k.Type=oo={}));function Lv(e,t,r){if(e instanceof G.Name){let i=t===oo.Num;return r?i?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:i?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+ao(e)}k.getErrorPath=Lv;function Ud(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}k.checkStrictMode=Ud});var Re=b(function(co){Object.defineProperty(co,"__esModule",{value:!0});var ae=F(),qv={data:new ae.Name("data"),valCxt:new ae.Name("valCxt"),instancePath:new ae.Name("instancePath"),parentData:new ae.Name("parentData"),parentDataProperty:new ae.Name("parentDataProperty"),rootData:new ae.Name("rootData"),dynamicAnchors:new ae.Name("dynamicAnchors"),vErrors:new ae.Name("vErrors"),errors:new ae.Name("errors"),this:new ae.Name("this"),self:new ae.Name("self"),scope:new ae.Name("scope"),json:new ae.Name("json"),jsonPos:new ae.Name("jsonPos"),jsonLen:new ae.Name("jsonLen"),jsonPart:new ae.Name("jsonPart")};co.default=qv});var Wr=b(function(le){Object.defineProperty(le,"__esModule",{value:!0});le.extendErrors=le.resetErrorsCount=le.reportExtraError=le.reportError=le.keyword$DataError=le.keywordError=void 0;var L=F(),dn=D(),ue=Re();le.keywordError={message:({keyword:e})=>L.str`must pass "${e}" keyword validation`};le.keyword$DataError={message:({keyword:e,schemaType:t})=>t?L.str`"${e}" keyword must be ${t} ($data)`:L.str`"${e}" keyword is invalid ($data)`};function Mv(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,c=Vd(e,t,r);if(i!==null&&i!==void 0?i:o||a)Bd(s,c);else Gd(n,L._`[${c}]`)}le.reportError=Mv;function Uv(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=Vd(e,t,r);if(Bd(n,a),!(s||o))Gd(i,ue.default.vErrors)}le.reportExtraError=Uv;function Bv(e,t){e.assign(ue.default.errors,t),e.if(L._`${ue.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${ue.default.vErrors}.length`,t),()=>e.assign(ue.default.vErrors,null)))}le.resetErrorsCount=Bv;function Gv({gen:e,keyword:t,schemaValue:r,data:i,errsCount:n,it:s}){if(n===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",n,ue.default.errors,(a)=>{if(e.const(o,L._`${ue.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(ue.default.instancePath,s.errorPath))),e.assign(L._`${o}.schemaPath`,L.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(L._`${o}.schema`,r),e.assign(L._`${o}.data`,i)})}le.extendErrors=Gv;function Bd(e,t){let r=e.const("err",t);e.if(L._`${ue.default.vErrors} === null`,()=>e.assign(ue.default.vErrors,L._`[${r}]`),L._`${ue.default.vErrors}.push(${r})`),e.code(L._`${ue.default.errors}++`)}function Gd(e,t){let{gen:r,validateName:i,schemaEnv:n}=e;if(n.$async)r.throw(L._`new ${e.ValidationError}(${t})`);else r.assign(L._`${i}.errors`,t),r.return(!1)}var jt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function Vd(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Vv(e,t,r)}function Vv(e,t,r={}){let{gen:i,it:n}=e,s=[Kv(n,r),zv(e,r)];return Wv(e,t,s),i.object(...s)}function Kv({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,dn.getErrorPath)(t,dn.Type.Str)}`:e;return[ue.default.instancePath,(0,L.strConcat)(ue.default.instancePath,r)]}function zv({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,dn.getErrorPath)(r,dn.Type.Str)}`;return[jt.schemaPath,n]}function Wv(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;if(i.push([jt.keyword,n],[jt.params,typeof t=="function"?t(e):t||L._`{}`]),c.messages)i.push([jt.message,typeof r=="function"?r(e):r]);if(c.verbose)i.push([jt.schema,o],[jt.parentSchema,L._`${l}${d}`],[ue.default.data,s]);if(u)i.push([jt.propertyName,u])}});var zd=b(function(nr){Object.defineProperty(nr,"__esModule",{value:!0});nr.boolOrEmptySchema=nr.topBoolOrEmptySchema=void 0;var Hv=Wr(),Jv=F(),Qv=Re(),Yv={message:"boolean schema is false"};function Xv(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)Kd(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Qv.default.data);else t.assign(Jv._`${i}.errors`,null),t.return(!0)}nr.topBoolOrEmptySchema=Xv;function Zv(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),Kd(e);else r.var(t,!0)}nr.boolOrEmptySchema=Zv;function Kd(e,t){let{gen:r,data:i}=e,n={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Hv.reportError)(n,Yv,void 0,t)}});var uo=b(function(sr){Object.defineProperty(sr,"__esModule",{value:!0});sr.getRules=sr.isJSONType=void 0;var ew=["string","number","integer","boolean","null","object","array"],tw=new Set(ew);function rw(e){return typeof e=="string"&&tw.has(e)}sr.isJSONType=rw;function iw(){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:{}}}sr.getRules=iw});var po=b(function(yt){Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function nw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&Wd(e,i)}yt.schemaHasRulesForType=nw;function Wd(e,t){return t.rules.some((r)=>Hd(e,r))}yt.shouldUseGroup=Wd;function Hd(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((i)=>e[i]!==void 0))}yt.shouldUseRule=Hd});var Hr=b(function(ce){Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;var sw=uo(),ow=po(),aw=Wr(),O=F(),Jd=D(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ce.DataType=or={}));function lw(e){let t=Qd(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}ce.getSchemaTypes=lw;function Qd(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(sw.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=Qd;function cw(e,t){let{gen:r,data:i,opts:n}=e,s=dw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,ow.schemaHasRulesForType)(e,t[0]));if(o){let a=mo(t,i,n.strictNumbers,or.Wrong);r.if(a,()=>{if(s.length)uw(e,t,s);else ho(e)})}return o}ce.coerceAndCheckDataType=cw;var Yd=new Set(["string","number","integer","boolean","null"]);function dw(e,t){return t?e.filter((r)=>Yd.has(r)||t==="array"&&r==="array"):[]}function uw(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",O._`typeof ${n}`),a=i.let("coerced",O._`undefined`);if(s.coerceTypes==="array")i.if(O._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,O._`${n}[0]`).assign(o,O._`typeof ${n}`).if(mo(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(O._`${a} !== undefined`);for(let u of r)if(Yd.has(u)||u==="array"&&s.coerceTypes==="array")c(u);i.else(),ho(e),i.endIf(),i.if(O._`${a} !== undefined`,()=>{i.assign(n,a),pw(e,a)});function c(u){switch(u){case"string":i.elseIf(O._`${o} == "number" || ${o} == "boolean"`).assign(a,O._`"" + ${n}`).elseIf(O._`${n} === null`).assign(a,O._`""`);return;case"number":i.elseIf(O._`${o} == "boolean" || ${n} === null
|
|
5
|
-
|| (${o} == "string" && ${n} && ${n} == +${n})`).assign(a,
|
|
6
|
-
|| (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,
|
|
7
|
-
|| ${o} === "boolean" || ${n} === null`).assign(a,O._`[${n}]`)}}}function pw({gen:e,parentData:t,parentDataProperty:r},i){e.if(O._`${t} !== undefined`,()=>e.assign(O._`${t}[${r}]`,i))}function fo(e,t,r,i=or.Correct){let n=i===or.Correct?O.operators.EQ:O.operators.NEQ,s;switch(e){case"null":return O._`${t} ${n} null`;case"array":s=O._`Array.isArray(${t})`;break;case"object":s=O._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(O._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return O._`typeof ${t} ${n} ${e}`}return i===or.Correct?s:(0,O.not)(s);function o(a=O.nil){return(0,O.and)(O._`typeof ${t} == "number"`,a,r?O._`isFinite(${t})`:O.nil)}}ce.checkDataType=fo;function mo(e,t,r,i){if(e.length===1)return fo(e[0],t,r,i);let n,s=(0,Jd.toHash)(e);if(s.array&&s.object){let o=O._`typeof ${t} != "object"`;n=s.null?o:O._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=O.nil;if(s.number)delete s.integer;for(let o in s)n=(0,O.and)(n,fo(o,t,r,i));return n}ce.checkDataTypes=mo;var fw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?O._`{type: ${e}}`:O._`{type: ${t}}`};function ho(e){let t=mw(e);(0,aw.reportError)(t,fw)}ce.reportTypeError=ho;function mw(e){let{gen:t,data:r,schema:i}=e,n=(0,Jd.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var Zd=b(function(un){Object.defineProperty(un,"__esModule",{value:!0});un.assignDefaults=void 0;var ar=F(),hw=D();function gw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)Xd(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>Xd(e,s,n.default))}un.assignDefaults=gw;function Xd(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=ar._`${s}${(0,ar.getProperty)(t)}`;if(n){(0,hw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=ar._`${a} === undefined`;if(o.useDefaults==="empty")c=ar._`${c} || ${a} === null || ${a} === ""`;i.if(c,ar._`${a} = ${(0,ar.stringify)(r)}`)}});var Ce=b(function(B){Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var K=F(),go=D(),_t=Re(),yw=D();function _w(e,t){let{gen:r,data:i,it:n}=e;r.if(_o(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=_w;function Pw({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(_o(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=Pw;function bw(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=bw;function eu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=eu;function yo(e,t,r){return K._`${eu(e)}.call(${t}, ${r})`}B.isOwnProperty=yo;function vw(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${yo(e,t,r)}`:n}B.propertyInData=vw;function _o(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(yo(e,t,r))):n}B.noPropertyInData=_o;function tu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=tu;function ww(e,t){return tu(t).filter((r)=>!(0,go.alwaysValidSchema)(e,t[r]))}B.schemaProperties=ww;function $w({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,c,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,d=[[_t.default.instancePath,(0,K.strConcat)(_t.default.instancePath,s)],[_t.default.parentData,o.parentData],[_t.default.parentDataProperty,o.parentDataProperty],[_t.default.rootData,_t.default.rootData]];if(o.opts.dynamicRef)d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...d)}`;return c!==K.nil?K._`${a}.call(${c}, ${p})`:K._`${a}(${p})`}B.callValidateCode=$w;var Ew=K._`new RegExp`;function Iw({gen:e,it:{opts:t}},r){let i=t.unicodeRegExp?"u":"",{regExp:n}=t.code,s=n(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${n.code==="new RegExp"?Ew:(0,yw.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=Iw;function Sw(e){let{gen:t,data:r,keyword:i,it:n}=e,s=t.name("valid");if(n.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",K._`${r}.length`);t.forRange("i",0,c,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:go.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=Sw;function xw(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>(0,go.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:i,schemaProp:u,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(l,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=xw});var nu=b(function(Ve){Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateKeywordUsage=Ve.validSchemaType=Ve.funcKeywordCode=Ve.macroKeywordCode=void 0;var pe=F(),Ft=Re(),Rw=Ce(),Cw=Wr();function jw(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),c=iu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:pe.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ve.macroKeywordCode=jw;function Fw(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:c}=e;Tw(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,l=iu(i,n,u),d=i.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1){if(h(),t.modifying)ru(e);g(()=>e.error())}else{let y=t.async?f():m();if(t.modifying)ru(e);g(()=>Ow(e,y))}}function f(){let y=i.let("ruleErrs",null);return i.try(()=>h(pe._`await `),(P)=>i.assign(d,!1).if(pe._`${P} instanceof ${c.ValidationError}`,()=>i.assign(y,pe._`${P}.errors`),()=>i.throw(P))),y}function m(){let y=pe._`${l}.errors`;return i.assign(y,null),h(pe.nil),y}function h(y=t.async?pe._`await `:pe.nil){let P=c.opts.passContext?Ft.default.this:Ft.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(d,pe._`${y}${(0,Rw.callValidateCode)(e,l,P,v)}`,t.modifying)}function g(y){var P;i.if((0,pe.not)((P=t.valid)!==null&&P!==void 0?P:d),y)}}Ve.funcKeywordCode=Fw;function ru(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,pe._`${i.parentData}[${i.parentDataProperty}]`))}function Ow(e,t){let{gen:r}=e;r.if(pe._`Array.isArray(${t})`,()=>{r.assign(Ft.default.vErrors,pe._`${Ft.default.vErrors} === null ? ${t} : ${Ft.default.vErrors}.concat(${t})`).assign(Ft.default.errors,pe._`${Ft.default.vErrors}.length`),(0,Cw.extendErrors)(e)},()=>e.error())}function Tw({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function iu(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,pe.stringify)(r)})}function Aw(e,t,r=!1){return!t.length||t.some((i)=>i==="array"?Array.isArray(e):i==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==i||r&&typeof e>"u")}Ve.validSchemaType=Aw;function kw({schema:e,opts:t,self:r,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw Error("ajv implementation error");let o=n.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}Ve.validateKeywordUsage=kw});var ou=b(function(Pt){Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendSubschemaMode=Pt.extendSubschemaData=Pt.getSubschema=void 0;var Ke=F(),su=D();function Dw(e,{keyword:t,schemaProp:r,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&i!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}${(0,Ke.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,su.escapeFragment)(r)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}Pt.getSubschema=Dw;function Nw(e,t,{dataProp:r,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",Ke._`${t.data}${(0,Ke.getProperty)(r)}`,!0);c(p),e.errorPath=Ke.str`${u}${(0,su.getErrorPath)(r,i,d.jsPropertySyntax)}`,e.parentDataProperty=Ke._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Ke.Name?n:a.let("data",n,!0);if(c(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}Pt.extendSubschemaData=Nw;function Lw(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:n,allErrors:s}){if(i!==void 0)e.compositeRule=i;if(n!==void 0)e.createErrors=n;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}Pt.extendSubschemaMode=Lw});var Po=b(function(gA,au){au.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if(i=t.length,i!=r.length)return!1;for(n=i;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),i=s.length,i!==Object.keys(r).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var cu=b(function(yA,lu){var bt=lu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var i=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};pn(t,i,n,e,"",e)};bt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bt.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 pn(e,t,r,i,n,s,o,a,c,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,c,u);for(var l in i){var d=i[l];if(Array.isArray(d)){if(l in bt.arrayKeywords)for(var p=0;p<d.length;p++)pn(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in bt.propsKeywords){if(d&&typeof d=="object")for(var f in d)pn(e,t,r,d[f],n+"/"+l+"/"+qw(f),s,n,l,i,f)}else if(l in bt.keywords||e.allKeys&&!(l in bt.skipKeywords))pn(e,t,r,d,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,c,u)}}function qw(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Jr=b(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getSchemaRefs=Pe.resolveUrl=Pe.normalizeId=Pe._getFullPath=Pe.getFullPath=Pe.inlineRef=void 0;var Mw=D(),Uw=Po(),Bw=cu(),Gw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Vw(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!bo(e);if(!t)return!1;return du(e)<=t}Pe.inlineRef=Vw;var Kw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bo(e){for(let t in e){if(Kw.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(bo))return!0;if(typeof r=="object"&&bo(r))return!0}return!1}function du(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,Gw.has(r))continue;if(typeof e[r]=="object")(0,Mw.eachItem)(e[r],(i)=>t+=du(i));if(t===1/0)return 1/0}return t}function uu(e,t="",r){if(r!==!1)t=lr(t);let i=e.parse(t);return pu(e,i)}Pe.getFullPath=uu;function pu(e,t){return e.serialize(t).split("#")[0]+"#"}Pe._getFullPath=pu;var zw=/#\/?$/;function lr(e){return e?e.replace(zw,""):""}Pe.normalizeId=lr;function Ww(e,t,r){return r=lr(r),e.resolve(t,r)}Pe.resolveUrl=Ww;var Hw=/^[a-z_][-a-z0-9._]*$/i;function Jw(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=lr(e[r]||t),s={"":n},o=uu(i,n,!1),a={},c=new Set;return Bw(e,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof d[r]=="string")g=y.call(this,d[r]);P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[p]=g;function y(v){let w=this.opts.uriResolver.resolve;if(v=lr(g?w(g,v):v),c.has(v))throw l(v);c.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(d,I.schema,v);else if(v!==lr(h))if(v[0]==="#")u(d,a[v],v),a[v]=d;else this.refs[v]=h;return v}function P(v){if(typeof v=="string"){if(!Hw.test(v))throw Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Uw(d,p))throw l(f)}function l(d){return Error(`reference "${d}" resolves to more than one schema`)}}Pe.getSchemaRefs=Jw});var cr=b(function(vt){Object.defineProperty(vt,"__esModule",{value:!0});vt.getData=vt.KeywordCxt=vt.validateFunctionCode=void 0;var yu=zd(),fu=Hr(),wo=po(),fn=Hr(),Qw=Zd(),Yr=nu(),vo=ou(),S=F(),j=Re(),Yw=Jr(),ot=D(),Qr=Wr();function Xw(e){if(bu(e)){if(vu(e),Pu(e)){t$(e);return}}_u(e,()=>(0,yu.topBoolOrEmptySchema)(e))}vt.validateFunctionCode=Xw;function _u({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${j.default.data}, ${j.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${mu(r,n)}`),e$(e,n),e.code(s)});else e.func(t,S._`${j.default.data}, ${Zw(n)}`,i.$async,()=>e.code(mu(r,n)).code(s))}function Zw(e){return S._`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?S._`, ${j.default.dynamicAnchors}={}`:S.nil}}={}`}function e$(e,t){e.if(j.default.valCxt,()=>{if(e.var(j.default.instancePath,S._`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,S._`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,S._`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,S._`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{if(e.var(j.default.instancePath,S._`""`),e.var(j.default.parentData,S._`undefined`),e.var(j.default.parentDataProperty,S._`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`{}`)})}function t$(e){let{schema:t,opts:r,gen:i}=e;_u(e,()=>{if(r.$comment&&t.$comment)$u(e);if(o$(e),i.let(j.default.vErrors,null),i.let(j.default.errors,0),r.unevaluated)r$(e);wu(e),c$(e)});return}function r$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",S._`${r}.evaluated`),t.if(S._`${e.evaluated}.dynamicProps`,()=>t.assign(S._`${e.evaluated}.props`,S._`undefined`)),t.if(S._`${e.evaluated}.dynamicItems`,()=>t.assign(S._`${e.evaluated}.items`,S._`undefined`))}function mu(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function i$(e,t){if(bu(e)){if(vu(e),Pu(e)){n$(e,t);return}}(0,yu.boolOrEmptySchema)(e,t)}function Pu({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function bu(e){return typeof e.schema!="boolean"}function n$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)$u(e);a$(e),l$(e);let s=i.const("_errs",j.default.errors);wu(e,s),i.var(t,S._`${s} === ${j.default.errors}`)}function vu(e){(0,ot.checkUnknownRules)(e),s$(e)}function wu(e,t){if(e.opts.jtd)return hu(e,[],!1,t);let r=(0,fu.getSchemaTypes)(e.schema),i=(0,fu.coerceAndCheckDataType)(e,r);hu(e,r,!i,t)}function s$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function o$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,ot.checkStrictMode)(e,"default is ignored in the schema root")}function a$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,Yw.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function l$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function $u({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${j.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=S.str`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${j.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function c$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw(S._`new ${n}(${j.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,j.default.vErrors),s.unevaluated)d$(e);t.return(S._`${j.default.errors} === 0`)}}function d$({gen:e,evaluated:t,props:r,items:i}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(i instanceof S.Name)e.assign(S._`${t}.items`,i)}function hu(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(s,l))){n.block(()=>Iu(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)u$(e,t);n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){if(!(0,wo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,fn.checkDataType)(p.type,o,c.strictNumbers)),gu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,fn.reportTypeError)(e);n.endIf()}else gu(e,p);if(!a)n.if(S._`${j.default.errors} === ${i||0}`)}}function gu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,Qw.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,wo.shouldUseRule)(i,s))Iu(e,s.keyword,s.definition,t.type)})}function u$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(p$(e,t),!e.opts.allowUnionTypes)f$(e,t);m$(e,e.dataTypes)}function p$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Eu(e.dataTypes,r))$o(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),g$(e,t)}function f$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))$o(e,"use allowUnionTypes to allow union type keyword")}function m$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,wo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>h$(t,o)))$o(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function h$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Eu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function g$(e,t){let r=[];for(let i of e.dataTypes)if(Eu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function $o(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ot.checkStrictMode)(e,t,e.opts.strictTypes)}class Eo{constructor(e,t,r){if((0,Yr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ot.schemaRefOrVal)(e,this.schema,r,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",Su(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Yr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",j.default.errors)}result(e,t,r){this.failResult((0,S.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();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,S.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(S._`${t} !== undefined && (${(0,S.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?Qr.reportExtraError:Qr.reportError)(this,this.def.error,t)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Qr.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,r=S.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=S.nil,t=S.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:n,def:s}=this;if(r.if((0,S.or)(S._`${i} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(n.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:n}=this;return(0,S.or)(s(),o());function s(){if(r.length){if(!(t instanceof S.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return S._`${(0,fn.checkDataTypes)(a,t,n.opts.strictNumbers,fn.DataType.Wrong)}`}return S.nil}function o(){if(i.validateSchema){let a=e.scopeValue("validate$data",{ref:i.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,vo.getSubschema)(this.it,e);(0,vo.extendSubschemaData)(r,this.it,e),(0,vo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return i$(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=ot.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=ot.mergeEvaluated.items(i,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}vt.KeywordCxt=Eo;function Iu(e,t,r,i){let n=new Eo(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,Yr.funcKeywordCode)(n,r);else if("macro"in r)(0,Yr.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,Yr.funcKeywordCode)(n,r)}var y$=/^\/(?:[^~]|~0|~1)*$/,_$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Su(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!y$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=j.default.rootData}else{let u=_$.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(c("property/index",l));return i[t-l]}if(l>t)throw Error(c("data",l));if(s=r[t-l],!n)return s}let o=s,a=n.split("/");for(let u of a)if(u)s=S._`${s}${(0,S.getProperty)((0,ot.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}vt.getData=Su});var Xr=b(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});class xu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Io.default=xu});var dr=b(function(xo){Object.defineProperty(xo,"__esModule",{value:!0});var So=Jr();class Ru extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,So.resolveUrl)(e,t,r),this.missingSchema=(0,So.normalizeId)((0,So.getFullPath)(e,this.missingRef))}}xo.default=Ru});var ei=b(function(je){Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Le=F(),P$=Xr(),Ot=Re(),qe=Jr(),Cu=D(),b$=cr();class Zr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=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,qe.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}je.SchemaEnv=Zr;function Co(e){let t=ju.call(this,e);if(t)return t;let r=(0,qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Le.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:P$.default,code:Le._`require("ajv/dist/runtime/validation_error").default`});let c=o.scopeName("validate");e.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Ot.default.data,parentData:Ot.default.parentData,parentDataProperty:Ot.default.parentDataProperty,dataNames:[Ot.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Le._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,b$.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();if(l=`${o.scopeRefs(Ot.default.scope)}return ${d}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Ot.default.self}`,`${Ot.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:c,validateCode:d,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Le.Name?void 0:m,items:h instanceof Le.Name?void 0:h,dynamicProps:m instanceof Le.Name,dynamicItems:h instanceof Le.Name},f.source)f.source.evaluated=(0,Le.stringify)(f.evaluated)}return e.validate=f,e}catch(d){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw d}finally{this._compilations.delete(e)}}je.compileSchema=Co;function v$(e,t,r){var i;r=(0,qe.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=E$.call(this,e,r);if(s===void 0){let o=(i=e.localRefs)===null||i===void 0?void 0:i[r],{schemaId:a}=this.opts;if(o)s=new Zr({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=w$.call(this,s)}je.resolveRef=v$;function w$(e){if((0,qe.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Co.call(this,e)}function ju(e){for(let t of this._compilations)if($$(t,e))return t}je.getCompilingSchema=ju;function $$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function E$(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||mn.call(this,e,t)}function mn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,qe._getFullPath)(this.opts.uriResolver,r),n=(0,qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return Ro.call(this,r,e);let s=(0,qe.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=mn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Ro.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Co.call(this,o);if(s===(0,qe.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];if(u)n=(0,qe.resolveUrl)(this.opts.uriResolver,n,u);return new Zr({schema:a,schemaId:c,root:e,baseId:n})}return Ro.call(this,r,o)}je.resolveSchema=mn;var I$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ro(e,{baseId:t,schema:r,root:i}){var n;if(((n=e.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[(0,Cu.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r==="object"&&r[this.opts.schemaId];if(!I$.has(a)&&u)t=(0,qe.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cu.schemaHasRulesButRef)(r,this.RULES)){let a=(0,qe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=mn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new Zr({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Fu=b(function($A,S$){S$.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 Fo=b(function(EA,ku){var x$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tu=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 jo(e){let t="",r=0,i=0;for(i=0;i<e.length;i++){if(r=e[i].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i];break}for(i+=1;i<e.length;i++){if(r=e[i].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i]}return t}var R$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ou(e){return e.length=0,!0}function C$(e,t,r){if(e.length){let i=jo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function j$(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=C$;for(let c=0;c<e.length;c++){let u=e[c];if(u==="["||u==="]")continue;if(u===":"){if(s===!0)o=!0;if(!a(n,i,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Ou}else{n.push(u);continue}}if(n.length)if(a===Ou)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(jo(n));return r.address=i.join(""),r}function Au(e){if(F$(e,":")<2)return{host:e,isIPV6:!1};let t=j$(e);if(!t.error){let{address:r,address:i}=t;if(t.zone)r+="%"+t.zone,i+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:i}}else return{host:e,isIPV6:!1}}function F$(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function O$(e){let t=e,r=[],i=-1,n=0;while(n=t.length){if(n===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(n===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]==="/"){r.push("/");break}}}else if(n===3){if(t==="/.."){if(r.length!==0)r.pop();r.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),r.length!==0)r.pop();continue}}}}if((i=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,i)),t=t.slice(i)}return r.join("")}function T$(e,t){let r=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=r(e.scheme);if(e.userinfo!==void 0)e.userinfo=r(e.userinfo);if(e.host!==void 0)e.host=r(e.host);if(e.path!==void 0)e.path=r(e.path);if(e.query!==void 0)e.query=r(e.query);if(e.fragment!==void 0)e.fragment=r(e.fragment);return e}function A$(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!Tu(r)){let i=Au(r);if(i.isIPV6===!0)r=`[${i.escapedHost}]`;else r=e.host}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}ku.exports={nonSimpleDomain:R$,recomposeAuthority:A$,normalizeComponentEncoding:T$,removeDotSegments:O$,isIPv4:Tu,isUUID:x$,normalizeIPv6:Au,stringArrayToHexStripped:jo}});var Mu=b(function(IA,qu){var{isUUID:k$}=Fo(),D$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,N$=["http","https","ws","wss","urn","urn:uuid"];function L$(e){return N$.indexOf(e)!==-1}function Oo(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 Du(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Nu(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 q$(e){return e.secure=Oo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function M$(e){if(e.port===(Oo(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,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function U$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(D$);if(r){let i=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let n=`${i}:${t.nid||e.nid}`,s=To(n);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function B$(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),n=`${r}:${t.nid||i}`,s=To(n);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${i||t.nid}:${a}`,t.skipEscape=!0,o}function G$(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!k$(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function V$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Lu={scheme:"http",domainHost:!0,parse:Du,serialize:Nu},K$={scheme:"https",domainHost:Lu.domainHost,parse:Du,serialize:Nu},hn={scheme:"ws",domainHost:!0,parse:q$,serialize:M$},z$={scheme:"wss",domainHost:hn.domainHost,parse:hn.parse,serialize:hn.serialize},W$={scheme:"urn",parse:U$,serialize:B$,skipNormalize:!0},H$={scheme:"urn:uuid",parse:G$,serialize:V$,skipNormalize:!0},gn={http:Lu,https:K$,ws:hn,wss:z$,urn:W$,"urn:uuid":H$};Object.setPrototypeOf(gn,null);function To(e){return e&&(gn[e]||gn[e.toLowerCase()])||void 0}qu.exports={wsIsSecure:Oo,SCHEMES:gn,isValidSchemeName:L$,getSchemeHandler:To}});var Gu=b(function(SA,_n){var{normalizeIPv6:J$,removeDotSegments:ti,recomposeAuthority:Q$,normalizeComponentEncoding:yn,isIPv4:Y$,nonSimpleDomain:X$}=Fo(),{SCHEMES:Z$,getSchemeHandler:Uu}=Mu();function eE(e,t){if(typeof e==="string")e=ze(at(e,t),t);else if(typeof e==="object")e=at(ze(e,t),t);return e}function tE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Bu(at(e,i),at(t,i),i,!0);return i.skipEscape=!0,ze(n,i)}function Bu(e,t,r,i){let n={};if(!i)e=at(ze(e,r),r),t=at(ze(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(!t.path)if(n.path=e.path,t.query!==void 0)n.query=t.query;else n.query=e.query;else{if(t.path[0]==="/")n.path=ti(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)n.path="/"+t.path;else if(!e.path)n.path=t.path;else n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;n.path=ti(n.path)}n.query=t.query}n.userinfo=e.userinfo,n.host=e.host,n.port=e.port}n.scheme=e.scheme}return n.fragment=t.fragment,n}function rE(e,t,r){if(typeof e==="string")e=unescape(e),e=ze(yn(at(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=ze(yn(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ze(yn(at(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=ze(yn(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ze(e,t){let r={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:""},i=Object.assign({},t),n=[],s=Uu(i.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,i);if(r.path!==void 0)if(!i.skipEscape){if(r.path=escape(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=unescape(r.path);if(i.reference!=="suffix"&&r.scheme)n.push(r.scheme,":");let o=Q$(r);if(o!==void 0){if(i.reference!=="suffix")n.push("//");if(n.push(o),r.path&&r.path[0]!=="/")n.push("/")}if(r.path!==void 0){let a=r.path;if(!i.absolutePath&&(!s||!s.absolutePath))a=ti(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);n.push(a)}if(r.query!==void 0)n.push("?",r.query);if(r.fragment!==void 0)n.push("#",r.fragment);return n.join("")}var iE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function at(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(iE);if(s){if(i.scheme=s[1],i.userinfo=s[3],i.host=s[4],i.port=parseInt(s[5],10),i.path=s[6]||"",i.query=s[7],i.fragment=s[8],isNaN(i.port))i.port=s[5];if(i.host)if(Y$(i.host)===!1){let c=J$(i.host);i.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;if(i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path)i.reference="same-document";else if(i.scheme===void 0)i.reference="relative";else if(i.fragment===void 0)i.reference="absolute";else i.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==i.reference)i.error=i.error||"URI is not a "+r.reference+" reference.";let o=Uu(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&X$(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(a){i.error=i.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(i.scheme!==void 0)i.scheme=unescape(i.scheme);if(i.host!==void 0)i.host=unescape(i.host)}if(i.path)i.path=escape(unescape(i.path));if(i.fragment)i.fragment=encodeURI(decodeURIComponent(i.fragment))}if(o&&o.parse)o.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}var Ao={SCHEMES:Z$,normalize:eE,resolve:tE,resolveComponent:Bu,equal:rE,serialize:ze,parse:at};_n.exports=Ao;_n.exports.default=Ao;_n.exports.fastUri=Ao});var Ku=b(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});var Vu=Gu();Vu.code='require("ajv/dist/runtime/uri").default';ko.default=Vu});var Lo=b(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var nE=cr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return nE.KeywordCxt}});var ur=F();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var sE=Xr(),Qu=dr(),oE=uo(),ri=ei(),aE=F(),ii=Jr(),Pn=Hr(),No=D(),zu=Fu(),lE=Ku(),Yu=(e,t)=>new RegExp(e,t);Yu.code="new RegExp";var cE=["removeAdditional","useDefaults","coerceTypes"],dE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uE={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."},pE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wu=200;function fE(e){var t,r,i,n,s,o,a,c,u,l,d,p,f,m,h,g,y,P,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,X=J===!0||J===void 0?1:J||0,Se=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:Yu,qr=(n=e.uriResolver)!==null&&n!==void 0?n:lE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:V)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:V)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:X,regExp:Se}:{optimize:X,regExp:Se},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Wu,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Wu,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(P=e.messages)!==null&&P!==void 0?P:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(x=e.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(R=e.int32range)!==null&&R!==void 0?R:!0,uriResolver:qr}}class bn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...fE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new aE.ValueScope({scope:{},prefixes:dE,es5:t,lines:r}),this.logger=PE(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,oE.getRules)(),Hu.call(this,uE,e,"NOT SUPPORTED"),Hu.call(this,pE,e,"DEPRECATED","warn"),this._metaOpts=yE.call(this),e.formats)hE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)gE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);mE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=zu;if(r==="id")i={...zu},i.id=i.$id,delete i.$id;if(t&&e)this.addMetaSchema(i,i[r],!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 r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);if(!("$async"in r))this.errors=r.errors;return i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(u,l){await n.call(this,u.$schema);let d=this._addSchema(u,l);return d.validate||s.call(this,d)}async function n(u){if(u&&!this.getSchema(u))await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(l){if(!(l instanceof Qu.default))throw l;return o.call(this,l),await a.call(this,l.missingSchema),s.call(this,u)}}function o({missingSchema:u,missingRef:l}){if(this.refs[u])throw Error(`AnySchema ${u} is loaded but ${l} cannot be resolved`)}async function a(u){let l=await c.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function c(u){let l=this._loading[u];if(l)return l;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let n;if(typeof e==="object"){let{schemaId:s}=this.opts;if(n=e[s],n!==void 0&&typeof n!="string")throw Error(`schema ${s} must be string`)}return t=(0,ii.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(r,e);if(!i&&t){let n="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(n);else throw Error(n)}return i}getSchema(e){let t;while(typeof(t=Ju.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ri.SchemaEnv({schema:{},schemaId:r});if(t=ri.resolveSchema.call(this,i,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=Ju.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 r=e[this.opts.schemaId];if(r)r=(0,ii.normalizeId)(r),delete this.schemas[r],delete this.refs[r];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 r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(vE.call(this,r,t),!t)return(0,No.eachItem)(r,(n)=>Do.call(this,n)),this;$E.call(this,t);let i={...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)};return(0,No.eachItem)(r,i.type.length===0?(n)=>Do.call(this,n,i):(n)=>i.type.forEach((s)=>Do.call(this,n,i,s))),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 r of t.rules){let i=r.rules.findIndex((n)=>n.keyword===e);if(i>=0)r.rules.splice(i,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:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((i)=>`${r}${i.instancePath} ${i.message}`).reduce((i,n)=>i+t+n)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let n=i.split("/").slice(1),s=e;for(let o of n)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:c}=a.definition,u=s[o];if(c&&u)s[o]=Xu(u)}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];if(!t||t.test(r)){if(typeof i=="string")delete e[r];else if(i&&!i.meta)this._cache.delete(i.schema),delete e[r]}}}_addSchema(e,t,r,i=this.opts.validateSchema,n=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];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;r=(0,ii.normalizeId)(s||r);let c=ii.getSchemaRefs.call(this,e,r);if(a=new ri.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),n&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(i)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 ri.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{ri.compileSchema.call(this,e)}finally{this.opts=t}}}bn.ValidationError=sE.default;bn.MissingRefError=Qu.default;ie.default=bn;function Hu(e,t,r,i="error"){for(let n in e){let s=n;if(s in t)this.logger[i](`${r}: option ${n}. ${e[s]}`)}}function Ju(e){return e=(0,ii.normalizeId)(e),this.schemas[e]||this.refs[e]}function mE(){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 hE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function gE(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 r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function yE(){let e={...this.opts};for(let t of cE)delete e[t];return e}var _E={log(){},warn(){},error(){}};function PE(e){if(e===!1)return _E;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 bE=/^[a-z_$][a-z0-9_$:-]*$/i;function vE(e,t){let{RULES:r}=this;if((0,No.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!bE.test(i))throw Error(`Keyword ${i} 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 Do(e,t,r){var i;let n=t===null||t===void 0?void 0:t.post;if(r&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:c})=>c===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)}};if(t.before)wE.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((c)=>this.addKeyword(c))}function wE(e,t,r){let i=e.rules.findIndex((n)=>n.keyword===r);if(i>=0)e.rules.splice(i,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function $E(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Xu(t);e.validateSchema=this.compile(t,!0)}var EE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xu(e){return{anyOf:[e,EE]}}});var Zu=b(function(qo){Object.defineProperty(qo,"__esModule",{value:!0});var IE={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qo.default=IE});var $n=b(function(Tt){Object.defineProperty(Tt,"__esModule",{value:!0});Tt.callRef=Tt.getValidate=void 0;var SE=dr(),ep=Ce(),be=F(),pr=Re(),tp=ei(),vn=D(),xE={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:c}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=tp.resolveRef.call(c,u,n,r);if(l===void 0)throw new SE.default(i.opts.uriResolver,n,r);if(l instanceof tp.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return wn(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return wn(e,be._`${m}.validate`,u,u.$async)}function p(m){let h=rp(e,m);wn(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,be.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:be.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function rp(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):be._`${r.scopeValue("wrapper",{ref:t})}.validate`}Tt.getValidate=rp;function wn(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,u=c.passContext?pr.default.this:be.nil;if(i)l();else d();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(be._`await ${(0,ep.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(be._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function d(){e.result((0,ep.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=be._`${m}.errors`;n.assign(pr.default.vErrors,be._`${pr.default.vErrors} === null ? ${h} : ${pr.default.vErrors}.concat(${h})`),n.assign(pr.default.errors,be._`${pr.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=vn.mergeEvaluated.props(n,g.props,s.props)}else{let y=n.var("props",be._`${m}.evaluated.props`);s.props=vn.mergeEvaluated.props(n,y,s.props,be.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=vn.mergeEvaluated.items(n,g.items,s.items)}else{let y=n.var("items",be._`${m}.evaluated.items`);s.items=vn.mergeEvaluated.items(n,y,s.items,be.Name)}}}Tt.callRef=wn;Tt.default=xE});var Uo=b(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});var RE=Zu(),CE=$n(),jE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",RE.default,CE.default];Mo.default=jE});var ip=b(function(Bo){Object.defineProperty(Bo,"__esModule",{value:!0});var En=F(),wt=En.operators,In={maximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},minimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},exclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},exclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},FE={message:({keyword:e,schemaCode:t})=>En.str`must be ${In[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>En._`{comparison: ${In[e].okStr}, limit: ${t}}`},OE={keyword:Object.keys(In),type:"number",schemaType:"number",$data:!0,error:FE,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(En._`${r} ${In[t].fail} ${i} || isNaN(${r})`)}};Bo.default=OE});var np=b(function(Go){Object.defineProperty(Go,"__esModule",{value:!0});var ni=F(),TE={message:({schemaCode:e})=>ni.str`must be multiple of ${e}`,params:({schemaCode:e})=>ni._`{multipleOf: ${e}}`},AE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:TE,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?ni._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:ni._`${o} !== parseInt(${o})`;e.fail$data(ni._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Go.default=AE});var op=b(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});function sp(e){let t=e.length,r=0,i=0,n;while(i<t)if(r++,n=e.charCodeAt(i++),n>=55296&&n<=56319&&i<t){if(n=e.charCodeAt(i),(n&64512)===56320)i++}return r}Vo.default=sp;sp.code='require("ajv/dist/runtime/ucs2length").default'});var ap=b(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});var At=F(),kE=D(),DE=op(),NE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return At.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>At._`{limit: ${e}}`},LE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:NE,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?At.operators.GT:At.operators.LT,o=n.opts.unicode===!1?At._`${r}.length`:At._`${(0,kE.useFunc)(e.gen,DE.default)}(${r})`;e.fail$data(At._`${o} ${s} ${i}`)}};Ko.default=LE});var lp=b(function(zo){Object.defineProperty(zo,"__esModule",{value:!0});var qE=Ce(),Sn=F(),ME={message:({schemaCode:e})=>Sn.str`must match pattern "${e}"`,params:({schemaCode:e})=>Sn._`{pattern: ${e}}`},UE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ME,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?Sn._`(new RegExp(${n}, ${o}))`:(0,qE.usePattern)(e,i);e.fail$data(Sn._`!${a}.test(${t})`)}};zo.default=UE});var cp=b(function(Wo){Object.defineProperty(Wo,"__esModule",{value:!0});var si=F(),BE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return si.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>si._`{limit: ${e}}`},GE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:BE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?si.operators.GT:si.operators.LT;e.fail$data(si._`Object.keys(${r}).length ${n} ${i}`)}};Wo.default=GE});var dp=b(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var oi=Ce(),ai=F(),VE=D(),KE={message:({params:{missingProperty:e}})=>ai.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>ai._`{missingProperty: ${e}}`},zE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:KE,code(e){let{gen:t,schema:r,schemaCode:i,data:n,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors)u();else l();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,VE.checkStrictMode)(o,y,o.opts.strictRequired)}}function u(){if(c||s)e.block$data(ai.nil,d);else for(let f of r)(0,oi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(c||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,oi.checkMissingProp)(e,r,f)),(0,oi.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,oi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,oi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,ai.not)(m),()=>{e.error(),t.break()})},ai.nil)}}};Ho.default=zE});var up=b(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var li=F(),WE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return li.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>li._`{limit: ${e}}`},HE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:WE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?li.operators.GT:li.operators.LT;e.fail$data(li._`${r}.length ${n} ${i}`)}};Jo.default=HE});var xn=b(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});var pp=Po();pp.code='require("ajv/dist/runtime/equal").default';Qo.default=pp});var fp=b(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var Yo=Hr(),ne=F(),JE=D(),QE=xn(),YE={message:({params:{i:e,j:t}})=>ne.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>ne._`{i: ${e}, j: ${t}}`},XE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:YE,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let c=t.let("valid"),u=s.items?(0,Yo.getSchemaTypes)(s.items):[];e.block$data(c,l,ne._`${o} === false`),e.ok(c);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if(ne._`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),y=(0,Yo.checkDataTypes)(u,g,a.opts.strictNumbers,Yo.DataType.Wrong),P=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(y,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${P}[${g}] == "number"`,()=>{t.assign(h,ne._`${P}[${g}]`),e.error(),t.assign(c,!1).break()}).code(ne._`${P}[${g}] = ${m}`)})}function f(m,h){let g=(0,JE.useFunc)(t,QE.default),y=t.name("outer");t.label(y).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};Xo.default=XE});var mp=b(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Zo=F(),ZE=D(),eI=xn(),tI={message:"must be equal to constant",params:({schemaCode:e})=>Zo._`{allowedValue: ${e}}`},rI={keyword:"const",$data:!0,error:tI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(Zo._`!${(0,ZE.useFunc)(t,eI.default)}(${r}, ${n})`);else e.fail(Zo._`${s} !== ${r}`)}};ea.default=rI});var hp=b(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var ci=F(),iI=D(),nI=xn(),sI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>ci._`{allowedValues: ${e}}`},oI={keyword:"enum",schemaType:"array",$data:!0,error:sI,code(e){let{gen:t,data:r,$data:i,schema:n,schemaCode:s,it:o}=e;if(!i&&n.length===0)throw Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,c,u=()=>c!==null&&c!==void 0?c:c=(0,iI.useFunc)(t,nI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,ci.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(ci._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?ci._`${u()}(${r}, ${f}[${m}])`:ci._`${r} === ${h}`}}};ta.default=oI});var ia=b(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var aI=ip(),lI=np(),cI=ap(),dI=lp(),uI=cp(),pI=dp(),fI=up(),mI=fp(),hI=mp(),gI=hp(),yI=[aI.default,lI.default,cI.default,dI.default,uI.default,pI.default,fI.default,mI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hI.default,gI.default];ra.default=yI});var sa=b(function(di){Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var kt=F(),na=D(),_I={message:({params:{len:e}})=>kt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>kt._`{limit: ${e}}`},PI={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_I,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,na.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gp(e,i)}};function gp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",kt._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(kt._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,na.alwaysValidSchema)(o,i)){let u=r.var("valid",kt._`${a} <= ${t.length}`);r.if((0,kt.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:na.Type.Num},u),!o.allErrors)r.if((0,kt.not)(u),()=>r.break())})}}di.validateAdditionalItems=gp;di.default=PI});var oa=b(function(ui){Object.defineProperty(ui,"__esModule",{value:!0});ui.validateTuple=void 0;var yp=F(),Rn=D(),bI=Ce(),vI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _p(e,"additionalItems",t);if(r.items=!0,(0,Rn.alwaysValidSchema)(r,t))return;e.ok((0,bI.validateArray)(e))}};function _p(e,t,r=e.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=e;if(l(n),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Rn.mergeEvaluated.items(i,r.length,a.items);let c=i.name("valid"),u=i.const("len",yp._`${s}.length`);r.forEach((d,p)=>{if((0,Rn.alwaysValidSchema)(a,d))return;i.if(yp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},c)),e.ok(c)});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Rn.checkStrictMode)(a,g,p.strictTuples)}}}ui.validateTuple=_p;ui.default=vI});var Pp=b(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var wI=oa(),$I={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,wI.validateTuple)(e,"items")};aa.default=$I});var vp=b(function(la){Object.defineProperty(la,"__esModule",{value:!0});var bp=F(),EI=D(),II=Ce(),SI=sa(),xI={message:({params:{len:e}})=>bp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>bp._`{limit: ${e}}`},RI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xI,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,EI.alwaysValidSchema)(i,t))return;if(n)(0,SI.validateAdditionalItems)(e,n);else e.ok((0,II.validateArray)(e))}};la.default=RI});var wp=b(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var Fe=F(),Cn=D(),CI={message:({params:{min:e,max:t}})=>t===void 0?Fe.str`must contain at least ${e} valid item(s)`:Fe.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Fe._`{minContains: ${e}}`:Fe._`{minContains: ${e}, maxContains: ${t}}`},jI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:CI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:c,maxContains:u}=i;if(s.opts.next)o=c===void 0?1:c,a=u;else o=1;let l=t.const("len",Fe._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Cn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Cn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Cn.alwaysValidSchema)(s,r)){let h=Fe._`${l} >= ${o}`;if(a!==void 0)h=Fe._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let d=t.name("valid");if(a===void 0&&o===1)f(d,()=>t.if(d,()=>t.break()));else if(o===0){if(t.let(d,!0),a!==void 0)t.if(Fe._`${n}.length > 0`,p)}else t.let(d,!1),p();e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,l,(y)=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Cn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Fe._`${h}++`),a===void 0)t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0).break());else if(t.if(Fe._`${h} > ${a}`,()=>t.assign(d,!1).break()),o===1)t.assign(d,!0);else t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0))}}};ca.default=jI});var jn=b(function(We){Object.defineProperty(We,"__esModule",{value:!0});We.validateSchemaDeps=We.validatePropertyDeps=We.error=void 0;var da=F(),FI=D(),pi=Ce();We.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return da.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>da._`{property: ${e},
|
|
3
|
+
(function(exports, require, module, __filename, __dirname) {var F_=Object.create;var{getPrototypeOf:T_,defineProperty:Vs,getOwnPropertyNames:k_}=Object;var A_=Object.prototype.hasOwnProperty;function D_(e){return this[e]}var N_,L_,Ce=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?N_??=new WeakMap:L_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?F_(T_(e)):{};let o=t||!e||!e.__esModule?Vs(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of k_(e))if(!A_.call(o,a))Vs(o,a,{get:D_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var q_=(e)=>e;function M_(e,t){this[e]=q_.bind(null,t)}var U_=(e,t)=>{for(var r in t)Vs(e,r,{get:t[r],enumerable:!0,configurable:!0,set:M_.bind(t,r)})};var ei=P(function(M){Object.defineProperty(M,"__esModule",{value:!0});M.regexpCode=M.getEsmExportName=M.getProperty=M.safeStringify=M.stringify=M.strConcat=M.addCodeArg=M.str=M._=M.nil=M._Code=M.Name=M.IDENTIFIER=M._CodeOrName=void 0;class cn{}M._CodeOrName=cn;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class ar extends cn{constructor(e){super();if(!M.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}M.Name=ar;class Le extends cn{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof ar)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=Le;M.nil=new Le("");function kd(e,...t){let r=[e[0]],i=0;while(i<t.length)lo(r,t[i]),r.push(e[++i]);return new Le(r)}M._=kd;var ao=new Le("+");function Ad(e,...t){let r=[Zr(e[0])],i=0;while(i<t.length)r.push(ao),lo(r,t[i]),r.push(ao,Zr(e[++i]));return Yv(r),new Le(r)}M.str=Ad;function lo(e,t){if(t instanceof Le)e.push(...t._items);else if(t instanceof ar)e.push(t);else e.push(ew(t))}M.addCodeArg=lo;function Yv(e){let t=1;while(t<e.length-1){if(e[t]===ao){let r=Xv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Xv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof ar||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof ar))return`"${e}${t.slice(1)}`;return}function Zv(e,t){return t.emptyStr()?e:e.emptyStr()?t:Ad`${e}${t}`}M.strConcat=Zv;function ew(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zr(Array.isArray(e)?e.join(","):e)}function tw(e){return new Le(Zr(e))}M.stringify=tw;function Zr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Zr;function rw(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new Le(`.${e}`):kd`[${e}]`}M.getProperty=rw;function iw(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new Le(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=iw;function nw(e){return new Le(e.toString())}M.regexpCode=nw});var po=P(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var be=ei();class Dd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var dn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(dn||(Pe.UsedValueState=dn={}));Pe.varKinds={const:new be.Name("const"),let:new be.Name("let"),var:new be.Name("var")};class co{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof be.Name?e:this.name(e)}name(e){return new be.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}Pe.Scope=co;class uo extends be.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=be._`.${new be.Name(t)}[${r}]`}}Pe.ValueScopeName=uo;var sw=be._`\n`;class Nd extends co{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sw:be.nil}}get(){return this._scope}name(e){return new uo(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:n}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[n];if(o){let u=o.get(s);if(u)return u}else o=this._values[n]=new Map;o.set(s,i);let a=this._scope[n]||(this._scope[n]=[]),d=a.length;return a[d]=t.ref,i.setValue(t,{property:n,itemIndex:d}),i}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return be._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(i)=>{if(i.value===void 0)throw Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let n=be.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((d)=>{if(a.has(d))return;a.set(d,dn.Started);let u=t(d);if(u){let l=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;n=be._`${n}${l} ${d} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(d))n=be._`${n}${u}${this.opts._n}`;else throw new Dd(d);a.set(d,dn.Completed)})}return n}}Pe.ValueScope=Nd});var j=P(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.or=k.and=k.not=k.CodeGen=k.operators=k.varKinds=k.ValueScopeName=k.ValueScope=k.Scope=k.Name=k.regexpCode=k.stringify=k.getProperty=k.nil=k.strConcat=k.str=k._=void 0;var N=ei(),qe=po(),Pt=ei();Object.defineProperty(k,"_",{enumerable:!0,get:function(){return Pt._}});Object.defineProperty(k,"str",{enumerable:!0,get:function(){return Pt.str}});Object.defineProperty(k,"strConcat",{enumerable:!0,get:function(){return Pt.strConcat}});Object.defineProperty(k,"nil",{enumerable:!0,get:function(){return Pt.nil}});Object.defineProperty(k,"getProperty",{enumerable:!0,get:function(){return Pt.getProperty}});Object.defineProperty(k,"stringify",{enumerable:!0,get:function(){return Pt.stringify}});Object.defineProperty(k,"regexpCode",{enumerable:!0,get:function(){return Pt.regexpCode}});Object.defineProperty(k,"Name",{enumerable:!0,get:function(){return Pt.Name}});var gn=po();Object.defineProperty(k,"Scope",{enumerable:!0,get:function(){return gn.Scope}});Object.defineProperty(k,"ValueScope",{enumerable:!0,get:function(){return gn.ValueScope}});Object.defineProperty(k,"ValueScopeName",{enumerable:!0,get:function(){return gn.ValueScopeName}});Object.defineProperty(k,"varKinds",{enumerable:!0,get:function(){return gn.varKinds}});k.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};class vt{optimizeNodes(){return this}optimizeNames(e,t){return this}}class Ld extends vt{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?qe.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=cr(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class ho extends vt{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=cr(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return hn(e,this.rhs)}}class qd extends ho{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Md extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Ud extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Bd extends vt{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class Gd extends vt{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=cr(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class yn extends vt{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;while(i--){let n=r[i];if(n.optimizeNames(e,t))continue;ow(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>At(e,t.names),{})}}class wt extends yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Vd extends yn{}class ti extends wt{}ti.kind="else";class dt extends wt{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new ti(r):r}if(t){if(e===!1)return t instanceof dt?t:t.nodes;if(this.nodes.length)return this;return new dt(Jd(e),t instanceof dt?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=cr(this.condition,e,t),this}get names(){let e=super.names;if(hn(e,this.condition),this.else)At(e,this.else.names);return e}}dt.kind="if";class lr extends wt{}lr.kind="for";class Kd extends lr{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=cr(this.iteration,e,t),this}get names(){return At(super.names,this.iteration.names)}}class zd extends lr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?qe.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=hn(super.names,this.from);return hn(e,this.to)}}class fo extends lr{constructor(e,t,r,i){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=cr(this.iterable,e,t),this}get names(){return At(super.names,this.iterable.names)}}class un extends wt{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}un.kind="func";class pn extends yn{render(e){return"return "+super.render(e)}}pn.kind="return";class Wd extends wt{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)At(e,this.catch.names);if(this.finally)At(e,this.finally.names);return e}}class fn extends wt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}fn.kind="catch";class mn extends wt{render(e){return"finally"+super.render(e)}}mn.kind="finally";class Hd{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
4
|
+
`:""},this._extScope=e,this._scope=new qe.Scope({parent:e}),this._nodes=[new Vd]}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 r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}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,r,i){let n=this._scope.toName(t);if(r!==void 0&&i)this._constants[n.str]=r;return this._leafNode(new Ld(e,n,r)),n}const(e,t,r){return this._def(qe.varKinds.const,e,t,r)}let(e,t,r){return this._def(qe.varKinds.let,e,t,r)}var(e,t,r){return this._def(qe.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new ho(e,t,r))}add(e,t){return this._leafNode(new qd(e,k.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new Gd(e));return this}object(...e){let t=["{"];for(let[r,i]of e){if(t.length>1)t.push(",");if(t.push(r),r!==i||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,i)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new dt(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new dt(e))}else(){return this._elseNode(new ti)}endIf(){return this._endBlockNode(dt,ti)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Kd(e),t)}forRange(e,t,r,i,n=this.opts.es5?qe.varKinds.var:qe.varKinds.let){let s=this._scope.toName(e);return this._for(new zd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=qe.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let s=t instanceof N.Name?t:this.var("_arr",t);return this.forRange("_i",0,N._`${s}.length`,(o)=>{this.var(n,N._`${s}[${o}]`),r(n)})}return this._for(new fo("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?qe.varKinds.var:qe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let n=this._scope.toName(e);return this._for(new fo("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(lr)}label(e){return this._leafNode(new Md(e))}break(e){return this._leafNode(new Ud(e))}return(e){let t=new pn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(pn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Wd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new fn(n),t(n)}if(r)this._currNode=i.finally=new mn,this.code(r);return this._endBlockNode(fn,mn)}throw(e){return this._leafNode(new Bd(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 r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=N.nil,r,i){if(this._blockNode(new un(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(un)}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 r=this._currNode;if(r instanceof e||t&&r 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 dt))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}}k.CodeGen=Hd;function At(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function hn(e,t){return t instanceof N._CodeOrName?At(e,t.names):e}function cr(e,t,r){if(e instanceof N.Name)return i(e);if(!n(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=i(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function i(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function n(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function ow(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Jd(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${mo(e)}`}k.not=Jd;var aw=Qd(k.operators.AND);function lw(...e){return e.reduce(aw)}k.and=lw;var cw=Qd(k.operators.OR);function dw(...e){return e.reduce(cw)}k.or=dw;function Qd(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${mo(t)} ${e} ${mo(r)}`}function mo(e){return e instanceof N.Name?e:N._`(${e})`}});var D=P(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.checkStrictMode=A.getErrorPath=A.Type=A.useFunc=A.setEvaluated=A.evaluatedPropsToName=A.mergeEvaluated=A.eachItem=A.unescapeJsonPointer=A.escapeJsonPointer=A.escapeFragment=A.unescapeFragment=A.schemaRefOrVal=A.schemaHasRulesButRef=A.schemaHasRules=A.checkUnknownRules=A.alwaysValidSchema=A.toHash=void 0;var G=j(),uw=ei();function pw(e){let t={};for(let r of e)t[r]=!0;return t}A.toHash=pw;function fw(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Zd(e,t),!eu(t,e.self.RULES.all)}A.alwaysValidSchema=fw;function Zd(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let n=i.RULES.keywords;for(let s in t)if(!n[s])iu(e,`unknown keyword: "${s}"`)}A.checkUnknownRules=Zd;function eu(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}A.schemaHasRules=eu;function mw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}A.schemaHasRulesButRef=mw;function hw({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(i)}`}A.schemaRefOrVal=hw;function gw(e){return tu(decodeURIComponent(e))}A.unescapeFragment=gw;function yw(e){return encodeURIComponent(yo(e))}A.escapeFragment=yw;function yo(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}A.escapeJsonPointer=yo;function tu(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}A.unescapeJsonPointer=tu;function _w(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}A.eachItem=_w;function Yd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let d=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(n,s,o):t(n,s,o),o):s instanceof G.Name?(t(n,o,s),s):r(s,o);return a===G.Name&&!(d instanceof G.Name)?i(n,d):d}}A.mergeEvaluated={props:Yd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>{e.if(G._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,G._`${r} || {}`).code(G._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,G._`${r} || {}`),_o(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ru}),items:Yd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,G._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>e.assign(r,t===!0?!0:G._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function ru(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)_o(e,r,t);return r}A.evaluatedPropsToName=ru;function _o(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}A.setEvaluated=_o;var Xd={};function bw(e,t){return e.scopeValue("func",{ref:t,code:Xd[t.code]||(Xd[t.code]=new uw._Code(t.code))})}A.useFunc=bw;var go;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(go||(A.Type=go={}));function Pw(e,t,r){if(e instanceof G.Name){let i=t===go.Num;return r?i?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:i?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+yo(e)}A.getErrorPath=Pw;function iu(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}A.checkStrictMode=iu});var Oe=P(function(bo){Object.defineProperty(bo,"__esModule",{value:!0});var ae=j(),vw={data:new ae.Name("data"),valCxt:new ae.Name("valCxt"),instancePath:new ae.Name("instancePath"),parentData:new ae.Name("parentData"),parentDataProperty:new ae.Name("parentDataProperty"),rootData:new ae.Name("rootData"),dynamicAnchors:new ae.Name("dynamicAnchors"),vErrors:new ae.Name("vErrors"),errors:new ae.Name("errors"),this:new ae.Name("this"),self:new ae.Name("self"),scope:new ae.Name("scope"),json:new ae.Name("json"),jsonPos:new ae.Name("jsonPos"),jsonLen:new ae.Name("jsonLen"),jsonPart:new ae.Name("jsonPart")};bo.default=vw});var ri=P(function(le){Object.defineProperty(le,"__esModule",{value:!0});le.extendErrors=le.resetErrorsCount=le.reportExtraError=le.reportError=le.keyword$DataError=le.keywordError=void 0;var L=j(),_n=D(),me=Oe();le.keywordError={message:({keyword:e})=>L.str`must pass "${e}" keyword validation`};le.keyword$DataError={message:({keyword:e,schemaType:t})=>t?L.str`"${e}" keyword must be ${t} ($data)`:L.str`"${e}" keyword is invalid ($data)`};function ww(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,d=ou(e,t,r);if(i!==null&&i!==void 0?i:o||a)nu(s,d);else su(n,L._`[${d}]`)}le.reportError=ww;function $w(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=ou(e,t,r);if(nu(n,a),!(s||o))su(i,me.default.vErrors)}le.reportExtraError=$w;function Ew(e,t){e.assign(me.default.errors,t),e.if(L._`${me.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${me.default.vErrors}.length`,t),()=>e.assign(me.default.vErrors,null)))}le.resetErrorsCount=Ew;function Iw({gen:e,keyword:t,schemaValue:r,data:i,errsCount:n,it:s}){if(n===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",n,me.default.errors,(a)=>{if(e.const(o,L._`${me.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(me.default.instancePath,s.errorPath))),e.assign(L._`${o}.schemaPath`,L.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(L._`${o}.schema`,r),e.assign(L._`${o}.data`,i)})}le.extendErrors=Iw;function nu(e,t){let r=e.const("err",t);e.if(L._`${me.default.vErrors} === null`,()=>e.assign(me.default.vErrors,L._`[${r}]`),L._`${me.default.vErrors}.push(${r})`),e.code(L._`${me.default.errors}++`)}function su(e,t){let{gen:r,validateName:i,schemaEnv:n}=e;if(n.$async)r.throw(L._`new ${e.ValidationError}(${t})`);else r.assign(L._`${i}.errors`,t),r.return(!1)}var Dt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function ou(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Sw(e,t,r)}function Sw(e,t,r={}){let{gen:i,it:n}=e,s=[xw(n,r),Rw(e,r)];return Cw(e,t,s),i.object(...s)}function xw({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,_n.getErrorPath)(t,_n.Type.Str)}`:e;return[me.default.instancePath,(0,L.strConcat)(me.default.instancePath,r)]}function Rw({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,_n.getErrorPath)(r,_n.Type.Str)}`;return[Dt.schemaPath,n]}function Cw(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:d,propertyName:u,topSchemaRef:l,schemaPath:c}=a;if(i.push([Dt.keyword,n],[Dt.params,typeof t=="function"?t(e):t||L._`{}`]),d.messages)i.push([Dt.message,typeof r=="function"?r(e):r]);if(d.verbose)i.push([Dt.schema,o],[Dt.parentSchema,L._`${l}${c}`],[me.default.data,s]);if(u)i.push([Dt.propertyName,u])}});var lu=P(function(dr){Object.defineProperty(dr,"__esModule",{value:!0});dr.boolOrEmptySchema=dr.topBoolOrEmptySchema=void 0;var Ow=ri(),jw=j(),Fw=Oe(),Tw={message:"boolean schema is false"};function kw(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)au(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Fw.default.data);else t.assign(jw._`${i}.errors`,null),t.return(!0)}dr.topBoolOrEmptySchema=kw;function Aw(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),au(e);else r.var(t,!0)}dr.boolOrEmptySchema=Aw;function au(e,t){let{gen:r,data:i}=e,n={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Ow.reportError)(n,Tw,void 0,t)}});var Po=P(function(ur){Object.defineProperty(ur,"__esModule",{value:!0});ur.getRules=ur.isJSONType=void 0;var Dw=["string","number","integer","boolean","null","object","array"],Nw=new Set(Dw);function Lw(e){return typeof e=="string"&&Nw.has(e)}ur.isJSONType=Lw;function qw(){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:{}}}ur.getRules=qw});var vo=P(function($t){Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function Mw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&cu(e,i)}$t.schemaHasRulesForType=Mw;function cu(e,t){return t.rules.some((r)=>du(e,r))}$t.shouldUseGroup=cu;function du(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((i)=>e[i]!==void 0))}$t.shouldUseRule=du});var ii=P(function(ce){Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;var Uw=Po(),Bw=vo(),Gw=ri(),F=j(),uu=D(),pr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(pr||(ce.DataType=pr={}));function Vw(e){let t=pu(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}ce.getSchemaTypes=Vw;function pu(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Uw.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=pu;function Kw(e,t){let{gen:r,data:i,opts:n}=e,s=zw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,Bw.schemaHasRulesForType)(e,t[0]));if(o){let a=$o(t,i,n.strictNumbers,pr.Wrong);r.if(a,()=>{if(s.length)Ww(e,t,s);else Eo(e)})}return o}ce.coerceAndCheckDataType=Kw;var fu=new Set(["string","number","integer","boolean","null"]);function zw(e,t){return t?e.filter((r)=>fu.has(r)||t==="array"&&r==="array"):[]}function Ww(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",F._`typeof ${n}`),a=i.let("coerced",F._`undefined`);if(s.coerceTypes==="array")i.if(F._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,F._`${n}[0]`).assign(o,F._`typeof ${n}`).if($o(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(F._`${a} !== undefined`);for(let u of r)if(fu.has(u)||u==="array"&&s.coerceTypes==="array")d(u);i.else(),Eo(e),i.endIf(),i.if(F._`${a} !== undefined`,()=>{i.assign(n,a),Hw(e,a)});function d(u){switch(u){case"string":i.elseIf(F._`${o} == "number" || ${o} == "boolean"`).assign(a,F._`"" + ${n}`).elseIf(F._`${n} === null`).assign(a,F._`""`);return;case"number":i.elseIf(F._`${o} == "boolean" || ${n} === null
|
|
5
|
+
|| (${o} == "string" && ${n} && ${n} == +${n})`).assign(a,F._`+${n}`);return;case"integer":i.elseIf(F._`${o} === "boolean" || ${n} === null
|
|
6
|
+
|| (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,F._`+${n}`);return;case"boolean":i.elseIf(F._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf(F._`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":i.elseIf(F._`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(a,null);return;case"array":i.elseIf(F._`${o} === "string" || ${o} === "number"
|
|
7
|
+
|| ${o} === "boolean" || ${n} === null`).assign(a,F._`[${n}]`)}}}function Hw({gen:e,parentData:t,parentDataProperty:r},i){e.if(F._`${t} !== undefined`,()=>e.assign(F._`${t}[${r}]`,i))}function wo(e,t,r,i=pr.Correct){let n=i===pr.Correct?F.operators.EQ:F.operators.NEQ,s;switch(e){case"null":return F._`${t} ${n} null`;case"array":s=F._`Array.isArray(${t})`;break;case"object":s=F._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(F._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return F._`typeof ${t} ${n} ${e}`}return i===pr.Correct?s:(0,F.not)(s);function o(a=F.nil){return(0,F.and)(F._`typeof ${t} == "number"`,a,r?F._`isFinite(${t})`:F.nil)}}ce.checkDataType=wo;function $o(e,t,r,i){if(e.length===1)return wo(e[0],t,r,i);let n,s=(0,uu.toHash)(e);if(s.array&&s.object){let o=F._`typeof ${t} != "object"`;n=s.null?o:F._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=F.nil;if(s.number)delete s.integer;for(let o in s)n=(0,F.and)(n,wo(o,t,r,i));return n}ce.checkDataTypes=$o;var Jw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?F._`{type: ${e}}`:F._`{type: ${t}}`};function Eo(e){let t=Qw(e);(0,Gw.reportError)(t,Jw)}ce.reportTypeError=Eo;function Qw(e){let{gen:t,data:r,schema:i}=e,n=(0,uu.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var hu=P(function(bn){Object.defineProperty(bn,"__esModule",{value:!0});bn.assignDefaults=void 0;var fr=j(),Yw=D();function Xw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)mu(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>mu(e,s,n.default))}bn.assignDefaults=Xw;function mu(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=fr._`${s}${(0,fr.getProperty)(t)}`;if(n){(0,Yw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let d=fr._`${a} === undefined`;if(o.useDefaults==="empty")d=fr._`${d} || ${a} === null || ${a} === ""`;i.if(d,fr._`${a} = ${(0,fr.stringify)(r)}`)}});var je=P(function(B){Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var K=j(),Io=D(),Et=Oe(),Zw=D();function e$(e,t){let{gen:r,data:i,it:n}=e;r.if(xo(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=e$;function t$({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(xo(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=t$;function r$(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=r$;function gu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=gu;function So(e,t,r){return K._`${gu(e)}.call(${t}, ${r})`}B.isOwnProperty=So;function i$(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${So(e,t,r)}`:n}B.propertyInData=i$;function xo(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(So(e,t,r))):n}B.noPropertyInData=xo;function yu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=yu;function n$(e,t){return yu(t).filter((r)=>!(0,Io.alwaysValidSchema)(e,t[r]))}B.schemaProperties=n$;function s$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,d,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,c=[[Et.default.instancePath,(0,K.strConcat)(Et.default.instancePath,s)],[Et.default.parentData,o.parentData],[Et.default.parentDataProperty,o.parentDataProperty],[Et.default.rootData,Et.default.rootData]];if(o.opts.dynamicRef)c.push([Et.default.dynamicAnchors,Et.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...c)}`;return d!==K.nil?K._`${a}.call(${d}, ${p})`:K._`${a}(${p})`}B.callValidateCode=s$;var o$=K._`new RegExp`;function a$({gen:e,it:{opts:t}},r){let i=t.unicodeRegExp?"u":"",{regExp:n}=t.code,s=n(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${n.code==="new RegExp"?o$:(0,Zw.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=a$;function l$(e){let{gen:t,data:r,keyword:i,it:n}=e,s=t.name("valid");if(n.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let d=t.const("len",K._`${r}.length`);t.forRange("i",0,d,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:Io.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=l$;function c$(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((d)=>(0,Io.alwaysValidSchema)(n,d))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((d,u)=>{let l=e.subschema({keyword:i,schemaProp:u,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(l,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=c$});var Pu=P(function(Je){Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var he=j(),Nt=Oe(),d$=je(),u$=ri();function p$(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),d=bu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:he.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:d,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Je.macroKeywordCode=p$;function f$(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:d}=e;h$(d,t);let u=!a&&t.compile?t.compile.call(d.self,s,o,d):t.validate,l=bu(i,n,u),c=i.let("valid");e.block$data(c,p),e.ok((r=t.valid)!==null&&r!==void 0?r:c);function p(){if(t.errors===!1){if(h(),t.modifying)_u(e);g(()=>e.error())}else{let _=t.async?f():m();if(t.modifying)_u(e);g(()=>m$(e,_))}}function f(){let _=i.let("ruleErrs",null);return i.try(()=>h(he._`await `),(b)=>i.assign(c,!1).if(he._`${b} instanceof ${d.ValidationError}`,()=>i.assign(_,he._`${b}.errors`),()=>i.throw(b))),_}function m(){let _=he._`${l}.errors`;return i.assign(_,null),h(he.nil),_}function h(_=t.async?he._`await `:he.nil){let b=d.opts.passContext?Nt.default.this:Nt.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(c,he._`${_}${(0,d$.callValidateCode)(e,l,b,v)}`,t.modifying)}function g(_){var b;i.if((0,he.not)((b=t.valid)!==null&&b!==void 0?b:c),_)}}Je.funcKeywordCode=f$;function _u(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,he._`${i.parentData}[${i.parentDataProperty}]`))}function m$(e,t){let{gen:r}=e;r.if(he._`Array.isArray(${t})`,()=>{r.assign(Nt.default.vErrors,he._`${Nt.default.vErrors} === null ? ${t} : ${Nt.default.vErrors}.concat(${t})`).assign(Nt.default.errors,he._`${Nt.default.vErrors}.length`),(0,u$.extendErrors)(e)},()=>e.error())}function h$({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function bu(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,he.stringify)(r)})}function g$(e,t,r=!1){return!t.length||t.some((i)=>i==="array"?Array.isArray(e):i==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==i||r&&typeof e>"u")}Je.validSchemaType=g$;function y$({schema:e,opts:t,self:r,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw Error("ajv implementation error");let o=n.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){let d=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw Error(d)}}}Je.validateKeywordUsage=y$});var wu=P(function(It){Object.defineProperty(It,"__esModule",{value:!0});It.extendSubschemaMode=It.extendSubschemaData=It.getSubschema=void 0;var Qe=j(),vu=D();function _$(e,{keyword:t,schemaProp:r,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&i!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Qe._`${e.schemaPath}${(0,Qe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Qe._`${e.schemaPath}${(0,Qe.getProperty)(t)}${(0,Qe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,vu.escapeFragment)(r)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}It.getSubschema=_$;function b$(e,t,{dataProp:r,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:c}=t,p=a.let("data",Qe._`${t.data}${(0,Qe.getProperty)(r)}`,!0);d(p),e.errorPath=Qe.str`${u}${(0,vu.getErrorPath)(r,i,c.jsPropertySyntax)}`,e.parentDataProperty=Qe._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Qe.Name?n:a.let("data",n,!0);if(d(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function d(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}It.extendSubschemaData=b$;function P$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:n,allErrors:s}){if(i!==void 0)e.compositeRule=i;if(n!==void 0)e.createErrors=n;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}It.extendSubschemaMode=P$});var Ro=P(function(lA,$u){$u.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if(i=t.length,i!=r.length)return!1;for(n=i;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),i=s.length,i!==Object.keys(r).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var Iu=P(function(cA,Eu){var St=Eu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var i=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};Pn(t,i,n,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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 Pn(e,t,r,i,n,s,o,a,d,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,d,u);for(var l in i){var c=i[l];if(Array.isArray(c)){if(l in St.arrayKeywords)for(var p=0;p<c.length;p++)Pn(e,t,r,c[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in St.propsKeywords){if(c&&typeof c=="object")for(var f in c)Pn(e,t,r,c[f],n+"/"+l+"/"+v$(f),s,n,l,i,f)}else if(l in St.keywords||e.allKeys&&!(l in St.skipKeywords))Pn(e,t,r,c,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,d,u)}}function v$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=P(function(ve){Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var w$=D(),$$=Ro(),E$=Iu(),I$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function S$(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!Co(e);if(!t)return!1;return Su(e)<=t}ve.inlineRef=S$;var x$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Co(e){for(let t in e){if(x$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Co))return!0;if(typeof r=="object"&&Co(r))return!0}return!1}function Su(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,I$.has(r))continue;if(typeof e[r]=="object")(0,w$.eachItem)(e[r],(i)=>t+=Su(i));if(t===1/0)return 1/0}return t}function xu(e,t="",r){if(r!==!1)t=mr(t);let i=e.parse(t);return Ru(e,i)}ve.getFullPath=xu;function Ru(e,t){return e.serialize(t).split("#")[0]+"#"}ve._getFullPath=Ru;var R$=/#\/?$/;function mr(e){return e?e.replace(R$,""):""}ve.normalizeId=mr;function C$(e,t,r){return r=mr(r),e.resolve(t,r)}ve.resolveUrl=C$;var O$=/^[a-z_][-a-z0-9._]*$/i;function j$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=mr(e[r]||t),s={"":n},o=xu(i,n,!1),a={},d=new Set;return E$(e,{allKeys:!0},(c,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof c[r]=="string")g=_.call(this,c[r]);b.call(this,c.$anchor),b.call(this,c.$dynamicAnchor),s[p]=g;function _(v){let w=this.opts.uriResolver.resolve;if(v=mr(g?w(g,v):v),d.has(v))throw l(v);d.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(c,I.schema,v);else if(v!==mr(h))if(v[0]==="#")u(c,a[v],v),a[v]=c;else this.refs[v]=h;return v}function b(v){if(typeof v=="string"){if(!O$.test(v))throw Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(c,p,f){if(p!==void 0&&!$$(c,p))throw l(f)}function l(c){return Error(`reference "${c}" resolves to more than one schema`)}}ve.getSchemaRefs=j$});var hr=P(function(xt){Object.defineProperty(xt,"__esModule",{value:!0});xt.getData=xt.KeywordCxt=xt.validateFunctionCode=void 0;var Tu=lu(),Cu=ii(),jo=vo(),vn=ii(),F$=hu(),oi=Pu(),Oo=wu(),S=j(),O=Oe(),T$=ni(),ut=D(),si=ri();function k$(e){if(Du(e)){if(Nu(e),Au(e)){N$(e);return}}ku(e,()=>(0,Tu.topBoolOrEmptySchema)(e))}xt.validateFunctionCode=k$;function ku({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${O.default.data}, ${O.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${Ou(r,n)}`),D$(e,n),e.code(s)});else e.func(t,S._`${O.default.data}, ${A$(n)}`,i.$async,()=>e.code(Ou(r,n)).code(s))}function A$(e){return S._`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${e.dynamicRef?S._`, ${O.default.dynamicAnchors}={}`:S.nil}}={}`}function D$(e,t){e.if(O.default.valCxt,()=>{if(e.var(O.default.instancePath,S._`${O.default.valCxt}.${O.default.instancePath}`),e.var(O.default.parentData,S._`${O.default.valCxt}.${O.default.parentData}`),e.var(O.default.parentDataProperty,S._`${O.default.valCxt}.${O.default.parentDataProperty}`),e.var(O.default.rootData,S._`${O.default.valCxt}.${O.default.rootData}`),t.dynamicRef)e.var(O.default.dynamicAnchors,S._`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{if(e.var(O.default.instancePath,S._`""`),e.var(O.default.parentData,S._`undefined`),e.var(O.default.parentDataProperty,S._`undefined`),e.var(O.default.rootData,O.default.data),t.dynamicRef)e.var(O.default.dynamicAnchors,S._`{}`)})}function N$(e){let{schema:t,opts:r,gen:i}=e;ku(e,()=>{if(r.$comment&&t.$comment)qu(e);if(B$(e),i.let(O.default.vErrors,null),i.let(O.default.errors,0),r.unevaluated)L$(e);Lu(e),K$(e)});return}function L$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",S._`${r}.evaluated`),t.if(S._`${e.evaluated}.dynamicProps`,()=>t.assign(S._`${e.evaluated}.props`,S._`undefined`)),t.if(S._`${e.evaluated}.dynamicItems`,()=>t.assign(S._`${e.evaluated}.items`,S._`undefined`))}function Ou(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function q$(e,t){if(Du(e)){if(Nu(e),Au(e)){M$(e,t);return}}(0,Tu.boolOrEmptySchema)(e,t)}function Au({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Du(e){return typeof e.schema!="boolean"}function M$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)qu(e);G$(e),V$(e);let s=i.const("_errs",O.default.errors);Lu(e,s),i.var(t,S._`${s} === ${O.default.errors}`)}function Nu(e){(0,ut.checkUnknownRules)(e),U$(e)}function Lu(e,t){if(e.opts.jtd)return ju(e,[],!1,t);let r=(0,Cu.getSchemaTypes)(e.schema),i=(0,Cu.coerceAndCheckDataType)(e,r);ju(e,r,!i,t)}function U$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function B$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function G$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,T$.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function V$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function qu({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${O.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=S.str`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${O.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function K$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${O.default.errors} === 0`,()=>t.return(O.default.data),()=>t.throw(S._`new ${n}(${O.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,O.default.vErrors),s.unevaluated)z$(e);t.return(S._`${O.default.errors} === 0`)}}function z$({gen:e,evaluated:t,props:r,items:i}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(i instanceof S.Name)e.assign(S._`${t}.items`,i)}function ju(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:d,self:u}=e,{RULES:l}=u;if(s.$ref&&(d.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(s,l))){n.block(()=>Uu(e,"$ref",l.all.$ref.definition));return}if(!d.jtd)W$(e,t);n.block(()=>{for(let p of l.rules)c(p);c(l.post)});function c(p){if(!(0,jo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,vn.checkDataType)(p.type,o,d.strictNumbers)),Fu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,vn.reportTypeError)(e);n.endIf()}else Fu(e,p);if(!a)n.if(S._`${O.default.errors} === ${i||0}`)}}function Fu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,F$.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,jo.shouldUseRule)(i,s))Uu(e,s.keyword,s.definition,t.type)})}function W$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(H$(e,t),!e.opts.allowUnionTypes)J$(e,t);Q$(e,e.dataTypes)}function H$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Mu(e.dataTypes,r))Fo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),X$(e,t)}function J$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Fo(e,"use allowUnionTypes to allow union type keyword")}function Q$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,jo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>Y$(t,o)))Fo(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function Y$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Mu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function X$(e,t){let r=[];for(let i of e.dataTypes)if(Mu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function Fo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}class To{constructor(e,t,r){if((0,oi.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ut.schemaRefOrVal)(e,this.schema,r,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",Bu(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,oi.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",O.default.errors)}result(e,t,r){this.failResult((0,S.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();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,S.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(S._`${t} !== undefined && (${(0,S.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?si.reportExtraError:si.reportError)(this,this.def.error,t)}$dataError(){(0,si.reportError)(this,this.def.$dataError||si.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,si.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,r=S.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=S.nil,t=S.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:n,def:s}=this;if(r.if((0,S.or)(S._`${i} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(n.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:n}=this;return(0,S.or)(s(),o());function s(){if(r.length){if(!(t instanceof S.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return S._`${(0,vn.checkDataTypes)(a,t,n.opts.strictNumbers,vn.DataType.Wrong)}`}return S.nil}function o(){if(i.validateSchema){let a=e.scopeValue("validate$data",{ref:i.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,Oo.getSubschema)(this.it,e);(0,Oo.extendSubschemaData)(r,this.it,e),(0,Oo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return q$(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=ut.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=ut.mergeEvaluated.items(i,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}xt.KeywordCxt=To;function Uu(e,t,r,i){let n=new To(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,oi.funcKeywordCode)(n,r);else if("macro"in r)(0,oi.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,oi.funcKeywordCode)(n,r)}var Z$=/^\/(?:[^~]|~0|~1)*$/,eE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Bu(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return O.default.rootData;if(e[0]==="/"){if(!Z$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=O.default.rootData}else{let u=eE.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(d("property/index",l));return i[t-l]}if(l>t)throw Error(d("data",l));if(s=r[t-l],!n)return s}let o=s,a=n.split("/");for(let u of a)if(u)s=S._`${s}${(0,S.getProperty)((0,ut.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function d(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}xt.getData=Bu});var ai=P(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});class Gu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}ko.default=Gu});var gr=P(function(Do){Object.defineProperty(Do,"__esModule",{value:!0});var Ao=ni();class Vu extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,Ao.resolveUrl)(e,t,r),this.missingSchema=(0,Ao.normalizeId)((0,Ao.getFullPath)(e,this.missingRef))}}Do.default=Vu});var ci=P(function(Fe){Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Me=j(),tE=ai(),Lt=Oe(),Ue=ni(),Ku=D(),rE=hr();class li{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=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,Ue.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}Fe.SchemaEnv=li;function Lo(e){let t=zu.call(this,e);if(t)return t;let r=(0,Ue.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Me.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:tE.default,code:Me._`require("ajv/dist/runtime/validation_error").default`});let d=o.scopeName("validate");e.validateName=d;let u={gen:o,allErrors:this.opts.allErrors,data:Lt.default.data,parentData:Lt.default.parentData,parentDataProperty:Lt.default.parentDataProperty,dataNames:[Lt.default.data],dataPathArr:[Me.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Me.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Me.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Me._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,rE.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let c=o.toString();if(l=`${o.scopeRefs(Lt.default.scope)}return ${c}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Lt.default.self}`,`${Lt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:d,validateCode:c,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Me.Name?void 0:m,items:h instanceof Me.Name?void 0:h,dynamicProps:m instanceof Me.Name,dynamicItems:h instanceof Me.Name},f.source)f.source.evaluated=(0,Me.stringify)(f.evaluated)}return e.validate=f,e}catch(c){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw c}finally{this._compilations.delete(e)}}Fe.compileSchema=Lo;function iE(e,t,r){var i;r=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=oE.call(this,e,r);if(s===void 0){let o=(i=e.localRefs)===null||i===void 0?void 0:i[r],{schemaId:a}=this.opts;if(o)s=new li({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=nE.call(this,s)}Fe.resolveRef=iE;function nE(e){if((0,Ue.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Lo.call(this,e)}function zu(e){for(let t of this._compilations)if(sE(t,e))return t}Fe.getCompilingSchema=zu;function sE(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function oE(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||wn.call(this,e,t)}function wn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,Ue._getFullPath)(this.opts.uriResolver,r),n=(0,Ue.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return No.call(this,r,e);let s=(0,Ue.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=wn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return No.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Lo.call(this,o);if(s===(0,Ue.normalizeId)(t)){let{schema:a}=o,{schemaId:d}=this.opts,u=a[d];if(u)n=(0,Ue.resolveUrl)(this.opts.uriResolver,n,u);return new li({schema:a,schemaId:d,root:e,baseId:n})}return No.call(this,r,o)}Fe.resolveSchema=wn;var aE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function No(e,{baseId:t,schema:r,root:i}){var n;if(((n=e.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let d=r[(0,Ku.unescapeFragment)(a)];if(d===void 0)return;r=d;let u=typeof r==="object"&&r[this.opts.schemaId];if(!aE.has(a)&&u)t=(0,Ue.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Ku.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=wn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new li({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Wu=P(function(hA,lE){lE.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 Mo=P(function(gA,Yu){var cE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ju=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 qo(e){let t="",r=0,i=0;for(i=0;i<e.length;i++){if(r=e[i].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i];break}for(i+=1;i<e.length;i++){if(r=e[i].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i]}return t}var dE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hu(e){return e.length=0,!0}function uE(e,t,r){if(e.length){let i=qo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function pE(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=uE;for(let d=0;d<e.length;d++){let u=e[d];if(u==="["||u==="]")continue;if(u===":"){if(s===!0)o=!0;if(!a(n,i,r))break;if(++t>7){r.error=!0;break}if(d>0&&e[d-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Hu}else{n.push(u);continue}}if(n.length)if(a===Hu)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(qo(n));return r.address=i.join(""),r}function Qu(e){if(fE(e,":")<2)return{host:e,isIPV6:!1};let t=pE(e);if(!t.error){let{address:r,address:i}=t;if(t.zone)r+="%"+t.zone,i+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:i}}else return{host:e,isIPV6:!1}}function fE(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function mE(e){let t=e,r=[],i=-1,n=0;while(n=t.length){if(n===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(n===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]==="/"){r.push("/");break}}}else if(n===3){if(t==="/.."){if(r.length!==0)r.pop();r.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),r.length!==0)r.pop();continue}}}}if((i=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,i)),t=t.slice(i)}return r.join("")}function hE(e,t){let r=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=r(e.scheme);if(e.userinfo!==void 0)e.userinfo=r(e.userinfo);if(e.host!==void 0)e.host=r(e.host);if(e.path!==void 0)e.path=r(e.path);if(e.query!==void 0)e.query=r(e.query);if(e.fragment!==void 0)e.fragment=r(e.fragment);return e}function gE(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!Ju(r)){let i=Qu(r);if(i.isIPV6===!0)r=`[${i.escapedHost}]`;else r=e.host}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}Yu.exports={nonSimpleDomain:dE,recomposeAuthority:gE,normalizeComponentEncoding:hE,removeDotSegments:mE,isIPv4:Ju,isUUID:cE,normalizeIPv6:Qu,stringArrayToHexStripped:qo}});var rp=P(function(yA,tp){var{isUUID:yE}=Mo(),_E=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bE=["http","https","ws","wss","urn","urn:uuid"];function PE(e){return bE.indexOf(e)!==-1}function Uo(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 Xu(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Zu(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 vE(e){return e.secure=Uo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function wE(e){if(e.port===(Uo(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,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function $E(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(_E);if(r){let i=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let n=`${i}:${t.nid||e.nid}`,s=Bo(n);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function EE(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),n=`${r}:${t.nid||i}`,s=Bo(n);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${i||t.nid}:${a}`,t.skipEscape=!0,o}function IE(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!yE(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function SE(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var ep={scheme:"http",domainHost:!0,parse:Xu,serialize:Zu},xE={scheme:"https",domainHost:ep.domainHost,parse:Xu,serialize:Zu},$n={scheme:"ws",domainHost:!0,parse:vE,serialize:wE},RE={scheme:"wss",domainHost:$n.domainHost,parse:$n.parse,serialize:$n.serialize},CE={scheme:"urn",parse:$E,serialize:EE,skipNormalize:!0},OE={scheme:"urn:uuid",parse:IE,serialize:SE,skipNormalize:!0},En={http:ep,https:xE,ws:$n,wss:RE,urn:CE,"urn:uuid":OE};Object.setPrototypeOf(En,null);function Bo(e){return e&&(En[e]||En[e.toLowerCase()])||void 0}tp.exports={wsIsSecure:Uo,SCHEMES:En,isValidSchemeName:PE,getSchemeHandler:Bo}});var sp=P(function(_A,Sn){var{normalizeIPv6:jE,removeDotSegments:di,recomposeAuthority:FE,normalizeComponentEncoding:In,isIPv4:TE,nonSimpleDomain:kE}=Mo(),{SCHEMES:AE,getSchemeHandler:ip}=rp();function DE(e,t){if(typeof e==="string")e=Ye(pt(e,t),t);else if(typeof e==="object")e=pt(Ye(e,t),t);return e}function NE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=np(pt(e,i),pt(t,i),i,!0);return i.skipEscape=!0,Ye(n,i)}function np(e,t,r,i){let n={};if(!i)e=pt(Ye(e,r),r),t=pt(Ye(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=di(t.path||""),n.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=di(t.path||""),n.query=t.query;else{if(!t.path)if(n.path=e.path,t.query!==void 0)n.query=t.query;else n.query=e.query;else{if(t.path[0]==="/")n.path=di(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)n.path="/"+t.path;else if(!e.path)n.path=t.path;else n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;n.path=di(n.path)}n.query=t.query}n.userinfo=e.userinfo,n.host=e.host,n.port=e.port}n.scheme=e.scheme}return n.fragment=t.fragment,n}function LE(e,t,r){if(typeof e==="string")e=unescape(e),e=Ye(In(pt(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=Ye(In(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=Ye(In(pt(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=Ye(In(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function Ye(e,t){let r={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:""},i=Object.assign({},t),n=[],s=ip(i.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,i);if(r.path!==void 0)if(!i.skipEscape){if(r.path=escape(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=unescape(r.path);if(i.reference!=="suffix"&&r.scheme)n.push(r.scheme,":");let o=FE(r);if(o!==void 0){if(i.reference!=="suffix")n.push("//");if(n.push(o),r.path&&r.path[0]!=="/")n.push("/")}if(r.path!==void 0){let a=r.path;if(!i.absolutePath&&(!s||!s.absolutePath))a=di(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);n.push(a)}if(r.query!==void 0)n.push("?",r.query);if(r.fragment!==void 0)n.push("#",r.fragment);return n.join("")}var qE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pt(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(qE);if(s){if(i.scheme=s[1],i.userinfo=s[3],i.host=s[4],i.port=parseInt(s[5],10),i.path=s[6]||"",i.query=s[7],i.fragment=s[8],isNaN(i.port))i.port=s[5];if(i.host)if(TE(i.host)===!1){let d=jE(i.host);i.host=d.host.toLowerCase(),n=d.isIPV6}else n=!0;if(i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path)i.reference="same-document";else if(i.scheme===void 0)i.reference="relative";else if(i.fragment===void 0)i.reference="absolute";else i.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==i.reference)i.error=i.error||"URI is not a "+r.reference+" reference.";let o=ip(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&kE(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(a){i.error=i.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(i.scheme!==void 0)i.scheme=unescape(i.scheme);if(i.host!==void 0)i.host=unescape(i.host)}if(i.path)i.path=escape(unescape(i.path));if(i.fragment)i.fragment=encodeURI(decodeURIComponent(i.fragment))}if(o&&o.parse)o.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}var Go={SCHEMES:AE,normalize:DE,resolve:NE,resolveComponent:np,equal:LE,serialize:Ye,parse:pt};Sn.exports=Go;Sn.exports.default=Go;Sn.exports.fastUri=Go});var ap=P(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});var op=sp();op.code='require("ajv/dist/runtime/uri").default';Vo.default=op});var Wo=P(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var ME=hr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return ME.KeywordCxt}});var yr=j();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return yr._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return yr.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return yr.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return yr.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return yr.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return yr.CodeGen}});var UE=ai(),pp=gr(),BE=Po(),ui=ci(),GE=j(),pi=ni(),xn=ii(),zo=D(),lp=Wu(),VE=ap(),fp=(e,t)=>new RegExp(e,t);fp.code="new RegExp";var KE=["removeAdditional","useDefaults","coerceTypes"],zE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),WE={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."},HE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cp=200;function JE(e){var t,r,i,n,s,o,a,d,u,l,c,p,f,m,h,g,_,b,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=J===!0||J===void 0?1:J||0,Re=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:fp,Hr=(n=e.uriResolver)!==null&&n!==void 0?n:VE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(d=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&d!==void 0?d:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(c=e.strictTuples)!==null&&c!==void 0?c:V)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:V)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Z,regExp:Re}:{optimize:Z,regExp:Re},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:cp,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:cp,meta:(_=e.meta)!==null&&_!==void 0?_:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(x=e.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(R=e.int32range)!==null&&R!==void 0?R:!0,uriResolver:Hr}}class Rn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...JE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new GE.ValueScope({scope:{},prefixes:zE,es5:t,lines:r}),this.logger=tI(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,BE.getRules)(),dp.call(this,WE,e,"NOT SUPPORTED"),dp.call(this,HE,e,"DEPRECATED","warn"),this._metaOpts=ZE.call(this),e.formats)YE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)XE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);QE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=lp;if(r==="id")i={...lp},i.id=i.$id,delete i.$id;if(t&&e)this.addMetaSchema(i,i[r],!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 r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);if(!("$async"in r))this.errors=r.errors;return i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(u,l){await n.call(this,u.$schema);let c=this._addSchema(u,l);return c.validate||s.call(this,c)}async function n(u){if(u&&!this.getSchema(u))await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(l){if(!(l instanceof pp.default))throw l;return o.call(this,l),await a.call(this,l.missingSchema),s.call(this,u)}}function o({missingSchema:u,missingRef:l}){if(this.refs[u])throw Error(`AnySchema ${u} is loaded but ${l} cannot be resolved`)}async function a(u){let l=await d.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function d(u){let l=this._loading[u];if(l)return l;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let n;if(typeof e==="object"){let{schemaId:s}=this.opts;if(n=e[s],n!==void 0&&typeof n!="string")throw Error(`schema ${s} must be string`)}return t=(0,pi.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(r,e);if(!i&&t){let n="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(n);else throw Error(n)}return i}getSchema(e){let t;while(typeof(t=up.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ui.SchemaEnv({schema:{},schemaId:r});if(t=ui.resolveSchema.call(this,i,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=up.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 r=e[this.opts.schemaId];if(r)r=(0,pi.normalizeId)(r),delete this.schemas[r],delete this.refs[r];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 r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(iI.call(this,r,t),!t)return(0,zo.eachItem)(r,(n)=>Ko.call(this,n)),this;sI.call(this,t);let i={...t,type:(0,xn.getJSONTypes)(t.type),schemaType:(0,xn.getJSONTypes)(t.schemaType)};return(0,zo.eachItem)(r,i.type.length===0?(n)=>Ko.call(this,n,i):(n)=>i.type.forEach((s)=>Ko.call(this,n,i,s))),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 r of t.rules){let i=r.rules.findIndex((n)=>n.keyword===e);if(i>=0)r.rules.splice(i,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:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((i)=>`${r}${i.instancePath} ${i.message}`).reduce((i,n)=>i+t+n)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let n=i.split("/").slice(1),s=e;for(let o of n)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:d}=a.definition,u=s[o];if(d&&u)s[o]=mp(u)}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];if(!t||t.test(r)){if(typeof i=="string")delete e[r];else if(i&&!i.meta)this._cache.delete(i.schema),delete e[r]}}}_addSchema(e,t,r,i=this.opts.validateSchema,n=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];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;r=(0,pi.normalizeId)(s||r);let d=pi.getSchemaRefs.call(this,e,r);if(a=new ui.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:d}),this._cache.set(a.schema,a),n&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(i)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 ui.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{ui.compileSchema.call(this,e)}finally{this.opts=t}}}Rn.ValidationError=UE.default;Rn.MissingRefError=pp.default;ie.default=Rn;function dp(e,t,r,i="error"){for(let n in e){let s=n;if(s in t)this.logger[i](`${r}: option ${n}. ${e[s]}`)}}function up(e){return e=(0,pi.normalizeId)(e),this.schemas[e]||this.refs[e]}function QE(){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 YE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function XE(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 r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function ZE(){let e={...this.opts};for(let t of KE)delete e[t];return e}var eI={log(){},warn(){},error(){}};function tI(e){if(e===!1)return eI;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 rI=/^[a-z_$][a-z0-9_$:-]*$/i;function iI(e,t){let{RULES:r}=this;if((0,zo.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!rI.test(i))throw Error(`Keyword ${i} 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 Ko(e,t,r){var i;let n=t===null||t===void 0?void 0:t.post;if(r&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:d})=>d===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,xn.getJSONTypes)(t.type),schemaType:(0,xn.getJSONTypes)(t.schemaType)}};if(t.before)nI.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((d)=>this.addKeyword(d))}function nI(e,t,r){let i=e.rules.findIndex((n)=>n.keyword===r);if(i>=0)e.rules.splice(i,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function sI(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=mp(t);e.validateSchema=this.compile(t,!0)}var oI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mp(e){return{anyOf:[e,oI]}}});var hp=P(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var aI={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ho.default=aI});var jn=P(function(qt){Object.defineProperty(qt,"__esModule",{value:!0});qt.callRef=qt.getValidate=void 0;var lI=gr(),gp=je(),we=j(),_r=Oe(),yp=ci(),Cn=D(),cI={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:d}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return c();let l=yp.resolveRef.call(d,u,n,r);if(l===void 0)throw new lI.default(i.opts.uriResolver,n,r);if(l instanceof yp.SchemaEnv)return p(l);return f(l);function c(){if(s===u)return On(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return On(e,we._`${m}.validate`,u,u.$async)}function p(m){let h=_p(e,m);On(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,we.stringify)(m)}:{ref:m}),g=t.name("valid"),_=e.subschema({schema:m,dataTypes:[],schemaPath:we.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(_),e.ok(g)}}};function _p(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):we._`${r.scopeValue("wrapper",{ref:t})}.validate`}qt.getValidate=_p;function On(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:d}=s,u=d.passContext?_r.default.this:we.nil;if(i)l();else c();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(we._`await ${(0,gp.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(we._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function c(){e.result((0,gp.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=we._`${m}.errors`;n.assign(_r.default.vErrors,we._`${_r.default.vErrors} === null ? ${h} : ${_r.default.vErrors}.concat(${h})`),n.assign(_r.default.errors,we._`${_r.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=Cn.mergeEvaluated.props(n,g.props,s.props)}else{let _=n.var("props",we._`${m}.evaluated.props`);s.props=Cn.mergeEvaluated.props(n,_,s.props,we.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=Cn.mergeEvaluated.items(n,g.items,s.items)}else{let _=n.var("items",we._`${m}.evaluated.items`);s.items=Cn.mergeEvaluated.items(n,_,s.items,we.Name)}}}qt.callRef=On;qt.default=cI});var Qo=P(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var dI=hp(),uI=jn(),pI=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dI.default,uI.default];Jo.default=pI});var bp=P(function(Yo){Object.defineProperty(Yo,"__esModule",{value:!0});var Fn=j(),Rt=Fn.operators,Tn={maximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},minimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},exclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},exclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},fI={message:({keyword:e,schemaCode:t})=>Fn.str`must be ${Tn[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Fn._`{comparison: ${Tn[e].okStr}, limit: ${t}}`},mI={keyword:Object.keys(Tn),type:"number",schemaType:"number",$data:!0,error:fI,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(Fn._`${r} ${Tn[t].fail} ${i} || isNaN(${r})`)}};Yo.default=mI});var Pp=P(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var fi=j(),hI={message:({schemaCode:e})=>fi.str`must be multiple of ${e}`,params:({schemaCode:e})=>fi._`{multipleOf: ${e}}`},gI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hI,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?fi._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:fi._`${o} !== parseInt(${o})`;e.fail$data(fi._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Xo.default=gI});var wp=P(function(Zo){Object.defineProperty(Zo,"__esModule",{value:!0});function vp(e){let t=e.length,r=0,i=0,n;while(i<t)if(r++,n=e.charCodeAt(i++),n>=55296&&n<=56319&&i<t){if(n=e.charCodeAt(i),(n&64512)===56320)i++}return r}Zo.default=vp;vp.code='require("ajv/dist/runtime/ucs2length").default'});var $p=P(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Mt=j(),yI=D(),_I=wp(),bI={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return Mt.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>Mt._`{limit: ${e}}`},PI={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bI,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?Mt.operators.GT:Mt.operators.LT,o=n.opts.unicode===!1?Mt._`${r}.length`:Mt._`${(0,yI.useFunc)(e.gen,_I.default)}(${r})`;e.fail$data(Mt._`${o} ${s} ${i}`)}};ea.default=PI});var Ep=P(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var vI=je(),kn=j(),wI={message:({schemaCode:e})=>kn.str`must match pattern "${e}"`,params:({schemaCode:e})=>kn._`{pattern: ${e}}`},$I={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:wI,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?kn._`(new RegExp(${n}, ${o}))`:(0,vI.usePattern)(e,i);e.fail$data(kn._`!${a}.test(${t})`)}};ta.default=$I});var Ip=P(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var mi=j(),EI={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return mi.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>mi._`{limit: ${e}}`},II={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EI,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?mi.operators.GT:mi.operators.LT;e.fail$data(mi._`Object.keys(${r}).length ${n} ${i}`)}};ra.default=II});var Sp=P(function(ia){Object.defineProperty(ia,"__esModule",{value:!0});var hi=je(),gi=j(),SI=D(),xI={message:({params:{missingProperty:e}})=>gi.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>gi._`{missingProperty: ${e}}`},RI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xI,code(e){let{gen:t,schema:r,schemaCode:i,data:n,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let d=r.length>=a.loopRequired;if(o.allErrors)u();else l();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,SI.checkStrictMode)(o,_,o.opts.strictRequired)}}function u(){if(d||s)e.block$data(gi.nil,c);else for(let f of r)(0,hi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(d||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,hi.checkMissingProp)(e,r,f)),(0,hi.reportMissingProp)(e,f),t.else()}function c(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,hi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,hi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,gi.not)(m),()=>{e.error(),t.break()})},gi.nil)}}};ia.default=RI});var xp=P(function(na){Object.defineProperty(na,"__esModule",{value:!0});var yi=j(),CI={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return yi.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>yi._`{limit: ${e}}`},OI={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CI,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?yi.operators.GT:yi.operators.LT;e.fail$data(yi._`${r}.length ${n} ${i}`)}};na.default=OI});var An=P(function(sa){Object.defineProperty(sa,"__esModule",{value:!0});var Rp=Ro();Rp.code='require("ajv/dist/runtime/equal").default';sa.default=Rp});var Cp=P(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var oa=ii(),ne=j(),jI=D(),FI=An(),TI={message:({params:{i:e,j:t}})=>ne.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>ne._`{i: ${e}, j: ${t}}`},kI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:TI,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let d=t.let("valid"),u=s.items?(0,oa.getSchemaTypes)(s.items):[];e.block$data(d,l,ne._`${o} === false`),e.ok(d);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(d,!0),t.if(ne._`${m} > 1`,()=>(c()?p:f)(m,h))}function c(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),_=(0,oa.checkDataTypes)(u,g,a.opts.strictNumbers,oa.DataType.Wrong),b=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(_,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${b}[${g}] == "number"`,()=>{t.assign(h,ne._`${b}[${g}]`),e.error(),t.assign(d,!1).break()}).code(ne._`${b}[${g}] = ${m}`)})}function f(m,h){let g=(0,jI.useFunc)(t,FI.default),_=t.name("outer");t.label(_).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(d,!1).break(_)})))}}};aa.default=kI});var Op=P(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var la=j(),AI=D(),DI=An(),NI={message:"must be equal to constant",params:({schemaCode:e})=>la._`{allowedValue: ${e}}`},LI={keyword:"const",$data:!0,error:NI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(la._`!${(0,AI.useFunc)(t,DI.default)}(${r}, ${n})`);else e.fail(la._`${s} !== ${r}`)}};ca.default=LI});var jp=P(function(da){Object.defineProperty(da,"__esModule",{value:!0});var _i=j(),qI=D(),MI=An(),UI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>_i._`{allowedValues: ${e}}`},BI={keyword:"enum",schemaType:"array",$data:!0,error:UI,code(e){let{gen:t,data:r,$data:i,schema:n,schemaCode:s,it:o}=e;if(!i&&n.length===0)throw Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,d,u=()=>d!==null&&d!==void 0?d:d=(0,qI.useFunc)(t,MI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,c);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,_i.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function c(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(_i._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?_i._`${u()}(${r}, ${f}[${m}])`:_i._`${r} === ${h}`}}};da.default=BI});var pa=P(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var GI=bp(),VI=Pp(),KI=$p(),zI=Ep(),WI=Ip(),HI=Sp(),JI=xp(),QI=Cp(),YI=Op(),XI=jp(),ZI=[GI.default,VI.default,KI.default,zI.default,WI.default,HI.default,JI.default,QI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},YI.default,XI.default];ua.default=ZI});var ma=P(function(bi){Object.defineProperty(bi,"__esModule",{value:!0});bi.validateAdditionalItems=void 0;var Ut=j(),fa=D(),eS={message:({params:{len:e}})=>Ut.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ut._`{limit: ${e}}`},tS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:eS,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,fa.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Fp(e,i)}};function Fp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",Ut._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(Ut._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,fa.alwaysValidSchema)(o,i)){let u=r.var("valid",Ut._`${a} <= ${t.length}`);r.if((0,Ut.not)(u),()=>d(u)),e.ok(u)}function d(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:fa.Type.Num},u),!o.allErrors)r.if((0,Ut.not)(u),()=>r.break())})}}bi.validateAdditionalItems=Fp;bi.default=tS});var ha=P(function(Pi){Object.defineProperty(Pi,"__esModule",{value:!0});Pi.validateTuple=void 0;var Tp=j(),Dn=D(),rS=je(),iS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return kp(e,"additionalItems",t);if(r.items=!0,(0,Dn.alwaysValidSchema)(r,t))return;e.ok((0,rS.validateArray)(e))}};function kp(e,t,r=e.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=e;if(l(n),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Dn.mergeEvaluated.items(i,r.length,a.items);let d=i.name("valid"),u=i.const("len",Tp._`${s}.length`);r.forEach((c,p)=>{if((0,Dn.alwaysValidSchema)(a,c))return;i.if(Tp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},d)),e.ok(d)});function l(c){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===c.minItems&&(m===c.maxItems||c[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Dn.checkStrictMode)(a,g,p.strictTuples)}}}Pi.validateTuple=kp;Pi.default=iS});var Ap=P(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var nS=ha(),sS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,nS.validateTuple)(e,"items")};ga.default=sS});var Np=P(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var Dp=j(),oS=D(),aS=je(),lS=ma(),cS={message:({params:{len:e}})=>Dp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dp._`{limit: ${e}}`},dS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cS,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,oS.alwaysValidSchema)(i,t))return;if(n)(0,lS.validateAdditionalItems)(e,n);else e.ok((0,aS.validateArray)(e))}};ya.default=dS});var Lp=P(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var Te=j(),Nn=D(),uS={message:({params:{min:e,max:t}})=>t===void 0?Te.str`must contain at least ${e} valid item(s)`:Te.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Te._`{minContains: ${e}}`:Te._`{minContains: ${e}, maxContains: ${t}}`},pS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:uS,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:d,maxContains:u}=i;if(s.opts.next)o=d===void 0?1:d,a=u;else o=1;let l=t.const("len",Te._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Nn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Nn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Nn.alwaysValidSchema)(s,r)){let h=Te._`${l} >= ${o}`;if(a!==void 0)h=Te._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let c=t.name("valid");if(a===void 0&&o===1)f(c,()=>t.if(c,()=>t.break()));else if(o===0){if(t.let(c,!0),a!==void 0)t.if(Te._`${n}.length > 0`,p)}else t.let(c,!1),p();e.result(c,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,l,(_)=>{e.subschema({keyword:"contains",dataProp:_,dataPropType:Nn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Te._`${h}++`),a===void 0)t.if(Te._`${h} >= ${o}`,()=>t.assign(c,!0).break());else if(t.if(Te._`${h} > ${a}`,()=>t.assign(c,!1).break()),o===1)t.assign(c,!0);else t.if(Te._`${h} >= ${o}`,()=>t.assign(c,!0))}}};_a.default=pS});var Ln=P(function(Xe){Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var ba=j(),fS=D(),vi=je();Xe.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return ba.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>ba._`{property: ${e},
|
|
8
8
|
missingProperty: ${i},
|
|
9
9
|
depsCount: ${t},
|
|
10
|
-
deps: ${r}}`};var OI={keyword:"dependencies",type:"object",schemaType:"object",error:We.error,code(e){let[t,r]=TI(e);$p(e,t),Ep(e,r)}};function TI({schema:e}){let t={},r={};for(let i in e){if(i==="__proto__")continue;let n=Array.isArray(e[i])?t:r;n[i]=e[i]}return[t,r]}function $p(e,t=e.schema){let{gen:r,data:i,it:n}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,pi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(c,()=>{for(let u of a)(0,pi.checkReportMissingProp)(e,u)});else r.if(da._`${c} && (${(0,pi.checkMissingProp)(e,a,s)})`),(0,pi.reportMissingProp)(e,s),r.else()}}We.validatePropertyDeps=$p;function Ep(e,t=e.schema){let{gen:r,data:i,keyword:n,it:s}=e,o=r.name("valid");for(let a in t){if((0,FI.alwaysValidSchema)(s,t[a]))continue;r.if((0,pi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}We.validateSchemaDeps=Ep;We.default=OI});var Sp=b(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var Ip=F(),AI=D(),kI={message:"property name must be valid",params:({params:e})=>Ip._`{propertyName: ${e.propertyName}}`},DI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kI,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,AI.alwaysValidSchema)(n,r))return;let s=t.name("valid");t.forIn("key",i,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,Ip.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};ua.default=DI});var fa=b(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});var Fn=Ce(),Me=F(),NI=Re(),On=D(),LI={message:"must NOT have additional properties",params:({params:e})=>Me._`{additionalProperty: ${e.additionalProperty}}`},qI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:LI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,On.alwaysValidSchema)(o,r))return;let u=(0,Fn.allSchemaProperties)(i.properties),l=(0,Fn.allSchemaProperties)(i.patternProperties);d(),e.ok(Me._`${s} === ${NI.default.errors}`);function d(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let P=(0,On.schemaRefOrVal)(o,i.properties,"properties");y=(0,Fn.isOwnProperty)(t,P,g)}else if(u.length)y=(0,Me.or)(...u.map((P)=>Me._`${g} === ${P}`));else y=Me.nil;if(l.length)y=(0,Me.or)(y,...l.map((P)=>Me._`${(0,Fn.usePattern)(e,P)}.test(${g})`));return(0,Me.not)(y)}function f(g){t.code(Me._`delete ${n}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,On.alwaysValidSchema)(o,r)){let y=t.name("valid");if(c.removeAdditional==="failing")h(g,y,!1),t.if((0,Me.not)(y),()=>{e.reset(),f(g)});else if(h(g,y),!a)t.if((0,Me.not)(y),()=>t.break())}}function h(g,y,P){let v={keyword:"additionalProperties",dataProp:g,dataPropType:On.Type.Str};if(P===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,y)}}};pa.default=qI});var Cp=b(function(ha){Object.defineProperty(ha,"__esModule",{value:!0});var MI=cr(),xp=Ce(),ma=D(),Rp=fa(),UI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e;if(s.opts.removeAdditional==="all"&&i.additionalProperties===void 0)Rp.default.code(new MI.KeywordCxt(s,Rp.default,"additionalProperties"));let o=(0,xp.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=ma.mergeEvaluated.props(t,(0,ma.toHash)(o),s.props);let a=o.filter((d)=>!(0,ma.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a){if(u(d))l(d);else{if(t.if((0,xp.propertyInData)(t,n,d,s.opts.ownProperties)),l(d),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(d),e.ok(c)}function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ha.default=UI});var Tp=b(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var jp=Ce(),Tn=F(),Fp=D(),Op=D(),BI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:i,parentSchema:n,it:s}=e,{opts:o}=s,a=(0,jp.allSchemaProperties)(r),c=a.filter((h)=>(0,Fp.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&n.properties,l=t.name("valid");if(s.props!==!0&&!(s.props instanceof Tn.Name))s.props=(0,Op.evaluatedPropsToName)(t,s.props);let{props:d}=s;p();function p(){for(let h of a){if(u)f(h);if(s.allErrors)m(h);else t.var(l,!0),m(h),t.if(l)}}function f(h){for(let g in u)if(new RegExp(h).test(g))(0,Fp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Tn._`${(0,jp.usePattern)(e,h)}.test(${g})`,()=>{let y=c.includes(h);if(!y)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Op.Type.Str},l);if(s.opts.unevaluated&&d!==!0)t.assign(Tn._`${d}[${g}]`,!0);else if(!y&&!s.allErrors)t.if((0,Tn.not)(l),()=>t.break())})})}}};ga.default=BI});var Ap=b(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var GI=D(),VI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,GI.alwaysValidSchema)(i,r)){e.fail();return}let n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ya.default=VI});var kp=b(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var KI=Ce(),zI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:KI.validateUnion,error:{message:"must match a schema in anyOf"}};_a.default=zI});var Dp=b(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var An=F(),WI=D(),HI={message:"must match exactly one schema in oneOf",params:({params:e})=>An._`{passingSchemas: ${e.passing}}`},JI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:HI,code(e){let{gen:t,schema:r,parentSchema:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;if((0,WI.alwaysValidSchema)(n,l))t.var(c,!0);else p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c);if(d>0)t.if(An._`${c} && ${o}`).assign(o,!1).assign(a,An._`[${a}, ${d}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,d),p)e.mergeEvaluated(p,An.Name)})})}}};Pa.default=JI});var Np=b(function(ba){Object.defineProperty(ba,"__esModule",{value:!0});var QI=D(),YI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((s,o)=>{if((0,QI.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};ba.default=YI});var Mp=b(function(va){Object.defineProperty(va,"__esModule",{value:!0});var kn=F(),qp=D(),XI={message:({params:e})=>kn.str`must match "${e.ifClause}" schema`,params:({params:e})=>kn._`{failingKeyword: ${e.ifClause}}`},ZI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:XI,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,qp.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=Lp(i,"then"),s=Lp(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),n&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else if(n)t.if(a,u("then"));else t.if((0,kn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),d)t.assign(d,kn._`${l}`);else e.setParams({ifClause:l})}}}};function Lp(e,t){let r=e.schema[t];return r!==void 0&&!(0,qp.alwaysValidSchema)(e,r)}va.default=ZI});var Up=b(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});var eS=D(),tS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,eS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wa.default=tS});var Ea=b(function($a){Object.defineProperty($a,"__esModule",{value:!0});var rS=sa(),iS=Pp(),nS=oa(),sS=vp(),oS=wp(),aS=jn(),lS=Sp(),cS=fa(),dS=Cp(),uS=Tp(),pS=Ap(),fS=kp(),mS=Dp(),hS=Np(),gS=Mp(),yS=Up();function _S(e=!1){let t=[pS.default,fS.default,mS.default,hS.default,gS.default,yS.default,lS.default,cS.default,aS.default,dS.default,uS.default];if(e)t.push(iS.default,sS.default);else t.push(rS.default,nS.default);return t.push(oS.default),t}$a.default=_S});var Sa=b(function(fi){Object.defineProperty(fi,"__esModule",{value:!0});fi.dynamicAnchor=void 0;var Ia=F(),PS=Re(),Bp=ei(),bS=$n(),vS={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>Gp(e,e.schema)};function Gp(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=Ia._`${PS.default.dynamicAnchors}${(0,Ia.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:wS(e);r.if(Ia._`!${n}`,()=>r.assign(n,s))}fi.dynamicAnchor=Gp;function wS(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:c}=i.opts,u=new Bp.SchemaEnv({schema:r,schemaId:c,root:n,baseId:s,localRefs:o,meta:a});return Bp.compileSchema.call(i,u),(0,bS.getValidate)(e,u)}fi.default=vS});var xa=b(function(mi){Object.defineProperty(mi,"__esModule",{value:!0});mi.dynamicRef=void 0;var Vp=F(),$S=Re(),Kp=$n(),ES={keyword:"$dynamicRef",schemaType:"string",code:(e)=>zp(e,e.schema)};function zp(e,t){let{gen:r,keyword:i,it:n}=e;if(t[0]!=="#")throw Error(`"${i}" only supports hash fragment reference`);let s=t.slice(1);if(n.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",Vp._`${$S.default.dynamicAnchors}${(0,Vp.getProperty)(s)}`);r.if(u,a(u,c),a(n.validateName,c))}else a(n.validateName,c)()}function a(c,u){return u?()=>r.block(()=>{(0,Kp.callRef)(e,c),r.let(u,!0)}):()=>(0,Kp.callRef)(e,c)}}mi.dynamicRef=zp;mi.default=ES});var Wp=b(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var IS=Sa(),SS=D(),xS={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,IS.dynamicAnchor)(e,"");else(0,SS.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ra.default=xS});var Hp=b(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var RS=xa(),CS={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,RS.dynamicRef)(e,e.schema)};Ca.default=CS});var Jp=b(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var jS=Sa(),FS=xa(),OS=Wp(),TS=Hp(),AS=[jS.default,FS.default,OS.default,TS.default];ja.default=AS});var Yp=b(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var Qp=jn(),kS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Qp.error,code:(e)=>(0,Qp.validatePropertyDeps)(e)};Fa.default=kS});var Xp=b(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var DS=jn(),NS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,DS.validateSchemaDeps)(e)};Oa.default=NS});var Zp=b(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});var LS=D(),qS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,LS.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ta.default=qS});var ef=b(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});var MS=Yp(),US=Xp(),BS=Zp(),GS=[MS.default,US.default,BS.default];Aa.default=GS});var rf=b(function(ka){Object.defineProperty(ka,"__esModule",{value:!0});var $t=F(),tf=D(),VS=Re(),KS={message:"must NOT have unevaluated properties",params:({params:e})=>$t._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},zS={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:KS,code(e){let{gen:t,schema:r,data:i,errsCount:n,it:s}=e;if(!n)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof $t.Name)t.if($t._`${a} !== true`,()=>t.forIn("key",i,(d)=>t.if(u(a,d),()=>c(d))));else if(a!==!0)t.forIn("key",i,(d)=>a===void 0?c(d):t.if(l(a,d),()=>c(d)));s.props=!0,e.ok($t._`${n} === ${VS.default.errors}`);function c(d){if(r===!1){if(e.setParams({unevaluatedProperty:d}),e.error(),!o)t.break();return}if(!(0,tf.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tf.Type.Str},p),!o)t.if((0,$t.not)(p),()=>t.break())}}function u(d,p){return $t._`!${d} || !${d}[${p}]`}function l(d,p){let f=[];for(let m in d)if(d[m]===!0)f.push($t._`${p} !== ${m}`);return(0,$t.and)(...f)}}};ka.default=zS});var sf=b(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});var Dt=F(),nf=D(),WS={message:({params:{len:e}})=>Dt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dt._`{limit: ${e}}`},HS={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:WS,code(e){let{gen:t,schema:r,data:i,it:n}=e,s=n.items||0;if(s===!0)return;let o=t.const("len",Dt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Dt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,nf.alwaysValidSchema)(n,r)){let c=t.var("valid",Dt._`${o} <= ${s}`);t.if((0,Dt.not)(c),()=>a(c,s)),e.ok(c)}n.items=!0;function a(c,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:nf.Type.Num},c),!n.allErrors)t.if((0,Dt.not)(c),()=>t.break())})}}};Da.default=HS});var of=b(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var JS=rf(),QS=sf(),YS=[JS.default,QS.default];Na.default=YS});var af=b(function(La){Object.defineProperty(La,"__esModule",{value:!0});var Q=F(),XS={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},ZS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XS,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),y=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(y,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(y,h)),e.fail$data((0,Q.or)(P(),v()));function P(){if(c.strictSchema===!1)return Q.nil;return Q._`${o} && !${y}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${y}(${i}) : ${y}(${i}))`:Q._`${y}(${i})`,I=Q._`(typeof ${y} == "function" ? ${w} : ${y}.test(${i}))`;return Q._`${y} && ${y} !== true && ${g} === ${t} && !${I}`}}function f(){let m=d.formats[s];if(!m){P();return}if(m===!0)return;let[h,g,y]=v(m);if(h===t)e.pass(w());function P(){if(c.strictSchema===!1){d.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(I){let E=I instanceof RegExp?(0,Q.regexpCode)(I):c.code.formats?Q._`${c.code.formats}${(0,Q.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:I,code:E});if(typeof I=="object"&&!(I instanceof RegExp))return[I.type||"string",I.validate,Q._`${x}.validate`];return["string",I,x]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw Error("async format in sync schema");return Q._`await ${y}(${i})`}return typeof g=="function"?Q._`${y}(${i})`:Q._`${y}.test(${i})`}}}};La.default=ZS});var Ma=b(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var ex=af(),tx=[ex.default];qa.default=tx});var Ua=b(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cf=b(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var rx=Uo(),ix=ia(),nx=Ea(),sx=Jp(),ox=ef(),ax=of(),lx=Ma(),lf=Ua(),cx=[sx.default,rx.default,ix.default,(0,nx.default)(!0),lx.default,lf.metadataVocabulary,lf.contentVocabulary,ox.default,ax.default];Ba.default=cx});var uf=b(function(Dn){Object.defineProperty(Dn,"__esModule",{value:!0});Dn.DiscrError=void 0;var df;(function(e){e.Tag="tag",e.Mapping="mapping"})(df||(Dn.DiscrError=df={}))});var Ka=b(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var mr=F(),Ga=uf(),pf=ei(),dx=dr(),ux=D(),px={message:({params:{discrError:e,tagName:t}})=>e===Ga.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>mr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},fx={keyword:"discriminator",type:"object",schemaType:"object",error:px,code(e){let{gen:t,data:r,schema:i,parentSchema:n,it:s}=e,{oneOf:o}=n;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(i.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",mr._`${r}${(0,mr.getProperty)(a)}`);t.if(mr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ga.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(mr._`${u} === ${m}`),t.assign(c,d(f[m]));t.else(),e.error(!1,{discrError:Ga.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,mr.Name),m}function p(){var f;let m={},h=y(n),g=!0;for(let w=0;w<o.length;w++){let I=o[w];if((I===null||I===void 0?void 0:I.$ref)&&!(0,ux.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=pf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof pf.SchemaEnv)I=I.schema;if(I===void 0)throw new dx.default(s.opts.uriResolver,s.baseId,x)}let E=(f=I===null||I===void 0?void 0:I.properties)===null||f===void 0?void 0:f[a];if(typeof E!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(I)),P(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function P(w,I){if(w.const)v(w.const,I);else if(w.enum)for(let E of w.enum)v(E,I);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(w,I){if(typeof w!="string"||w in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[w]=I}}}};Va.default=fx});var ff=b(function(Sk,mx){mx.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 mf=b(function(xk,hx){hx.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 hf=b(function(Rk,gx){gx.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 gf=b(function(Ck,yx){yx.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 yf=b(function(jk,_x){_x.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 _f=b(function(Fk,Px){Px.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 Pf=b(function(Ok,bx){bx.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 bf=b(function(Tk,vx){vx.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 vf=b(function(za){Object.defineProperty(za,"__esModule",{value:!0});var wx=ff(),$x=mf(),Ex=hf(),Ix=gf(),Sx=yf(),xx=_f(),Rx=Pf(),Cx=bf(),jx=["/properties"];function Fx(e){return[wx,$x,Ex,Ix,Sx,t(this,xx),Rx,t(this,Cx)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,jx):i}}za.default=Fx});var Ja=b(function(z,Ha){Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv2020=void 0;var Ox=Lo(),Tx=cf(),Ax=Ka(),kx=vf(),Wa="https://json-schema.org/draft/2020-12/schema";class hi extends Ox.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),Tx.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(Ax.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;kx.default.call(this,e),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}}z.Ajv2020=hi;Ha.exports=z=hi;Ha.exports.Ajv2020=hi;Object.defineProperty(z,"__esModule",{value:!0});z.default=hi;var Dx=cr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return Dx.KeywordCxt}});var hr=F();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var Nx=Xr();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return Nx.default}});var Lx=dr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return Lx.default}})});var Zh=b(function(et){Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(e,t){return{validate:e,compare:t}}et.fullFormats={date:Ze(Jh,Ul),time:Ze(ql(!0),Bl),"date-time":Ze(zh(!0),Yh),"iso-time":Ze(ql(),Qh),"iso-date-time":Ze(zh(),Xh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pF,"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:PF,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:fF,int32:{type:"number",validate:gF},int64:{type:"number",validate:yF},float:{type:"number",validate:Hh},double:{type:"number",validate:Hh},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ul),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bl),"date-time":Ze(/^\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,Yh),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Qh),"iso-date-time":Ze(/^\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,Xh),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};et.formatNames=Object.keys(et.fullFormats);function aF(e){return e%4===0&&(e%100!==0||e%400===0)}var lF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,cF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Jh(e){let t=lF.exec(e);if(!t)return!1;let r=+t[1],i=+t[2],n=+t[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&aF(r)?29:cF[i])}function Ul(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ql(e){return function(r){let i=Ll.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],c=i[5]==="-"?-1:1,u=+(i[6]||0),l=+(i[7]||0);if(u>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function Bl(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),i=new Date("2020-01-01T"+t).valueOf();if(!(r&&i))return;return r-i}function Qh(e,t){if(!(e&&t))return;let r=Ll.exec(e),i=Ll.exec(t);if(!(r&&i))return;if(e=r[1]+r[2]+r[3],t=i[1]+i[2]+i[3],e>t)return 1;if(e<t)return-1;return 0}var Ml=/t|\s/i;function zh(e){let t=ql(e);return function(i){let n=i.split(Ml);return n.length===2&&Jh(n[0])&&t(n[1])}}function Yh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),i=new Date(t).valueOf();if(!(r&&i))return;return r-i}function Xh(e,t){if(!(e&&t))return;let[r,i]=e.split(Ml),[n,s]=t.split(Ml),o=Ul(r,n);if(o===void 0)return;return o||Bl(i,s)}var dF=/\/|:/,uF=/^(?:[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 pF(e){return dF.test(e)&&uF.test(e)}var Wh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function fF(e){return Wh.lastIndex=0,Wh.test(e)}var mF=-2147483648,hF=2147483647;function gF(e){return Number.isInteger(e)&&e<=hF&&e>=mF}function yF(e){return Number.isInteger(e)}function Hh(){return!0}var _F=/[^\\]\\Z/;function PF(e){if(_F.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var tg=b(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var bF=Uo(),vF=ia(),wF=Ea(),$F=Ma(),eg=Ua(),EF=[bF.default,vF.default,(0,wF.default)(),$F.default,eg.metadataVocabulary,eg.contentVocabulary];Gl.default=EF});var rg=b(function(Gq,IF){IF.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 ng=b(function(W,Vl){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var SF=Lo(),xF=tg(),RF=Ka(),ig=rg(),CF=["/properties"],bs="http://json-schema.org/draft-07/schema";class Di extends SF.default{_addVocabularies(){if(super._addVocabularies(),xF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(RF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ig,CF):ig;this.addMetaSchema(e,bs,!1),this.refs["http://json-schema.org/schema"]=bs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bs)?bs:void 0)}}W.Ajv=Di;Vl.exports=W=Di;Vl.exports.Ajv=Di;Object.defineProperty(W,"__esModule",{value:!0});W.default=Di;var jF=cr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return jF.KeywordCxt}});var Cr=F();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var FF=Xr();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return FF.default}});var OF=dr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return OF.default}})});var sg=b(function(jr){Object.defineProperty(jr,"__esModule",{value:!0});jr.formatLimitDefinition=void 0;var TF=ng(),Be=F(),Rt=Be.operators,vs={formatMaximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},formatMinimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},formatExclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},formatExclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},AF={message:({keyword:e,schemaCode:t})=>Be.str`should be ${vs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Be._`{comparison: ${vs[e].okStr}, limit: ${t}}`};jr.formatLimitDefinition={keyword:Object.keys(vs),type:"string",schemaType:"string",$data:!0,error:AF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new TF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",Be._`${p}[${c.schemaCode}]`);e.fail$data((0,Be.or)(Be._`typeof ${f} != "object"`,Be._`${f} instanceof RegExp`,Be._`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${n}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:o.code.formats?Be._`${o.code.formats}${(0,Be.getProperty)(p)}`:void 0});e.fail$data(d(m))}function d(p){return Be._`${p}.compare(${r}, ${i}) ${vs[n].fail} 0`}},dependencies:["format"]};var kF=(e)=>(e.addKeyword(jr.formatLimitDefinition),e);jr.default=kF});var cg=b(function(Ni,lg){Object.defineProperty(Ni,"__esModule",{value:!0});var Fr=Zh(),DF=sg(),Kl=F(),og=new Kl.Name("fullFormats"),NF=new Kl.Name("fastFormats"),zl=(e,t={keywords:!0})=>{if(Array.isArray(t))return ag(e,t,Fr.fullFormats,og),e;let[r,i]=t.mode==="fast"?[Fr.fastFormats,NF]:[Fr.fullFormats,og],n=t.formats||Fr.formatNames;if(ag(e,n,r,i),t.keywords)(0,DF.default)(e);return e};zl.get=(e,t="full")=>{let i=(t==="fast"?Fr.fastFormats:Fr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function ag(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=Kl._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}lg.exports=Ni=zl;Object.defineProperty(Ni,"__esModule",{value:!0});Ni.default=zl});var Xg=b(function(WM,Yg){Yg.exports=CO;function RO(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function CO(e){let t=RO(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 r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var yy=b(function(aU,gy){var VO=require("stream");class hy extends VO{#r=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.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=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)}}gy.exports=hy});class it extends Error{constructor(e,t,r){super(r);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class pt extends it{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Qi{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,r)=>{if(!this.argChoices.includes(t))throw new pt(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Yi(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Dc=require("events"),Zi=xe(require("child_process")),Ge=xe(require("path")),Br=xe(require("fs")),U=xe(require("process")),Nc=require("util");var Oc=require("util");class Xi{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((i)=>!i._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((i,n)=>i.name().localeCompare(n.name()));return t}compareOptions(e,t){let r=(i)=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((i)=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),n=r.long&&e._findOption(r.long);if(!i&&!n)t.push(r);else if(r.long&&!n)t.push(e.createOption(r.long,r.description));else if(r.short&&!i)t.push(e.createOption(r.short,r.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter((n)=>!n.hidden);t.push(...i)}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((r)=>Yi(r)).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((r,i)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+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((r)=>JSON.stringify(r)).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 r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}formatItemList(e,t,r){if(t.length===0)return[];return[r.styleTitle(e),...t,""]}groupItems(e,t,r){let i=new Map;return e.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[])}),t.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[]);i.get(s).push(n)}),i}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth??80;function n(l,d){return t.formatItem(l,r,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),i),""]);let a=t.visibleArguments(e).map((l)=>n(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(l)=>l.helpGroupHeading??"Options:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((d)=>n(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),s.join(`
|
|
11
|
-
`)}displayWidth(e){return
|
|
10
|
+
deps: ${r}}`};var mS={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(e){let[t,r]=hS(e);qp(e,t),Mp(e,r)}};function hS({schema:e}){let t={},r={};for(let i in e){if(i==="__proto__")continue;let n=Array.isArray(e[i])?t:r;n[i]=e[i]}return[t,r]}function qp(e,t=e.schema){let{gen:r,data:i,it:n}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let d=(0,vi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(d,()=>{for(let u of a)(0,vi.checkReportMissingProp)(e,u)});else r.if(ba._`${d} && (${(0,vi.checkMissingProp)(e,a,s)})`),(0,vi.reportMissingProp)(e,s),r.else()}}Xe.validatePropertyDeps=qp;function Mp(e,t=e.schema){let{gen:r,data:i,keyword:n,it:s}=e,o=r.name("valid");for(let a in t){if((0,fS.alwaysValidSchema)(s,t[a]))continue;r.if((0,vi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let d=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(d,o)},()=>r.var(o,!0)),e.ok(o)}}Xe.validateSchemaDeps=Mp;Xe.default=mS});var Bp=P(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var Up=j(),gS=D(),yS={message:"property name must be valid",params:({params:e})=>Up._`{propertyName: ${e.propertyName}}`},_S={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yS,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,gS.alwaysValidSchema)(n,r))return;let s=t.name("valid");t.forIn("key",i,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,Up.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};Pa.default=_S});var wa=P(function(va){Object.defineProperty(va,"__esModule",{value:!0});var qn=je(),Be=j(),bS=Oe(),Mn=D(),PS={message:"must NOT have additional properties",params:({params:e})=>Be._`{additionalProperty: ${e.additionalProperty}}`},vS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PS,code(e){let{gen:t,schema:r,parentSchema:i,data:n,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:d}=o;if(o.props=!0,d.removeAdditional!=="all"&&(0,Mn.alwaysValidSchema)(o,r))return;let u=(0,qn.allSchemaProperties)(i.properties),l=(0,qn.allSchemaProperties)(i.patternProperties);c(),e.ok(Be._`${s} === ${bS.default.errors}`);function c(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let _;if(u.length>8){let b=(0,Mn.schemaRefOrVal)(o,i.properties,"properties");_=(0,qn.isOwnProperty)(t,b,g)}else if(u.length)_=(0,Be.or)(...u.map((b)=>Be._`${g} === ${b}`));else _=Be.nil;if(l.length)_=(0,Be.or)(_,...l.map((b)=>Be._`${(0,qn.usePattern)(e,b)}.test(${g})`));return(0,Be.not)(_)}function f(g){t.code(Be._`delete ${n}[${g}]`)}function m(g){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,Mn.alwaysValidSchema)(o,r)){let _=t.name("valid");if(d.removeAdditional==="failing")h(g,_,!1),t.if((0,Be.not)(_),()=>{e.reset(),f(g)});else if(h(g,_),!a)t.if((0,Be.not)(_),()=>t.break())}}function h(g,_,b){let v={keyword:"additionalProperties",dataProp:g,dataPropType:Mn.Type.Str};if(b===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,_)}}};va.default=vS});var Kp=P(function(Ea){Object.defineProperty(Ea,"__esModule",{value:!0});var wS=hr(),Gp=je(),$a=D(),Vp=wa(),$S={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e;if(s.opts.removeAdditional==="all"&&i.additionalProperties===void 0)Vp.default.code(new wS.KeywordCxt(s,Vp.default,"additionalProperties"));let o=(0,Gp.allSchemaProperties)(r);for(let c of o)s.definedProperties.add(c);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=$a.mergeEvaluated.props(t,(0,$a.toHash)(o),s.props);let a=o.filter((c)=>!(0,$a.alwaysValidSchema)(s,r[c]));if(a.length===0)return;let d=t.name("valid");for(let c of a){if(u(c))l(c);else{if(t.if((0,Gp.propertyInData)(t,n,c,s.opts.ownProperties)),l(c),!s.allErrors)t.else().var(d,!0);t.endIf()}e.it.definedProperties.add(c),e.ok(d)}function u(c){return s.opts.useDefaults&&!s.compositeRule&&r[c].default!==void 0}function l(c){e.subschema({keyword:"properties",schemaProp:c,dataProp:c},d)}}};Ea.default=$S});var Jp=P(function(Ia){Object.defineProperty(Ia,"__esModule",{value:!0});var zp=je(),Un=j(),Wp=D(),Hp=D(),ES={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:i,parentSchema:n,it:s}=e,{opts:o}=s,a=(0,zp.allSchemaProperties)(r),d=a.filter((h)=>(0,Wp.alwaysValidSchema)(s,r[h]));if(a.length===0||d.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&n.properties,l=t.name("valid");if(s.props!==!0&&!(s.props instanceof Un.Name))s.props=(0,Hp.evaluatedPropsToName)(t,s.props);let{props:c}=s;p();function p(){for(let h of a){if(u)f(h);if(s.allErrors)m(h);else t.var(l,!0),m(h),t.if(l)}}function f(h){for(let g in u)if(new RegExp(h).test(g))(0,Wp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Un._`${(0,zp.usePattern)(e,h)}.test(${g})`,()=>{let _=d.includes(h);if(!_)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Hp.Type.Str},l);if(s.opts.unevaluated&&c!==!0)t.assign(Un._`${c}[${g}]`,!0);else if(!_&&!s.allErrors)t.if((0,Un.not)(l),()=>t.break())})})}}};Ia.default=ES});var Qp=P(function(Sa){Object.defineProperty(Sa,"__esModule",{value:!0});var IS=D(),SS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,IS.alwaysValidSchema)(i,r)){e.fail();return}let n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Sa.default=SS});var Yp=P(function(xa){Object.defineProperty(xa,"__esModule",{value:!0});var xS=je(),RS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xS.validateUnion,error:{message:"must match a schema in anyOf"}};xa.default=RS});var Xp=P(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var Bn=j(),CS=D(),OS={message:"must match exactly one schema in oneOf",params:({params:e})=>Bn._`{passingSchemas: ${e.passing}}`},jS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:OS,code(e){let{gen:t,schema:r,parentSchema:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),d=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,c)=>{let p;if((0,CS.alwaysValidSchema)(n,l))t.var(d,!0);else p=e.subschema({keyword:"oneOf",schemaProp:c,compositeRule:!0},d);if(c>0)t.if(Bn._`${d} && ${o}`).assign(o,!1).assign(a,Bn._`[${a}, ${c}]`).else();t.if(d,()=>{if(t.assign(o,!0),t.assign(a,c),p)e.mergeEvaluated(p,Bn.Name)})})}}};Ra.default=jS});var Zp=P(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var FS=D(),TS={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((s,o)=>{if((0,FS.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};Ca.default=TS});var rf=P(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var Gn=j(),tf=D(),kS={message:({params:e})=>Gn.str`must match "${e.ifClause}" schema`,params:({params:e})=>Gn._`{failingKeyword: ${e.ifClause}}`},AS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:kS,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,tf.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=ef(i,"then"),s=ef(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(d(),e.reset(),n&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else if(n)t.if(a,u("then"));else t.if((0,Gn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,c){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),c)t.assign(c,Gn._`${l}`);else e.setParams({ifClause:l})}}}};function ef(e,t){let r=e.schema[t];return r!==void 0&&!(0,tf.alwaysValidSchema)(e,r)}Oa.default=AS});var nf=P(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var DS=D(),NS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,DS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};ja.default=NS});var Ta=P(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var LS=ma(),qS=Ap(),MS=ha(),US=Np(),BS=Lp(),GS=Ln(),VS=Bp(),KS=wa(),zS=Kp(),WS=Jp(),HS=Qp(),JS=Yp(),QS=Xp(),YS=Zp(),XS=rf(),ZS=nf();function ex(e=!1){let t=[HS.default,JS.default,QS.default,YS.default,XS.default,ZS.default,VS.default,KS.default,GS.default,zS.default,WS.default];if(e)t.push(qS.default,US.default);else t.push(LS.default,MS.default);return t.push(BS.default),t}Fa.default=ex});var Aa=P(function(wi){Object.defineProperty(wi,"__esModule",{value:!0});wi.dynamicAnchor=void 0;var ka=j(),tx=Oe(),sf=ci(),rx=jn(),ix={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>of(e,e.schema)};function of(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=ka._`${tx.default.dynamicAnchors}${(0,ka.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:nx(e);r.if(ka._`!${n}`,()=>r.assign(n,s))}wi.dynamicAnchor=of;function nx(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:d}=i.opts,u=new sf.SchemaEnv({schema:r,schemaId:d,root:n,baseId:s,localRefs:o,meta:a});return sf.compileSchema.call(i,u),(0,rx.getValidate)(e,u)}wi.default=ix});var Da=P(function($i){Object.defineProperty($i,"__esModule",{value:!0});$i.dynamicRef=void 0;var af=j(),sx=Oe(),lf=jn(),ox={keyword:"$dynamicRef",schemaType:"string",code:(e)=>cf(e,e.schema)};function cf(e,t){let{gen:r,keyword:i,it:n}=e;if(t[0]!=="#")throw Error(`"${i}" only supports hash fragment reference`);let s=t.slice(1);if(n.allErrors)o();else{let d=r.let("valid",!1);o(d),e.ok(d)}function o(d){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",af._`${sx.default.dynamicAnchors}${(0,af.getProperty)(s)}`);r.if(u,a(u,d),a(n.validateName,d))}else a(n.validateName,d)()}function a(d,u){return u?()=>r.block(()=>{(0,lf.callRef)(e,d),r.let(u,!0)}):()=>(0,lf.callRef)(e,d)}}$i.dynamicRef=cf;$i.default=ox});var df=P(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var ax=Aa(),lx=D(),cx={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,ax.dynamicAnchor)(e,"");else(0,lx.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Na.default=cx});var uf=P(function(La){Object.defineProperty(La,"__esModule",{value:!0});var dx=Da(),ux={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,dx.dynamicRef)(e,e.schema)};La.default=ux});var pf=P(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var px=Aa(),fx=Da(),mx=df(),hx=uf(),gx=[px.default,fx.default,mx.default,hx.default];qa.default=gx});var mf=P(function(Ma){Object.defineProperty(Ma,"__esModule",{value:!0});var ff=Ln(),yx={keyword:"dependentRequired",type:"object",schemaType:"object",error:ff.error,code:(e)=>(0,ff.validatePropertyDeps)(e)};Ma.default=yx});var hf=P(function(Ua){Object.defineProperty(Ua,"__esModule",{value:!0});var _x=Ln(),bx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,_x.validateSchemaDeps)(e)};Ua.default=bx});var gf=P(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var Px=D(),vx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,Px.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ba.default=vx});var yf=P(function(Ga){Object.defineProperty(Ga,"__esModule",{value:!0});var wx=mf(),$x=hf(),Ex=gf(),Ix=[wx.default,$x.default,Ex.default];Ga.default=Ix});var bf=P(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var Ct=j(),_f=D(),Sx=Oe(),xx={message:"must NOT have unevaluated properties",params:({params:e})=>Ct._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},Rx={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:xx,code(e){let{gen:t,schema:r,data:i,errsCount:n,it:s}=e;if(!n)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof Ct.Name)t.if(Ct._`${a} !== true`,()=>t.forIn("key",i,(c)=>t.if(u(a,c),()=>d(c))));else if(a!==!0)t.forIn("key",i,(c)=>a===void 0?d(c):t.if(l(a,c),()=>d(c)));s.props=!0,e.ok(Ct._`${n} === ${Sx.default.errors}`);function d(c){if(r===!1){if(e.setParams({unevaluatedProperty:c}),e.error(),!o)t.break();return}if(!(0,_f.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:c,dataPropType:_f.Type.Str},p),!o)t.if((0,Ct.not)(p),()=>t.break())}}function u(c,p){return Ct._`!${c} || !${c}[${p}]`}function l(c,p){let f=[];for(let m in c)if(c[m]===!0)f.push(Ct._`${p} !== ${m}`);return(0,Ct.and)(...f)}}};Va.default=Rx});var vf=P(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});var Bt=j(),Pf=D(),Cx={message:({params:{len:e}})=>Bt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Bt._`{limit: ${e}}`},Ox={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Cx,code(e){let{gen:t,schema:r,data:i,it:n}=e,s=n.items||0;if(s===!0)return;let o=t.const("len",Bt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Bt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,Pf.alwaysValidSchema)(n,r)){let d=t.var("valid",Bt._`${o} <= ${s}`);t.if((0,Bt.not)(d),()=>a(d,s)),e.ok(d)}n.items=!0;function a(d,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Pf.Type.Num},d),!n.allErrors)t.if((0,Bt.not)(d),()=>t.break())})}}};Ka.default=Ox});var wf=P(function(za){Object.defineProperty(za,"__esModule",{value:!0});var jx=bf(),Fx=vf(),Tx=[jx.default,Fx.default];za.default=Tx});var $f=P(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});var Q=j(),kx={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},Ax={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:kx,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:d,errSchemaPath:u,schemaEnv:l,self:c}=a;if(!d.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:c.formats,code:d.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),_=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(_,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(_,h)),e.fail$data((0,Q.or)(b(),v()));function b(){if(d.strictSchema===!1)return Q.nil;return Q._`${o} && !${_}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${_}(${i}) : ${_}(${i}))`:Q._`${_}(${i})`,I=Q._`(typeof ${_} == "function" ? ${w} : ${_}.test(${i}))`;return Q._`${_} && ${_} !== true && ${g} === ${t} && !${I}`}}function f(){let m=c.formats[s];if(!m){b();return}if(m===!0)return;let[h,g,_]=v(m);if(h===t)e.pass(w());function b(){if(d.strictSchema===!1){c.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(I){let E=I instanceof RegExp?(0,Q.regexpCode)(I):d.code.formats?Q._`${d.code.formats}${(0,Q.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:I,code:E});if(typeof I=="object"&&!(I instanceof RegExp))return[I.type||"string",I.validate,Q._`${x}.validate`];return["string",I,x]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw Error("async format in sync schema");return Q._`await ${_}(${i})`}return typeof g=="function"?Q._`${_}(${i})`:Q._`${_}.test(${i})`}}}};Wa.default=Ax});var Ja=P(function(Ha){Object.defineProperty(Ha,"__esModule",{value:!0});var Dx=$f(),Nx=[Dx.default];Ha.default=Nx});var Qa=P(function(br){Object.defineProperty(br,"__esModule",{value:!0});br.contentVocabulary=br.metadataVocabulary=void 0;br.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];br.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var If=P(function(Ya){Object.defineProperty(Ya,"__esModule",{value:!0});var Lx=Qo(),qx=pa(),Mx=Ta(),Ux=pf(),Bx=yf(),Gx=wf(),Vx=Ja(),Ef=Qa(),Kx=[Ux.default,Lx.default,qx.default,(0,Mx.default)(!0),Vx.default,Ef.metadataVocabulary,Ef.contentVocabulary,Bx.default,Gx.default];Ya.default=Kx});var xf=P(function(Vn){Object.defineProperty(Vn,"__esModule",{value:!0});Vn.DiscrError=void 0;var Sf;(function(e){e.Tag="tag",e.Mapping="mapping"})(Sf||(Vn.DiscrError=Sf={}))});var el=P(function(Za){Object.defineProperty(Za,"__esModule",{value:!0});var Pr=j(),Xa=xf(),Rf=ci(),zx=gr(),Wx=D(),Hx={message:({params:{discrError:e,tagName:t}})=>e===Xa.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Pr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Jx={keyword:"discriminator",type:"object",schemaType:"object",error:Hx,code(e){let{gen:t,data:r,schema:i,parentSchema:n,it:s}=e,{oneOf:o}=n;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(i.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),u=t.const("tag",Pr._`${r}${(0,Pr.getProperty)(a)}`);t.if(Pr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Xa.DiscrError.Tag,tag:u,tagName:a})),e.ok(d);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(Pr._`${u} === ${m}`),t.assign(d,c(f[m]));t.else(),e.error(!1,{discrError:Xa.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function c(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,Pr.Name),m}function p(){var f;let m={},h=_(n),g=!0;for(let w=0;w<o.length;w++){let I=o[w];if((I===null||I===void 0?void 0:I.$ref)&&!(0,Wx.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=Rf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof Rf.SchemaEnv)I=I.schema;if(I===void 0)throw new zx.default(s.opts.uriResolver,s.baseId,x)}let E=(f=I===null||I===void 0?void 0:I.properties)===null||f===void 0?void 0:f[a];if(typeof E!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_(I)),b(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function _({required:w}){return Array.isArray(w)&&w.includes(a)}function b(w,I){if(w.const)v(w.const,I);else if(w.enum)for(let E of w.enum)v(E,I);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(w,I){if(typeof w!="string"||w in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[w]=I}}}};Za.default=Jx});var Cf=P(function(_D,Qx){Qx.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 Of=P(function(bD,Yx){Yx.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 jf=P(function(PD,Xx){Xx.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 Ff=P(function(vD,Zx){Zx.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 Tf=P(function(wD,eR){eR.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 kf=P(function($D,tR){tR.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 Af=P(function(ED,rR){rR.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 Df=P(function(ID,iR){iR.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 Nf=P(function(tl){Object.defineProperty(tl,"__esModule",{value:!0});var nR=Cf(),sR=Of(),oR=jf(),aR=Ff(),lR=Tf(),cR=kf(),dR=Af(),uR=Df(),pR=["/properties"];function fR(e){return[nR,sR,oR,aR,lR,t(this,cR),dR,t(this,uR)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,pR):i}}tl.default=fR});var nl=P(function(z,il){Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv2020=void 0;var mR=Wo(),hR=If(),gR=el(),yR=Nf(),rl="https://json-schema.org/draft/2020-12/schema";class Ei extends mR.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),hR.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(gR.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;yR.default.call(this,e),this.refs["http://json-schema.org/schema"]=rl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rl)?rl:void 0)}}z.Ajv2020=Ei;il.exports=z=Ei;il.exports.Ajv2020=Ei;Object.defineProperty(z,"__esModule",{value:!0});z.default=Ei;var _R=hr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return _R.KeywordCxt}});var vr=j();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var bR=ai();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return bR.default}});var PR=gr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return PR.default}})});var Fg=P(function(nt){Object.defineProperty(nt,"__esModule",{value:!0});nt.formatNames=nt.fastFormats=nt.fullFormats=void 0;function it(e,t){return{validate:e,compare:t}}nt.fullFormats={date:it(Rg,rc),time:it(ec(!0),ic),"date-time":it(Ig(!0),Og),"iso-time":it(ec(),Cg),"iso-date-time":it(Ig(),jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Zj,"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:oF,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:eF,int32:{type:"number",validate:iF},int64:{type:"number",validate:nF},float:{type:"number",validate:xg},double:{type:"number",validate:xg},password:!0,binary:!0};nt.fastFormats={...nt.fullFormats,date:it(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,rc),time:it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ic),"date-time":it(/^\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,Og),"iso-time":it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Cg),"iso-date-time":it(/^\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,jg),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};nt.formatNames=Object.keys(nt.fullFormats);function Hj(e){return e%4===0&&(e%100!==0||e%400===0)}var Jj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Qj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Rg(e){let t=Jj.exec(e);if(!t)return!1;let r=+t[1],i=+t[2],n=+t[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&Hj(r)?29:Qj[i])}function rc(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Zl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ec(e){return function(r){let i=Zl.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],d=i[5]==="-"?-1:1,u=+(i[6]||0),l=+(i[7]||0);if(u>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let c=s-l*d,p=n-u*d-(c<0?1:0);return(p===23||p===-1)&&(c===59||c===-1)&&o<61}}function ic(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),i=new Date("2020-01-01T"+t).valueOf();if(!(r&&i))return;return r-i}function Cg(e,t){if(!(e&&t))return;let r=Zl.exec(e),i=Zl.exec(t);if(!(r&&i))return;if(e=r[1]+r[2]+r[3],t=i[1]+i[2]+i[3],e>t)return 1;if(e<t)return-1;return 0}var tc=/t|\s/i;function Ig(e){let t=ec(e);return function(i){let n=i.split(tc);return n.length===2&&Rg(n[0])&&t(n[1])}}function Og(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),i=new Date(t).valueOf();if(!(r&&i))return;return r-i}function jg(e,t){if(!(e&&t))return;let[r,i]=e.split(tc),[n,s]=t.split(tc),o=rc(r,n);if(o===void 0)return;return o||ic(i,s)}var Yj=/\/|:/,Xj=/^(?:[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 Zj(e){return Yj.test(e)&&Xj.test(e)}var Sg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eF(e){return Sg.lastIndex=0,Sg.test(e)}var tF=-2147483648,rF=2147483647;function iF(e){return Number.isInteger(e)&&e<=rF&&e>=tF}function nF(e){return Number.isInteger(e)}function xg(){return!0}var sF=/[^\\]\\Z/;function oF(e){if(sF.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var kg=P(function(nc){Object.defineProperty(nc,"__esModule",{value:!0});var aF=Qo(),lF=pa(),cF=Ta(),dF=Ja(),Tg=Qa(),uF=[aF.default,lF.default,(0,cF.default)(),dF.default,Tg.metadataVocabulary,Tg.contentVocabulary];nc.default=uF});var Ag=P(function(zM,pF){pF.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 Ng=P(function(W,sc){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var fF=Wo(),mF=kg(),hF=el(),Dg=Ag(),gF=["/properties"],Rs="http://json-schema.org/draft-07/schema";class Ki extends fF.default{_addVocabularies(){if(super._addVocabularies(),mF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(hF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Dg,gF):Dg;this.addMetaSchema(e,Rs,!1),this.refs["http://json-schema.org/schema"]=Rs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rs)?Rs:void 0)}}W.Ajv=Ki;sc.exports=W=Ki;sc.exports.Ajv=Ki;Object.defineProperty(W,"__esModule",{value:!0});W.default=Ki;var yF=hr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return yF.KeywordCxt}});var Lr=j();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Lr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Lr.CodeGen}});var _F=ai();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return _F.default}});var bF=gr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return bF.default}})});var Lg=P(function(qr){Object.defineProperty(qr,"__esModule",{value:!0});qr.formatLimitDefinition=void 0;var PF=Ng(),ze=j(),Tt=ze.operators,Cs={formatMaximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},formatMinimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},formatExclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},formatExclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},vF={message:({keyword:e,schemaCode:t})=>ze.str`should be ${Cs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>ze._`{comparison: ${Cs[e].okStr}, limit: ${t}}`};qr.formatLimitDefinition={keyword:Object.keys(Cs),type:"string",schemaType:"string",$data:!0,error:vF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let d=new PF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(d.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",ze._`${p}[${d.schemaCode}]`);e.fail$data((0,ze.or)(ze._`typeof ${f} != "object"`,ze._`${f} instanceof RegExp`,ze._`typeof ${f}.compare != "function"`,c(f)))}function l(){let p=d.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${n}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:o.code.formats?ze._`${o.code.formats}${(0,ze.getProperty)(p)}`:void 0});e.fail$data(c(m))}function c(p){return ze._`${p}.compare(${r}, ${i}) ${Cs[n].fail} 0`}},dependencies:["format"]};var wF=(e)=>(e.addKeyword(qr.formatLimitDefinition),e);qr.default=wF});var Bg=P(function(zi,Ug){Object.defineProperty(zi,"__esModule",{value:!0});var Mr=Fg(),$F=Lg(),oc=j(),qg=new oc.Name("fullFormats"),EF=new oc.Name("fastFormats"),ac=(e,t={keywords:!0})=>{if(Array.isArray(t))return Mg(e,t,Mr.fullFormats,qg),e;let[r,i]=t.mode==="fast"?[Mr.fastFormats,EF]:[Mr.fullFormats,qg],n=t.formats||Mr.formatNames;if(Mg(e,n,r,i),t.keywords)(0,$F.default)(e);return e};ac.get=(e,t="full")=>{let i=(t==="fast"?Mr.fastFormats:Mr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function Mg(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=oc._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}Ug.exports=zi=ac;Object.defineProperty(zi,"__esModule",{value:!0});zi.default=ac});var jy=P(function(QU,Oy){Oy.exports=gT;function hT(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function gT(e){let t=hT(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 r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var Qy=P(function(dB,Jy){var jT=require("stream");class Hy extends jT{#r=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.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=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)}}Jy.exports=Hy});class at extends Error{constructor(e,t,r){super(r);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class lt extends at{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class sn{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,r)=>{if(!this.argChoices.includes(t))throw new lt(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function on(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Xc=require("events"),ln=Ce(require("child_process")),He=Ce(require("path")),Yr=Ce(require("fs")),U=Ce(require("process")),Zc=require("util");var Hc=require("util");class an{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((i)=>!i._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((i,n)=>i.name().localeCompare(n.name()));return t}compareOptions(e,t){let r=(i)=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((i)=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),n=r.long&&e._findOption(r.long);if(!i&&!n)t.push(r);else if(r.long&&!n)t.push(e.createOption(r.long,r.description));else if(r.short&&!i)t.push(e.createOption(r.short,r.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter((n)=>!n.hidden);t.push(...i)}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((r)=>on(r)).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((r,i)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+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((r)=>JSON.stringify(r)).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 r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}formatItemList(e,t,r){if(t.length===0)return[];return[r.styleTitle(e),...t,""]}groupItems(e,t,r){let i=new Map;return e.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[])}),t.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[]);i.get(s).push(n)}),i}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth??80;function n(l,c){return t.formatItem(l,r,c,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),i),""]);let a=t.visibleArguments(e).map((l)=>n(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(l)=>l.helpGroupHeading??"Options:").forEach((l,c)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(c,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((c)=>n(t.styleOptionTerm(t.optionTerm(c)),t.styleOptionDescription(t.optionDescription(c))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,c)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(c,p,t))}),s.join(`
|
|
11
|
+
`)}displayWidth(e){return Hc.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,r,i){let s=" ".repeat(2);if(!r)return s+e;let o=e.padEnd(t+e.length-i.displayWidth(e)),a=2,u=(this.helpWidth??80)-t-a-2,l;if(u<this.minWidthToWrap||i.preformatted(r))l=r;else l=i.boxWrap(r,u).replace(/\n/g,`
|
|
12
12
|
`+" ".repeat(t+a));return s+o+" ".repeat(a)+l.replace(/\n/g,`
|
|
13
|
-
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,n=[];return r.forEach((s)=>{let o=s.match(i);if(o===null){n.push("");return}let a=[o.shift()],
|
|
14
|
-
`)}}class
|
|
13
|
+
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,n=[];return r.forEach((s)=>{let o=s.match(i);if(o===null){n.push("");return}let a=[o.shift()],d=this.displayWidth(a[0]);o.forEach((u)=>{let l=this.displayWidth(u);if(d+l<=t){a.push(u),d+=l;return}n.push(a.join(""));let c=u.trimStart();a=[c],d=this.displayWidth(c)}),n.push(a.join(""))}),n.join(`
|
|
14
|
+
`)}}class Qr{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=B_(e);if(this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new lt(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return Jc(this.name().replace(/^no-/,""));return Jc(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Ks{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{if(this.positiveOptions.has(r))this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let i=this.negativeOptions.get(r).presetArg,n=i!==void 0?i:!1;return t.negate===(n===e)}}function Jc(e){return e.split("-").reduce((t,r)=>t+r[0].toUpperCase()+r.slice(1))}function B_(e){let t,r,i=/^-[^-]$/,n=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(i.test(s[0]))t=s.shift();if(n.test(s[0]))r=s.shift();if(!t&&i.test(s[0]))t=s.shift();if(!t&&n.test(s[0]))t=r,r=s.shift();if(s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${a}
|
|
15
15
|
- a short flag is a single dash and a single character
|
|
16
16
|
- either use a single dash and a single character (for a short flag)
|
|
17
17
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(i.test(o))throw Error(`${a}
|
|
18
18
|
- too many short flags`);if(n.test(o))throw Error(`${a}
|
|
19
19
|
- too many long flags`);throw Error(`${a}
|
|
20
|
-
- unrecognised flag format`)}if(t===void 0&&r===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:r}}function
|
|
20
|
+
- unrecognised flag format`)}if(t===void 0&&r===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:r}}function G_(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let r=[];for(let i=0;i<=e.length;i++)r[i]=[i];for(let i=0;i<=t.length;i++)r[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=e.length;n++){let s;if(e[n-1]===t[i-1])s=0;else s=1;if(r[n][i]=Math.min(r[n-1][i]+1,r[n][i-1]+1,r[n-1][i-1]+s),n>1&&i>1&&e[n-1]===t[i-2]&&e[n-2]===t[i-1])r[n][i]=Math.min(r[n][i],r[n-2][i-2]+1)}return r[e.length][t.length]}function zs(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let r=e.startsWith("--");if(r)e=e.slice(2),t=t.map((o)=>o.slice(2));let i=[],n=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=G_(e,o),d=Math.max(e.length,o.length);if((d-a)/d>s){if(a<n)n=a,i=[o];else if(a===n)i.push(o)}}),i.sort((o,a)=>o.localeCompare(a)),r)i=i.map((o)=>`--${o}`);if(i.length>1)return`
|
|
21
21
|
(Did you mean one of ${i.join(", ")}?)`;if(i.length===1)return`
|
|
22
|
-
(Did you mean ${i[0]}?)`;return""}class
|
|
23
|
-
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
24
|
-
Expecting one of '${r.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,r){if(this._exitCallback)this._exitCallback(new
|
|
25
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(i)=>[i.name()].concat(i.aliases()),r=t(e).find((i)=>this._findCommand(i));if(r){let i=t(this._findCommand(r)).join("|"),n=t(e).join("|");throw Error(`cannot add command '${n}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(r,e.defaultValue,"default");let i=(n,s,o)=>{if(n==null&&e.presetArg!==void 0)n=e.presetArg;let a=this.getOptionValue(r);if(n!==null&&e.parseArg)n=this._callParseArg(e,n,a,s);else if(n!==null&&e.variadic)n=e._collectValue(n,a);if(n==null)if(e.negate)n=!1;else if(e.isBoolean()||e.optional)n=!0;else n="";this.setOptionValueWithSource(r,n,o)};if(this.on("option:"+t,(n)=>{let s=`error: option '${e.flags}' argument '${n}' is invalid.`;i(n,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(n)=>{let s=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;i(n,s,"env")});return this}_optionEx(e,t,r,i,n){if(typeof t==="object"&&t instanceof
|
|
26
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,r){if(
|
|
22
|
+
(Did you mean ${i[0]}?)`;return""}class sr extends Xc.EventEmitter{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>U.default.stdout.write(t),writeErr:(t)=>U.default.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>U.default.stdout.isTTY?U.default.stdout.columns:void 0,getErrHelpWidth:()=>U.default.stderr.isTTY?U.default.stderr.columns:void 0,getOutHasColors:()=>Yc()??(U.default.stdout.isTTY&&U.default.stdout.hasColors?.()),getErrHasColors:()=>Yc()??(U.default.stderr.isTTY&&U.default.stderr.hasColors?.()),stripColor:(t)=>Zc.stripVTControlCharacters(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let i=t,n=r;if(typeof i==="object"&&i!==null)n=i,i=null;n=n||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(i)a.description(i),a._executableHandler=!0;if(n.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,o)a.arguments(o);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i)return this;return a}createCommand(e){return new sr(e)}createHelp(){return Object.assign(new an,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
23
|
+
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new sn(e,t)}argument(e,t,r,i){let n=this.createArgument(e,t);if(typeof r==="function")n.default(i).argParser(r);else n.default(r);return this.addArgument(n),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let r=e??"help [command]",[,i,n]=r.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);if(o.helpOption(!1),n)o.arguments(n);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
24
|
+
Expecting one of '${r.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,r){if(this._exitCallback)this._exitCallback(new at(e,t,r));U.default.exit(e)}action(e){let t=(r)=>{let i=this.registeredArguments.length,n=r.slice(0,i);if(this._storeOptionsAsProperties)n[i]=this;else n[i]=this.opts();return n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new Qr(e,t)}_callParseArg(e,t,r,i){try{return e.parseArg(t,r)}catch(n){if(n.code==="commander.invalidArgument"){let s=`${i} ${n.message}`;this.error(s,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
25
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(i)=>[i.name()].concat(i.aliases()),r=t(e).find((i)=>this._findCommand(i));if(r){let i=t(this._findCommand(r)).join("|"),n=t(e).join("|");throw Error(`cannot add command '${n}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(r,e.defaultValue,"default");let i=(n,s,o)=>{if(n==null&&e.presetArg!==void 0)n=e.presetArg;let a=this.getOptionValue(r);if(n!==null&&e.parseArg)n=this._callParseArg(e,n,a,s);else if(n!==null&&e.variadic)n=e._collectValue(n,a);if(n==null)if(e.negate)n=!1;else if(e.isBoolean()||e.optional)n=!0;else n="";this.setOptionValueWithSource(r,n,o)};if(this.on("option:"+t,(n)=>{let s=`error: option '${e.flags}' argument '${n}' is invalid.`;i(n,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(n)=>{let s=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;i(n,s,"env")});return this}_optionEx(e,t,r,i,n){if(typeof t==="object"&&t instanceof Qr)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,r);if(s.makeOptionMandatory(!!e.mandatory),typeof i==="function")s.default(n).argParser(i);else if(i instanceof RegExp){let o=i;i=(a,d)=>{let u=o.exec(a);return u?u[0]:d},s.default(n).argParser(i)}else s.default(i);return this.addOption(s)}option(e,t,r,i){return this._optionEx({},e,t,r,i)}requiredOption(e,t,r,i){return this._optionEx({mandatory:!0},e,t,r,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((r)=>{if(r.getOptionValueSource(e)!==void 0)t=r.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(U.default.versions?.electron)t.from="electron";let i=U.default.execArgv??[];if(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))t.from="eval"}if(e===void 0)e=U.default.argv;this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":if(U.default.defaultApp)this._scriptPath=e[1],r=e.slice(2);else r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",r}parse(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
26
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,r){if(Yr.default.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${e}' does not exist
|
|
27
27
|
- if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
28
28
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
29
|
-
- ${i}`;throw Error(n)}_executeSubCommand(e,t){t=t.slice();let r=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,l){let
|
|
29
|
+
- ${i}`;throw Error(n)}_executeSubCommand(e,t){t=t.slice();let r=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,l){let c=He.default.resolve(u,l);if(Yr.default.existsSync(c))return c;if(r.includes(He.default.extname(l)))return;let p=r.find((f)=>Yr.default.existsSync(`${c}${f}`));if(p)return`${c}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let u;try{u=Yr.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}s=He.default.resolve(He.default.dirname(u),s)}if(s){let u=i(s,n);if(!u&&!e._executableFile&&this._scriptPath){let l=He.default.basename(this._scriptPath,He.default.extname(this._scriptPath));if(l!==this._name)u=i(s,`${l}-${e._name}`)}n=u||n}let o=r.includes(He.default.extname(n)),a;if(U.default.platform!=="win32")if(o)t.unshift(n),t=Qc(U.default.execArgv).concat(t),a=ln.default.spawn(U.default.argv[0],t,{stdio:"inherit"});else a=ln.default.spawn(n,t,{stdio:"inherit"});else this._checkForMissingExecutable(n,s,e._name),t.unshift(n),t=Qc(U.default.execArgv).concat(t),a=ln.default.spawn(U.default.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((l)=>{U.default.on(l,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(l)})});let d=this._exitCallback;a.on("close",(u)=>{if(u=u??1,!d)U.default.exit(u);else d(new at(u,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(n,s,e._name);else if(u.code==="EACCES")throw Error(`'${n}' not executable`);if(!d)U.default.exit(1);else{let l=new at(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,d(l)}}),this.runningCommand=a}_dispatchSubcommand(e,t,r){let i=this._findCommand(e);if(!i)this.help({error:!0});i._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,i,"preSubcommand"),n=this._chainOrCall(n,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(r));else return i._parseCommand(t,r)}),n}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(r,i,n)=>{let s=i;if(i!==null&&r.parseArg){let o=`error: command-argument value '${i}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,i,n,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,i)=>{let n=r.defaultValue;if(r.variadic){if(i<this.args.length){if(n=this.args.slice(i),r.parseArg)n=n.reduce((s,o)=>e(r,o,s),r.defaultValue)}else if(n===void 0)n=[]}else if(i<this.args.length){if(n=this.args[i],r.parseArg)n=e(r,n,r.defaultValue)}t[i]=n}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let r=e,i=[];if(this._getCommandAndAncestors().reverse().filter((n)=>n._lifeCycleHooks[t]!==void 0).forEach((n)=>{n._lifeCycleHooks[t].forEach((s)=>{i.push({hookedCommand:n,callback:s})})}),t==="postAction")i.reverse();return i.forEach((n)=>{r=this._chainOrCall(r,()=>n.callback(n.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let i=e;if(this._lifeCycleHooks[r]!==void 0)this._lifeCycleHooks[r].forEach((n)=>{i=this._chainOrCall(i,()=>n(this,t))});return i}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{if(r.unknown.length>0)this.unknownOption(r.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(n,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(n))i(),this._processArguments(),this.parent.emit(n,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else i(),this._processArguments()}else if(this.commands.length)i(),this.help({error:!0});else i(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((r)=>{let i=r.attributeName();if(this.getOptionValue(i)===void 0)return!1;return this.getOptionValueSource(i)!=="default"});e.filter((r)=>r.conflictsWith.length>0).forEach((r)=>{let i=e.find((n)=>r.conflictsWith.includes(n.attributeName()));if(i)this._conflictingOption(r,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],i=t;function n(u){return u.length>1&&u[0]==="-"}let s=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((l)=>l.options.map((c)=>c.short).some((c)=>/^-\d$/.test(c)))},o=null,a=null,d=0;while(d<e.length||a){let u=a??e[d++];if(a=null,u==="--"){if(i===r)i.push(u);i.push(...e.slice(d));break}if(o&&(!n(u)||s(u))){this.emit(`option:${o.name()}`,u);continue}if(o=null,n(u)){let l=this._findOption(u);if(l){if(l.required){let c=e[d++];if(c===void 0)this.optionMissingArgument(l);this.emit(`option:${l.name()}`,c)}else if(l.optional){let c=null;if(d<e.length&&(!n(e[d])||s(e[d])))c=e[d++];this.emit(`option:${l.name()}`,c)}else this.emit(`option:${l.name()}`);o=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){if(l.required||l.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${l.name()}`,u.slice(2));else this.emit(`option:${l.name()}`),a=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),c=this._findOption(u.slice(0,l));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,u.slice(l+1));continue}}if(i===t&&n(u)&&!(this.commands.length===0&&s(u)))i=r;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),r.push(...e.slice(d));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(d));break}else if(this._defaultCommandName){r.push(u,...e.slice(d));break}}if(this._passThroughOptions){i.push(u,...e.slice(d));break}i.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let i=this.options[r].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
30
30
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
31
31
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
32
|
-
`),this.outputHelp({error:!0});let r=t||{},i=r.exitCode||1,n=r.code||"commander.error";this._exit(i,n,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in U.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()}`,U.default.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new
|
|
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 r=this.parent?._findCommand(e);if(r){let i=[r.name()].concat(r.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}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((r)=>
|
|
32
|
+
`),this.outputHelp({error:!0});let r=t||{},i=r.exitCode||1,n=r.code||"commander.error";this._exit(i,n,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in U.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()}`,U.default.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Ks(this.options),t=(r)=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter((r)=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach((r)=>{Object.keys(r.implied).filter((i)=>!t(i)).forEach((i)=>{this.setOptionValueWithSource(i,r.implied[i],"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 r=(s)=>{let o=s.attributeName(),a=this.getOptionValue(o),d=this.options.find((l)=>l.negate&&o===l.attributeName()),u=this.options.find((l)=>!l.negate&&o===l.attributeName());if(d&&(d.presetArg===void 0&&a===!1||d.presetArg!==void 0&&a===d.presetArg))return d;return u||s},i=(s)=>{let o=r(s),a=o.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},n=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],n=this;do{let s=n.createHelp().visibleOptions(n).filter((o)=>o.long).map((o)=>o.long);i=i.concat(s),n=n.parent}while(n&&!n._enablePositionalOptions);t=zs(e,i)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=e.length,n=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${n}. Expected ${t} argument${r} but got ${i}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach((n)=>{if(i.push(n.name()),n.alias())i.push(n.alias())}),t=zs(e,i)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let i=this.createOption(t,r);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
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 r=this.parent?._findCommand(e);if(r){let i=[r.name()].concat(r.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}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((r)=>on(r));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=He.default.basename(e,He.default.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let i=t.formatHelp(this,t);if(r.hasColors)return i;return this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,r,i,n;if(t)r=(o)=>this._outputConfiguration.writeErr(o),i=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth();else r=(o)=>this._outputConfiguration.writeOut(o),i=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!i)o=this._outputConfiguration.stripColor(o);return r(o)},hasColors:i,helpWidth:n}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let r=this._getOutputContext(e),i={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation({error:r.error});if(t){if(n=t(n),typeof n!=="string"&&!Buffer.isBuffer(n))throw Error("outputHelp callback must return a string or a Buffer")}if(r.write(n),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",i),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",i))}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(U.default.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
34
34
|
Expecting one of '${r.join("', '")}'`);let i=`${e}Help`;return this.on(i,(n)=>{let s;if(typeof t==="function")s=t({error:n.error,command:n.command});else s=t;if(s)n.write(`${s}
|
|
35
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((i)=>t.is(i)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function
|
|
36
|
-
`);return new
|
|
37
|
-
${t}`,e)}}var qs="x-potato-sdk-base-url",Lc=(e,t,r)=>(_(e.length>0,"The SDK base URL cannot be empty"),_(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[qs]:new URL(e).toString()},fetch:r});async function C(e,t){let{fetch:r=globalThis.fetch,...i}=t,n=new Headers(i.headers),s=n.get(qs);_(s,"The SDK base URL is missing"),n.delete(qs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let c=a;if(a.length===0)c=void 0;else if(o.headers.get("content-type")?.includes("application/json"))c=JSON.parse(a);throw re.fromResponse(o.status,c)}return a.length===0?void 0:JSON.parse(a)}var w0=()=>"/api/v2-beta/me",qc=async(e)=>C(w0(),{...e,method:"GET"}),$0=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([i,n])=>{if(n!==void 0)t.append(i,n===null?"null":n.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},Ms=async(e,t)=>C($0(e),{...t,method:"GET"}),E0=()=>"/api/v2-beta/projects",Mc=async(e,t)=>C(E0(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),I0=(e)=>`/api/v2-beta/projects/${e}`,Uc=async(e,t)=>C(I0(e),{...t,method:"GET"}),S0=(e)=>`/api/v2-beta/projects/${e}`,Bc=async(e,t,r)=>C(S0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),x0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Us=async(e,t,r)=>C(x0(e,t),{...r,method:"GET"}),R0=(e)=>`/api/v2-beta/pipelines/${e}`,Gc=async(e,t)=>C(R0(e),{...t,method:"GET"}),C0=(e)=>`/api/v2-beta/pipelines/${e}`,Vc=async(e,t,r)=>C(C0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),j0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/datasets?${i}`:`/api/v2-beta/projects/${e}/datasets`},Bs=async(e,t,r)=>C(j0(e,t),{...r,method:"GET"}),F0=(e)=>`/api/v2-beta/projects/${e}/datasets`,Kc=async(e,t,r)=>C(F0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),O0=(e)=>`/api/v2-beta/datasets/${e}`,zc=async(e,t)=>C(O0(e),{...t,method:"GET"}),T0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/fields?${i}`:`/api/v2-beta/datasets/${e}/fields`},Gs=async(e,t,r)=>C(T0(e,t),{...r,method:"GET"}),A0=(e)=>`/api/v2-beta/datasets/${e}/fields`,Vs=async(e,t,r)=>C(A0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),k0=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,Wc=async(e,t)=>C(k0(e),{...t,method:"GET"}),D0=(e)=>`/api/v2-beta/datasets/${e}/items`,Hc=async(e,t,r)=>C(D0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),N0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/items?${i}`:`/api/v2-beta/datasets/${e}/items`},Ks=async(e,t,r)=>C(N0(e,t),{...r,method:"GET"}),L0=(e)=>`/api/v2-beta/datasets/${e}/uploads`,Jc=async(e,t,r)=>C(L0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),q0=(e)=>`/api/v2-beta/uploads/${e}/finalize`,Qc=async(e,t)=>C(q0(e),{...t,method:"POST"}),M0=(e)=>`/api/v2-beta/uploads/${e}`,zs=async(e,t)=>C(M0(e),{...t,method:"GET"}),U0=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,Yc=async(e,t,r)=>C(U0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),B0=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,Xc=async(e,t,r)=>C(B0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),G0=(e)=>`/api/v2-beta/pipelines/${e}/export`,Zc=async(e,t)=>C(G0(e),{...t,method:"GET"}),V0=(e)=>`/api/v2-beta/pipelines/${e}/copy`,ed=async(e,t,r)=>C(V0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),K0=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,td=async(e,t,r)=>C(K0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),z0=(e)=>`/api/v2-beta/pipelines/${e}/runs`,rd=async(e,t)=>C(z0(e),{...t,method:"POST"}),W0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},Ws=async(e,t,r)=>C(W0(e,t),{...r,method:"GET"}),H0=(e)=>`/api/v2-beta/runs/${e}`,Hs=async(e,t)=>C(H0(e),{...t,method:"GET"}),J0=(e)=>`/api/v2-beta/runs/${e}/cancel`,id=async(e,t)=>C(J0(e),{...t,method:"POST"}),Q0=(e)=>`/api/v2-beta/datasets/${e}/exports`,nd=async(e,t,r)=>C(Q0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Y0=(e)=>`/api/v2-beta/exports/${e}`,Js=async(e,t)=>C(Y0(e),{...t,method:"GET"}),X0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,sd=async(e,t)=>C(X0(e),{...t,method:"GET"}),Z0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,od=async(e,t,r)=>C(Z0(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),ev=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,ad=async(e,t,r)=>C(ev(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),tv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,ld=async(e,t,r,i)=>C(tv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),rv=(e)=>`/api/v2-beta/projects/${e}/secrets`,cd=async(e,t)=>C(rv(e),{...t,method:"GET"}),iv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,dd=async(e,t,r,i)=>C(iv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),nv=(e)=>`/api/v2-beta/projects/${e}/files`,ud=async(e,t)=>C(nv(e),{...t,method:"GET"}),sv=(e)=>`/api/v2-beta/projects/${e}/files`,pd=async(e,t,r)=>C(sv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),ov=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,fd=async(e,t,r)=>C(ov(e,t),{...r,method:"POST"}),av=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,md=async(e,t,r)=>C(av(e,t),{...r,method:"DELETE"}),lv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/runs/${e}/items?${i}`:`/api/v2-beta/runs/${e}/items`},Qs=async(e,t,r)=>C(lv(e,t),{...r,method:"GET"}),cv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,hd=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,gd=async(e,t)=>C(dv(e),{...t,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,yd=async(e,t,r)=>C(uv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),pv=(e)=>`/api/v2-beta/checks/${e}`,Ys=async(e,t)=>C(pv(e),{...t,method:"GET"});async function*ft(e,t={}){let r=t.offset;while(!0){let i=await e({limit:t.limit,offset:r});if(yield*i.items,!i.pagination.hasMore)return;r=i.pagination.offset+i.pagination.limit}}var Gr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;_(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),_(Number.isFinite(n)&&n>0,"The polling interval must be a positive finite number");let s=Date.now()+i,o=new AbortController,a=setTimeout(()=>o.abort(),i);try{while(!0){if(o.signal.aborted)throw re.waitTimeout(i);let c=await e(o.signal);if(t(c))return c;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:d}=Promise.withResolvers();setTimeout(d,Math.min(n,u)),await l}}catch(c){if(o.signal.aborted)throw re.waitTimeout(i);throw c}finally{clearTimeout(a)}};var mv=(e)=>{let t=Lc(e.baseUrl,e.apiKey,e.fetch);async function r(l,d){switch(l.type){case"datasetUpload":return Gr((p)=>zs(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"datasetExport":return Gr((p)=>Js(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",d);case"pipelineCheck":return Gr((p)=>Ys(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"pipelineRun":return Gr((p)=>Hs(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d)}}return{me:()=>qc(t),projects:{create:(l)=>Mc(l,t),get:({projectId:l})=>Uc(l,t),update:({projectId:l,...d})=>Bc(l,d,t),listPage:(l={})=>Ms(l,t),listAll:(l={})=>ft(async(d)=>{let p=await Ms({...l,...d},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...d})=>Yc(l,d,t),get:({pipelineId:l})=>Gc(l,t),update:({pipelineId:l,...d})=>Vc(l,d,t),listPage:({projectId:l,...d})=>Us(l,d,t),listAll:({projectId:l,...d})=>ft(async(p)=>{let f=await Us(l,{...d,...p},t);return{items:f.pipelines,pagination:f.pagination}},d),getGraph:({pipelineId:l})=>sd(l,t),replaceGraph:({pipelineId:l,...d})=>od(l,"version"in d?{graph:d.graph,expectedVersion:d.version}:d,t),validateGraph:({pipelineId:l,...d})=>ad(l,d,t),estimateCost:({pipelineId:l,...d})=>td(l,d,t),patchNode:({pipelineId:l,nodeId:d,...p})=>ld(l,d,p,t),attachDataset:({pipelineId:l,...d})=>Xc(l,d,t),export:({pipelineId:l})=>Zc(l,t),copy:({pipelineId:l,...d})=>ed(l,d,t)},datasets:{create:({projectId:l,...d})=>Kc(l,d,t),get:({datasetId:l})=>zc(l,t),listPage:({projectId:l,...d})=>Bs(l,d,t),listAll:({projectId:l,...d})=>ft(async(p)=>{let f=await Bs(l,{...d,...p},t);return{items:f.datasets,pagination:f.pagination}},d),createField:async({datasetId:l,...d})=>{let p=await Vs(l,d,t);return _(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:d})=>{let p=await Vs(l,{fields:d},t);return _("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...d})=>Gs(l,d,t),getInferredFields:({datasetId:l})=>Wc(l,t),listAllFields:({datasetId:l,...d})=>ft(async(p)=>{let f=await Gs(l,{...d,...p},t);return{items:f.fields,pagination:f.pagination}},d),appendItems:({datasetId:l,...d})=>Hc(l,d,t),listItemsPage:({datasetId:l,...d})=>Ks(l,d,t),listAllItems:({datasetId:l,...d})=>ft(async(p)=>{let f=await Ks(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),startUpload:({datasetId:l,...d})=>Jc(l,d,t),finalizeUpload:({uploadId:l})=>Qc(l,t),getUpload:({uploadId:l})=>zs(l,t),startExport:({datasetId:l,...d})=>nd(l,d,t),getExport:({exportId:l})=>Js(l,t)},runs:{start:({pipelineId:l})=>{let d=new Headers(t.headers);return d.set("Content-Type","application/json"),rd(l,{...t,headers:d,body:"{}"})},get:({runId:l})=>Hs(l,t),cancel:({runId:l})=>id(l,t),listPage:({pipelineId:l,...d})=>Ws(l,d,t),listAll:({pipelineId:l,...d})=>ft(async(p)=>{let f=await Ws(l,{...d,...p},t);return{items:f.runs,pagination:f.pagination}},d),listItemsPage:({runId:l,...d})=>Qs(l,d,t),listAllItems:({runId:l,...d})=>ft(async(p)=>{let f=await Qs(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),getItem:({runId:l,itemId:d})=>hd(l,d,t)},secrets:{list:async({projectId:l})=>(await cd(l,t)).secrets,set:({projectId:l,name:d,...p})=>dd(l,d,p,t)},files:{list:async({projectId:l})=>(await ud(l,t)).files,startUpload:({projectId:l,...d})=>pd(l,d,t),finalizeUpload:({projectId:l,fileId:d})=>fd(l,d,t),delete:({projectId:l,fileId:d})=>md(l,d,t)},checks:{list:async({pipelineId:l})=>(await gd(l,t)).checks,start:({pipelineId:l,...d})=>yd(l,d,t),get:({checkRunId:l})=>Ys(l,t)},waitFor:r}};function nt(e){return mv(e)}var gr=require("fs/promises"),Qa=require("path"),$f=xe(Ja(),1);var Nn="toloka.json";class Ya extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var qx="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",Mx={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:qx},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},Ux=new $f.default({allErrors:!0,strict:!1}),wf=Ux.compile(Mx);function Bx(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 Ef(e){if(wf(e))return e;let t=wf.errors;throw _(t,"toloka.json validation failed without errors"),new Ya(`Invalid toloka.json: ${t.map(Bx).join("; ")}`)}async function $e(e){let t;try{t=await gr.readFile(Qa.join(e,Nn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Ef(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new Ya(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Nt(e,t){let r=Ef(t),i=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),n=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await gr.mkdir(e,{recursive:!0}),await gr.writeFile(Qa.join(e,Nn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
|
|
38
|
-
`,"utf8")}var
|
|
39
|
-
`,{mode:384}),await
|
|
40
|
-
`);return e.io.stdout(r),{output:r}}async function
|
|
41
|
-
`),{cause:n})}return}if(t.projectId===r.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function
|
|
42
|
-
`),{cause:
|
|
43
|
-
`);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var
|
|
44
|
-
`);function
|
|
45
|
-
`)};async function
|
|
46
|
-
${
|
|
47
|
-
`),n=(await e.prompt("API key: ",{mask:!0})).trim();
|
|
48
|
-
`),{cause:p})}let
|
|
49
|
-
`)}}async function
|
|
35
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((i)=>t.is(i)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Qc(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let r,i="127.0.0.1",n="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)r=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(r=s[1],/^\d+$/.test(s[3]))n=s[3];else i=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)r=s[1],i=s[3],n=s[4];if(r&&n!=="0")return`${r}=${i}:${parseInt(n)+1}`;return t})}function Yc(){if(U.default.env.NO_COLOR||U.default.env.FORCE_COLOR==="0"||U.default.env.FORCE_COLOR==="false")return!1;if(U.default.env.FORCE_COLOR||U.default.env.CLICOLOR_FORCE!==void 0)return!0;return}var Ck=new sr;function y(e,t){if(e)return;if(typeof t==="string")throw Error(t);throw t}var nn=require("path"),C_=require("readline/promises");class re extends Error{code;status;body;constructor(e,t,r,i){super(e);this.name="PotatoApiError",this.code=t,this.status=r,this.body=i}static fromResponse(e,t){return new re(`Potato API request failed with status ${e}`,"http",e,t)}static waitTimeout(e){return new re(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class or 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:r,reason:i})=>`- ${r}: ${i}`).join(`
|
|
36
|
+
`);return new or(`Pipeline graph validation failed
|
|
37
|
+
${t}`,e)}}var Hs="x-potato-sdk-base-url",ed=(e,t,r)=>(y(e.length>0,"The SDK base URL cannot be empty"),y(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[Hs]:new URL(e).toString()},fetch:r});async function C(e,t){let{fetch:r=globalThis.fetch,...i}=t,n=new Headers(i.headers),s=n.get(Hs);y(s,"The SDK base URL is missing"),n.delete(Hs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let d=a;if(a.length===0)d=void 0;else if(o.headers.get("content-type")?.includes("application/json"))d=JSON.parse(a);throw re.fromResponse(o.status,d)}return a.length===0?void 0:JSON.parse(a)}var nv=()=>"/api/v2-beta/me",td=async(e)=>C(nv(),{...e,method:"GET"}),sv=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([i,n])=>{if(n!==void 0)t.append(i,n===null?"null":n.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},Js=async(e,t)=>C(sv(e),{...t,method:"GET"}),ov=()=>"/api/v2-beta/projects",rd=async(e,t)=>C(ov(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),av=(e)=>`/api/v2-beta/projects/${e}`,id=async(e,t)=>C(av(e),{...t,method:"GET"}),lv=(e)=>`/api/v2-beta/projects/${e}`,nd=async(e,t,r)=>C(lv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),cv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Qs=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e)=>`/api/v2-beta/pipelines/${e}`,sd=async(e,t)=>C(dv(e),{...t,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}`,od=async(e,t,r)=>C(uv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),pv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/datasets?${i}`:`/api/v2-beta/projects/${e}/datasets`},Ys=async(e,t,r)=>C(pv(e,t),{...r,method:"GET"}),fv=(e)=>`/api/v2-beta/projects/${e}/datasets`,ad=async(e,t,r)=>C(fv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),mv=(e)=>`/api/v2-beta/datasets/${e}`,ld=async(e,t)=>C(mv(e),{...t,method:"GET"}),hv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/fields?${i}`:`/api/v2-beta/datasets/${e}/fields`},Xs=async(e,t,r)=>C(hv(e,t),{...r,method:"GET"}),gv=(e)=>`/api/v2-beta/datasets/${e}/fields`,Zs=async(e,t,r)=>C(gv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),yv=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,cd=async(e,t)=>C(yv(e),{...t,method:"GET"}),_v=(e)=>`/api/v2-beta/datasets/${e}/items`,dd=async(e,t,r)=>C(_v(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),bv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/items?${i}`:`/api/v2-beta/datasets/${e}/items`},eo=async(e,t,r)=>C(bv(e,t),{...r,method:"GET"}),Pv=(e)=>`/api/v2-beta/datasets/${e}/uploads`,ud=async(e,t,r)=>C(Pv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),vv=(e)=>`/api/v2-beta/uploads/${e}/finalize`,pd=async(e,t)=>C(vv(e),{...t,method:"POST"}),wv=(e)=>`/api/v2-beta/uploads/${e}`,to=async(e,t)=>C(wv(e),{...t,method:"GET"}),$v=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,fd=async(e,t,r)=>C($v(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Ev=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,md=async(e,t,r)=>C(Ev(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Iv=(e)=>`/api/v2-beta/pipelines/${e}/export`,hd=async(e,t)=>C(Iv(e),{...t,method:"GET"}),Sv=(e)=>`/api/v2-beta/pipelines/${e}/copy`,gd=async(e,t,r)=>C(Sv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),xv=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,yd=async(e,t,r)=>C(xv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Rv=(e)=>`/api/v2-beta/pipelines/${e}/runs`,_d=async(e,t)=>C(Rv(e),{...t,method:"POST"}),Cv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},ro=async(e,t,r)=>C(Cv(e,t),{...r,method:"GET"}),Ov=(e)=>`/api/v2-beta/runs/${e}`,io=async(e,t)=>C(Ov(e),{...t,method:"GET"});var jv=(e)=>`/api/v2-beta/runs/${e}/cancel`,bd=async(e,t)=>C(jv(e),{...t,method:"POST"}),Fv=(e)=>`/api/v2-beta/datasets/${e}/exports`,Pd=async(e,t,r)=>C(Fv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Tv=(e)=>`/api/v2-beta/exports/${e}`,no=async(e,t)=>C(Tv(e),{...t,method:"GET"}),kv=(e)=>`/api/v2-beta/pipelines/${e}/graph`,vd=async(e,t)=>C(kv(e),{...t,method:"GET"}),Av=(e)=>`/api/v2-beta/pipelines/${e}/graph`,wd=async(e,t,r)=>C(Av(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Dv=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,$d=async(e,t,r)=>C(Dv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Nv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,Ed=async(e,t,r,i)=>C(Nv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),Lv=(e)=>`/api/v2-beta/projects/${e}/secrets`,Id=async(e,t)=>C(Lv(e),{...t,method:"GET"}),qv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,Sd=async(e,t,r,i)=>C(qv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),Mv=(e)=>`/api/v2-beta/projects/${e}/files`,xd=async(e,t)=>C(Mv(e),{...t,method:"GET"}),Uv=(e)=>`/api/v2-beta/projects/${e}/files`,Rd=async(e,t,r)=>C(Uv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Bv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,Cd=async(e,t,r)=>C(Bv(e,t),{...r,method:"POST"}),Gv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,Od=async(e,t,r)=>C(Gv(e,t),{...r,method:"DELETE"}),Vv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/runs/${e}/items?${i}`:`/api/v2-beta/runs/${e}/items`},so=async(e,t,r)=>C(Vv(e,t),{...r,method:"GET"}),Kv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,jd=async(e,t,r)=>C(Kv(e,t),{...r,method:"GET"}),zv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Fd=async(e,t)=>C(zv(e),{...t,method:"GET"}),Wv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Td=async(e,t,r)=>C(Wv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Hv=(e)=>`/api/v2-beta/checks/${e}`,oo=async(e,t)=>C(Hv(e),{...t,method:"GET"});async function*bt(e,t={}){let r=t.offset;while(!0){let i=await e({limit:t.limit,offset:r});if(yield*i.items,!i.pagination.hasMore)return;r=i.pagination.offset+i.pagination.limit}}var Xr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;y(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),y(Number.isFinite(n)&&n>0,"The polling interval must be a positive finite number");let s=Date.now()+i,o=new AbortController,a=setTimeout(()=>o.abort(),i);try{while(!0){if(o.signal.aborted)throw re.waitTimeout(i);let d=await e(o.signal);if(t(d))return d;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:c}=Promise.withResolvers();setTimeout(c,Math.min(n,u)),await l}}catch(d){if(o.signal.aborted)throw re.waitTimeout(i);throw d}finally{clearTimeout(a)}};var Qv=(e)=>{let t=ed(e.baseUrl,e.apiKey,e.fetch);async function r(l,c){switch(l.type){case"datasetUpload":return Xr((p)=>to(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c);case"datasetExport":return Xr((p)=>no(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",c);case"pipelineCheck":return Xr((p)=>oo(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c);case"pipelineRun":return Xr((p)=>io(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c)}}return{me:()=>td(t),projects:{create:(l)=>rd(l,t),get:({projectId:l})=>id(l,t),update:({projectId:l,...c})=>nd(l,c,t),listPage:(l={})=>Js(l,t),listAll:(l={})=>bt(async(c)=>{let p=await Js({...l,...c},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...c})=>fd(l,c,t),get:({pipelineId:l})=>sd(l,t),update:({pipelineId:l,...c})=>od(l,c,t),listPage:({projectId:l,...c})=>Qs(l,c,t),listAll:({projectId:l,...c})=>bt(async(p)=>{let f=await Qs(l,{...c,...p},t);return{items:f.pipelines,pagination:f.pagination}},c),getGraph:({pipelineId:l})=>vd(l,t),replaceGraph:({pipelineId:l,...c})=>wd(l,"version"in c?{graph:c.graph,expectedVersion:c.version}:c,t),validateGraph:({pipelineId:l,...c})=>$d(l,c,t),estimateCost:({pipelineId:l,...c})=>yd(l,c,t),patchNode:({pipelineId:l,nodeId:c,...p})=>Ed(l,c,p,t),attachDataset:({pipelineId:l,...c})=>md(l,c,t),export:({pipelineId:l})=>hd(l,t),copy:({pipelineId:l,...c})=>gd(l,c,t)},datasets:{create:({projectId:l,...c})=>ad(l,c,t),get:({datasetId:l})=>ld(l,t),listPage:({projectId:l,...c})=>Ys(l,c,t),listAll:({projectId:l,...c})=>bt(async(p)=>{let f=await Ys(l,{...c,...p},t);return{items:f.datasets,pagination:f.pagination}},c),createField:async({datasetId:l,...c})=>{let p=await Zs(l,c,t);return y(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:c})=>{let p=await Zs(l,{fields:c},t);return y("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...c})=>Xs(l,c,t),getInferredFields:({datasetId:l})=>cd(l,t),listAllFields:({datasetId:l,...c})=>bt(async(p)=>{let f=await Xs(l,{...c,...p},t);return{items:f.fields,pagination:f.pagination}},c),appendItems:({datasetId:l,...c})=>dd(l,c,t),listItemsPage:({datasetId:l,...c})=>eo(l,c,t),listAllItems:({datasetId:l,...c})=>bt(async(p)=>{let f=await eo(l,{...c,...p},t);return{items:f.items,pagination:f.pagination}},c),startUpload:({datasetId:l,...c})=>ud(l,c,t),finalizeUpload:({uploadId:l})=>pd(l,t),getUpload:({uploadId:l})=>to(l,t),startExport:({datasetId:l,...c})=>Pd(l,c,t),getExport:({exportId:l})=>no(l,t)},runs:{start:({pipelineId:l})=>{let c=new Headers(t.headers);return c.set("Content-Type","application/json"),_d(l,{...t,headers:c,body:"{}"})},get:({runId:l})=>io(l,t),cancel:({runId:l})=>bd(l,t),listPage:({pipelineId:l,...c})=>ro(l,c,t),listAll:({pipelineId:l,...c})=>bt(async(p)=>{let f=await ro(l,{...c,...p},t);return{items:f.runs,pagination:f.pagination}},c),listItemsPage:({runId:l,...c})=>so(l,c,t),listAllItems:({runId:l,...c})=>bt(async(p)=>{let f=await so(l,{...c,...p},t);return{items:f.items,pagination:f.pagination}},c),getItem:({runId:l,itemId:c})=>jd(l,c,t)},secrets:{list:async({projectId:l})=>(await Id(l,t)).secrets,set:({projectId:l,name:c,...p})=>Sd(l,c,p,t)},files:{list:async({projectId:l})=>(await xd(l,t)).files,startUpload:({projectId:l,...c})=>Rd(l,c,t),finalizeUpload:({projectId:l,fileId:c})=>Cd(l,c,t),delete:({projectId:l,fileId:c})=>Od(l,c,t)},checks:{list:async({pipelineId:l})=>(await Fd(l,t)).checks,start:({pipelineId:l,...c})=>Td(l,c,t),get:({checkRunId:l})=>oo(l,t)},waitFor:r}};function ct(e){return Qv(e)}var wr=require("fs/promises"),sl=require("path"),qf=Ce(nl(),1);var Kn="toloka.json";class ol extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var vR="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",wR={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:vR},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},$R=new qf.default({allErrors:!0,strict:!1}),Lf=$R.compile(wR);function ER(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 Mf(e){if(Lf(e))return e;let t=Lf.errors;throw y(t,"toloka.json validation failed without errors"),new ol(`Invalid toloka.json: ${t.map(ER).join("; ")}`)}async function Ie(e){let t;try{t=await wr.readFile(sl.join(e,Kn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Mf(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new ol(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Gt(e,t){let r=Mf(t),i=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),n=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await wr.mkdir(e,{recursive:!0}),await wr.writeFile(sl.join(e,Kn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
|
|
38
|
+
`,"utf8")}var ge=require("fs/promises"),Gf=require("os"),$r=require("path");class Ii extends Error{constructor(e,t){super(e,t);this.name="CredentialsError"}}var Vf=(e)=>e.HOME??Gf.homedir(),IR=(e)=>e.XDG_CONFIG_HOME??$r.join(Vf(e),".config"),Ge=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??$r.join(IR(e),"toloka","credentials.json"),Kf=(e=process.env)=>$r.join(Vf(e),".toloka","credentials.json"),Uf=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},ft=(e)=>{let t=Uf(e.trim());try{let r=new URL(t);return r.hash="",r.search="",Uf(r.toString())}catch{return t}},zn=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,SR=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let r=Reflect.get(e,"name");if(r!==void 0&&typeof r!=="string")return;return r===void 0?{id:t}:{id:t,name:r}},xR=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[r,i]of Object.entries(e)){if(r.length===0)return;let n=SR(i);if(n===void 0)return;Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}return t},RR=(e,t)=>{let r=xR(e);if(r===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(r,t))return;return{current:t,projects:r}}if(t!==void 0)return;return Object.keys(r).length===0?{}:{projects:r}},CR=(e)=>{let t=zn(e,"baseUrl"),r=zn(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(typeof r!=="string"||r.length===0)return;let i=zn(e,"current"),n=zn(e,"projects");if(i===void 0&&n===void 0)return{baseUrl:t,apiKey:r};let s=RR(n,i);if(s===void 0)return;return{baseUrl:t,apiKey:r,...s}};async function Wn(e){let t;try{t=await ge.readFile(e,"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"missing";return"invalid"}try{let r=CR(JSON.parse(t));return r===void 0?"invalid":{credentials:r}}catch{return"invalid"}}async function al(e=process.env){let t=Ge(e),r=await Wn(t);if(r!=="missing"){if(r==="invalid")throw new Ii(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`);return{credentials:r.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let i=Kf(e),n=await Wn(i);if(n==="missing")return;if(n==="invalid")throw new Ii(`Invalid credentials file at ${i}. Run toloka logout, then toloka login.`);return{credentials:n.credentials,path:i,legacy:!0}}async function Si(e,t){try{return{found:await al(e)}}catch(r){if(!(r instanceof Ii)||t===void 0)throw r;return{found:void 0,warning:r.message}}}async function zf(e=process.env){return(await al(e))?.credentials}async function Ot(e=process.env){let t=await al(e);if(t!==void 0)return t;throw new Ii(`No stored credentials found at ${Ge(e)}. Run toloka login.`)}var OR=(e)=>{let t=e.projects,r=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,apiKey:e.apiKey,...e.current===void 0?{}:{current:e.current},...r?{projects:t}:{}}},Bf=async(e)=>{try{let t=await ge.lstat(e);y(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function ll(e){let t=$r.dirname(e);await Bf(t),await Bf(e),await ge.mkdir(t,{recursive:!0,mode:448}),await ge.chmod(t,448)}async function Hn(e,t=process.env){let r=Ge(t);return await ll(r),await ge.writeFile(r,`${JSON.stringify(OR(e),null,2)}
|
|
39
|
+
`,{mode:384}),await ge.chmod(r,384),r}var jR=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}};async function Wf(e=process.env){let t=[],r=[Ge(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Kf(e)]:[]];for(let i of r){if(!await jR(i))continue;await ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,Hf=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var de="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, set projectId in toloka.json, or run toloka project add.",TR="No project selected. Run toloka project add, or cd into a checkout.",Jf="project add writes the machine registry; unset --api-key / --base-url / POTATO_API_KEY / POTATO_BASE_URL, or run login against that platform first.",kR=/^[^/\s]+$/u,Jn=(e)=>{let t=e.trim();return y(t.length>0&&kR.test(t),"Project alias must be non-empty and contain no / or whitespace."),t},ye=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},AR=(e,t,r)=>ye(e?.baseUrl)??ye(t?.POTATO_BASE_URL)??mt(t??{})??ye(r?.baseUrl),xi=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,DR=(e,t,r)=>{if(!r||t?.projects===void 0)return{};if(t.current!==void 0){let i=xi(t.projects,t.current);if(i?.id===e)return i.name===void 0?{alias:t.current}:{alias:t.current,name:i.name}}for(let i of Object.keys(t.projects).toSorted()){let n=xi(t.projects,i);if(n?.id!==e)continue;return n.name===void 0?{alias:i}:{alias:i,name:n.name}}return{}};function Ri(e={}){let t=e.flags??{},r=e.environment??{},i=e.stored,n=e.effectiveBaseUrl??AR(t,r,i),s=i!==void 0&&n!==void 0&&ft(n)===ft(i.baseUrl),a=[{id:ye(t.projectId),source:"flag"},{id:ye(r.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:ye(r.POTATO_PROJECT_ID),source:"potato-project-id"},{id:ye(e.state?.projectId),source:"toloka.json"},{id:s&&i.current!==void 0?ye(i.projects?.[i.current]?.id):void 0,source:"registry"}].find((d)=>d.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...DR(a.id,i,s)}}var dl=(e,t)=>{if(e===void 0)return"Project: (none). Run toloka project add.";let r=e.alias===void 0?"":`alias ${e.alias}, `,i=e.source!=="registry"&&t?.current!==void 0?`; registry current is ${t.current}`:"";return`Project: ${e.id} (${r}from ${e.source}${i})`},Qn=(e,t,r)=>{let i=ye(e.apiKey)??ye(t.POTATO_API_KEY),n=ye(e.baseUrl)??ye(t.POTATO_BASE_URL)??mt(t);y(i===void 0||i===r.apiKey,Jf),y(n===void 0||ft(n)===ft(r.baseUrl),Jf)},Yn=async(e,t)=>{await Hn(e,t)},Qf=(e,t,r)=>{let i=Object.assign(Object.create(null),e.projects??{},{[t]:r.name===void 0?{id:r.id}:r});return{...e,current:t,projects:i}},cl=async(e,t,r)=>{y(e?.prompt,r);let i=(await e.prompt(t)).trim();return y(i.length>0,r),i};async function Yf(e){let t=[];for await(let i of e.client.projects.listAll()){let n=e.context?.id===i.id?"*":" ",s=e.context?.id===i.id&&e.context.alias!==void 0?` ${e.context.alias}`:"";t.push(`${n} ${i.id} ${i.name}${s}`)}let r=t.length===0?"No projects visible.":t.join(`
|
|
40
|
+
`);return e.io.stdout(r),{output:r}}async function Xf(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias??await cl(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),i=ye(e.projectId)??await cl(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),n=xi(t.credentials.projects,r);y(n===void 0||n.id===i,`Alias ${r} already points at ${n?.id}. Run toloka project remove ${r} first.`),await e.afterPreflight?.();let s=await e.client.projects.get({projectId:i});await Yn(Qf(t.credentials,r,{id:s.id,name:s.name}),e.environment);let o=`Using project ${s.id} as ${r}.`;return e.io?.stdout(o),{output:o,alias:r,projectId:s.id}}async function Zf(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias),i=xi(t.credentials.projects,r);y(i,`Unknown project alias ${r}.`),await Yn({...t.credentials,current:r},e.environment);let n=`Using project ${i.id} as ${r}.`;return e.io?.stdout(n),{output:n}}async function em(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias),i=Object.assign(Object.create(null),t.credentials.projects??{});y(xi(i,r),`Unknown project alias ${r}.`),delete i[r];let n=t.credentials.current===r?void 0:t.credentials.current;await Yn({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...n===void 0?{}:{current:n},...Object.keys(i).length===0?{}:{projects:i}},e.environment);let s=`Removed local alias ${r}.`;return e.io?.stdout(s),{output:s}}function tm(e){let t=Ri(e),r=t===void 0?TR:dl(t,e.stored);return e.io?.stdout(r),t===void 0?{output:r}:{output:r,project:t}}var NR=(e)=>{let t=[...new Set(e.map((r)=>r.teamId))];return t.length===1?t[0]:void 0},LR=async(e,t)=>{let r=ye(t);if(r!==void 0)return r;let i=[];for await(let s of e.projects.listAll())i.push(s);let n=NR(i);return y(n,"Missing team id. Pass --team-id. Visible projects do not share a single team, or none are visible."),n},qR=async(e,t,r,i)=>{if(t===void 0){try{await Gt(e,{projectId:r.id,pipelines:{},datasets:{}})}catch(n){let s=n instanceof Error?n.message:String(n);throw Error([`Created project ${r.id} as ${i}.`,`Failed to write toloka.json: ${s}`].join(`
|
|
41
|
+
`),{cause:n})}return}if(t.projectId===r.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function rm(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias??await cl(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));y(t.credentials.projects?.[r]===void 0,`Alias ${r} already exists. Run toloka project remove ${r} first.`);let i=e.sourceRoot===void 0?void 0:await Ie(e.sourceRoot);await e.afterPreflight?.();let n=await LR(e.client,e.teamId),s=await e.client.projects.create({teamId:n,name:ye(e.name)??r});try{await Yn(Qf(t.credentials,r,{id:s.id,name:s.name}),e.environment)}catch(d){let u=d instanceof Error?d.message:String(d);throw Error([`Created ${s.id} but failed to update the local registry: ${u}`,`Run: toloka project add ${r} ${s.id}`].join(`
|
|
42
|
+
`),{cause:d})}let o=[`Created project ${s.id} as ${r}.`];if(e.sourceRoot!==void 0){let d=await qR(e.sourceRoot,i,s,r);if(d!==void 0)o.push(d)}let a=o.join(`
|
|
43
|
+
`);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var Vt="https://platform.toloka.ai",MR=/^(?:prestable|pr-\d+)$/u,mt=(e)=>{let t=e.ENV?.trim();if(t===void 0||!MR.test(t))return;return`https://${t}.platform.toloka-test.ai`},UR="https://console.toloka.ai",BR="https://prestable.console.toloka-test.ai",im=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return UR;if(t.endsWith(".platform.toloka-test.ai"))return BR;return},GR=["Missing API key. Run toloka login once to store credentials for this machine:",""," toloka login","","It explains how to generate an API key and where it is saved. To override per command,","pass --api-key or set POTATO_API_KEY. Run toloka auth-status to see what is in effect."].join(`
|
|
44
|
+
`);function ul(e,t,r,i){let n=e.apiKey??r.POTATO_API_KEY??i?.apiKey,s=e.baseUrl??r.POTATO_BASE_URL??mt(r)??i?.baseUrl??Vt,o=Ri({flags:e,state:t,environment:r,stored:i,effectiveBaseUrl:s});return y(n,GR),{apiKey:n,baseUrl:s,...o===void 0?{}:{projectId:o.id}}}var VR=(e)=>{let t=im(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(`
|
|
45
|
+
`)};async function nm(e={}){let t=e.environment??process.env,r=e.write??(()=>{return}),i=ft(e.baseUrl??t.POTATO_BASE_URL??mt(t)??Vt),n=e.apiKey;if(n===void 0)y(e.prompt,"Missing API key. Pass --api-key, or set POTATO_API_KEY, when stdin is not a terminal."),r(`
|
|
46
|
+
${VR(i)}
|
|
47
|
+
`),n=(await e.prompt("API key: ",{mask:!0})).trim();y(n.length>0,"No API key entered.");let s={baseUrl:i,apiKey:n},o=e.probe?.(s)??ct(s),a;try{let p=await o.projects.listPage({limit:1});a=`Authenticated against ${i}: ${p.pagination.total} project(s) visible.`}catch(p){let f=p instanceof Error?p.message:String(p);throw Error([`Could not authenticate against ${i}: ${f}`,"","Nothing was saved. Check that the key was copied whole and has not been revoked."].join(`
|
|
48
|
+
`),{cause:p})}let d=Ge(t),u=await Wn(d),l=typeof u==="object"&&ft(u.credentials.baseUrl)===ft(i)?{baseUrl:i,apiKey:n,...u.credentials.current===void 0?{}:{current:u.credentials.current},...u.credentials.projects===void 0?{}:{projects:u.credentials.projects}}:s,c=await Hn(l,t);return{credentialsFile:c,baseUrl:i,output:[a,`Saved credentials to ${c}.`,"","toloka reads them automatically. --api-key and POTATO_API_KEY still win when set."].join(`
|
|
49
|
+
`)}}async function sm(e=process.env){let t=await Wf(e);return{removed:t,output:t.length===0?`No stored credentials found at ${Ge(e)}.`:`Removed ${t.join(", ")}.
|
|
50
50
|
|
|
51
|
-
This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var
|
|
52
|
-
`)};let{value:l,source:
|
|
51
|
+
This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var om=(e)=>e.find((t)=>t!==void 0),KR=(e,t,r,i)=>om([e.flagApiKey===void 0?void 0:{value:e.flagApiKey,source:"from --api-key"},t.POTATO_API_KEY===void 0?void 0:{value:t.POTATO_API_KEY,source:"from POTATO_API_KEY"},r===void 0?void 0:{value:r.credentials.apiKey,source:`stored in ${i}`}]),zR=(e,t,r)=>{let i=mt(t);return om([e.flagBaseUrl===void 0?void 0:{value:e.flagBaseUrl.replace(/\/+$/u,""),source:"from --base-url"},t.POTATO_BASE_URL===void 0?void 0:{value:t.POTATO_BASE_URL,source:"from POTATO_BASE_URL"},i===void 0?void 0:{value:i,source:`from ENV=${t.ENV}`},r===void 0?void 0:{value:r.credentials.baseUrl,source:"stored"}])??{value:Vt,source:"default"}};async function am(e={}){let t=e.environment??process.env,r=e.credentialLookup??await Si(t,e.flagApiKey??t.POTATO_API_KEY),{found:i,warning:n}=r,s=i?.path??Ge(t),o=KR(e,t,i,s),a=zR(e,t,i),d=dl(e.project,i?.credentials),u=n===void 0?[]:[n,""];if(o===void 0)return u.push("Not logged in.","","Run toloka login to store an API key for this machine.","",d),{authenticated:!1,output:u.join(`
|
|
52
|
+
`)};let{value:l,source:c}=a;if(u.push(`Platform: ${l} (${c})`,`API key: ${e.showToken===!0?o.value:Hf(o.value)} (${o.source})`,d),t.POTATO_API_KEY!==void 0&&i!==void 0)u.push("",`POTATO_API_KEY is set, so the key stored in ${i.path} is ignored.`);if(i?.legacy===!0)u.push("",`Credentials still live at the old path ${i.path}. Run toloka login to move them to ${Ge(t)}.`);let p=e.probe?.({baseUrl:l,apiKey:o.value})??ct({baseUrl:l,apiKey:o.value});try{let f=await p.projects.listPage({limit:1});return u.push("",`Reachable: ${f.pagination.total} project(s) visible.`),{authenticated:!0,output:u.join(`
|
|
53
53
|
`)}}catch(f){let m=f instanceof Error?f.message:String(f);return u.push("",`Not reachable: ${m}`,"","Run toloka login to store a working key."),{authenticated:!1,output:u.join(`
|
|
54
|
-
`)}}}var Th=require("crypto"),zt=require("fs/promises"),_s=require("path");var Pr=require("path");function zf(){let e=uR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function uR(e=process.argv[1]?Pr.dirname(process.argv[1]):process.cwd(),t=Pr.sep==="\\"){let r=t?Kf(e):e;return(i)=>{if(!i)return;let n=t?Kf(i):i,{dir:s,base:o,ext:a}=Pr.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let c=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${c}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function Kf(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var il=(e)=>{if("flags"in e){let t=Wf(e.flags),r=Hf(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Vn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,pR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function pR(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Wf=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,bi(r)]).filter(([,t])=>t!==void 0)),Hf=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map((r)=>{let i=t[r].metadata?.payload;return[r,i?Vn(i):void 0]}))},bi=(e)=>e===void 0?void 0:e.variant??e.enabled,Vn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var fR=["$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"],vi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return fR.forEach(i),t.forEach(i),r};var Ee=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 nl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var hR="NativeGzipValidationError",gR=31,yR=139,_R=8,PR=(e)=>e.length>=2&&e[0]===gR&&e[1]===yR;var wi,bR=()=>{if(wi)return wi;wi=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;wi[e]=t>>>0}return wi},vR=(e)=>{let t=bR(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Kn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=hR,t},wR=async(e,t)=>{if(e.size<18)Kn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!PR(r)||r[2]!==_R)Kn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==vR(t))Kn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Kn("invalid-size")};async function qt(e,t=!0,r){try{let i=new TextEncoder().encode(e),n=new globalThis.CompressionStream("gzip"),s=n.writable.getWriter(),o=s.write(i).then(()=>s.close()).catch(async(u)=>{try{await s.abort(u)}catch{}throw u}),a=new Response(n.readable).blob(),[c]=await Promise.all([a,o]);return await wR(c,i),c}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var $R=["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"],Jf=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return $R.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function br(e){let t=[];return JSON.stringify(e,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i=="function"||typeof i=="symbol")return;if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i})??"null"}var IR=Array.isArray,Qf=Object.prototype,dD=Qf.hasOwnProperty,zn=Qf.toString,He=IR||function(e){return zn.call(e)==="[object Array]"};var $i=(e)=>e===Object(e)&&!He(e);var Mt=(e)=>e===void 0,lt=(e)=>zn.call(e)=="[object String]",Yf=(e)=>lt(e)&&e.trim().length===0,Xf=(e)=>e===null;var Ei=(e)=>zn.call(e)=="[object Number]"&&e===e;var Zf=(e)=>zn.call(e)==="[object Boolean]";var em=(e)=>e instanceof Error;function Wn(e){return e===null||typeof e!="object"}function Ut(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function tm(e){return Ut(e,"ErrorEvent")}function vr(e){return typeof Event<"u"&&SR(e,Event)}function rm(e){return Ut(e,"Object")}function SR(e,t){try{return e instanceof t}catch{return!1}}function Ii(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ei(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return i.warn(" cannot be less than min: "+t+". Using min value instead."),t}return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),Ii(n||r,t,r,i)}var xR=86400000,RR=1,CR=10;function im(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??RR,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??CR}}class sl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ii(e.bucketSize,0,100,e._logger),this._refillRate=Ii(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ii(e.refillInterval,0,xR,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,i=Math.floor(r/this._refillInterval);if(i>0){let n=i*this._refillRate;e.tokens=Math.min(e.tokens+n,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];if(i)this._applyRefill(i,t);else i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i;if(i.tokens===0)return!0;if(i.tokens--,i.tokens===0)this._onBucketRateLimited?.(e);return i.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Bt{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Bt(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>281474976710655||t>4095||r>1073741823||i>4294967295)throw RangeError("invalid field value");let n=new Uint8Array(16);return n[0]=e/1099511627776,n[1]=e/4294967296,n[2]=e/16777216,n[3]=e/65536,n[4]=e/256,n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new Bt(n)}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 r=new Uint8Array(16);for(let i=0;i<16;i+=4){let n=parseInt(t.substring(2*i,2*i+8),16);r[i+0]=n>>>24,r[i+1]=n>>>16,r[i+2]=n>>>8,r[i+3]=n}return new Bt(r)}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 Bt(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class sm{constructor(e){this.timestamp=0,this.counter=0,this.random=e??jR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}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 Bt.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,Bt.ofInner(e)}}var jR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),nm,Ie=()=>FR().toString(),FR=()=>(nm||(nm=new sm)).generate();class ol{add(e){let t=Ie(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((i)=>i.id<=t&&!r.has(i.promise)).map((i)=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function OR(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var om=(e,t,r)=>{function i(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{i("debug",...s)},info:(...s)=>{i("log",...s)},warn:(...s)=>{i("warn",...s)},error:(...s)=>{i("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>om(`${e} ${s}`,t,r)}},TR=(e)=>e();function am(e,t=TR){return om(e,t,OR())}var $r="Mobile",Jn="iOS",wr="Android",pm="Tablet",wD=wr+" "+pm;var kR="Apple",$D=kR+" Watch",fm="Safari",Qn="BlackBerry",mm="Samsung",DR=mm+"Browser",NR=mm+" Internet",Yn="Chrome",LR=Yn+" OS",qR=Yn+" "+Jn,hm="Internet Explorer",MR=hm+" "+$r,ll="Opera",ED=ll+" Mini",gm="Edge",UR="Microsoft "+gm,cl="Firefox",BR=cl+" "+Jn,dl="Nintendo",ul="PlayStation",Hn="Xbox",GR=wr+" "+$r,VR=$r+" "+fm,Si="Windows",KR=Si+" Phone";var ym="Generic",ID=ym+" "+$r.toLowerCase(),SD=ym+" "+pm.toLowerCase(),zR="Konqueror",WR="Oculus Browser",lm="Vivaldi",HR="Yandex",cm="Whale",JR="DuckDuckGo",QR="Pale Moon",dm="Waterfox",um="Brave",YR="Google Search App",H="(\\d+(\\.\\d+)?)",al=new RegExp("Version/"+H);var xD=new RegExp(Hn,"i"),RD=new RegExp(ul+" \\w+","i"),CD=new RegExp(dl+" \\w+","i"),XR=new RegExp(Qn+"|PlayBook|BB10","i"),ZR={"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 jD={[MR]:[new RegExp("rv:"+H)],[UR]:[new RegExp(gm+"?\\/"+H)],[Yn]:[new RegExp("("+Yn+"|CrMo)\\/"+H)],[qR]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[fm]:[al],[VR]:[al],[ll]:[new RegExp("("+ll+"|OPR)\\/"+H)],[cl]:[new RegExp(cl+"\\/"+H)],[BR]:[new RegExp("FxiOS\\/"+H)],[zR]:[new RegExp("Konqueror[:/]?"+H,"i")],[Qn]:[new RegExp(Qn+" "+H),al],[GR]:[new RegExp("android\\s"+H,"i")],[NR]:[new RegExp(DR+"\\/"+H)],[WR]:[new RegExp("OculusBrowser\\/"+H)],[lm]:[new RegExp(lm+"\\/"+H)],[HR]:[new RegExp("YaBrowser\\/"+H)],[cm]:[new RegExp(cm+"\\/"+H)],[um]:[new RegExp(um+"\\/"+H)],[JR]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[QR]:[new RegExp("PaleMoon\\/"+H)],[dm]:[new RegExp(dm+"\\/"+H)],[YR]:[new RegExp("GSA\\/"+H)],[hm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var FD=[[new RegExp(Hn+"; "+Hn+" (.*?)[);]","i"),(e)=>[Hn,e&&e[1]||""]],[new RegExp(dl,"i"),[dl,""]],[new RegExp(ul,"i"),[ul,""]],[XR,[Qn,""]],[new RegExp(Si,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[KR,""];if(new RegExp($r).test(t)&&!/IEMobile\b/.test(t))return[Si+" "+$r,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=ZR[i]||"";if(/arm/i.test(t))n="RT";return[Si,n]}return[Si,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Jn,t.join(".")]}return[Jn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=Mt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+wr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[wr,t.join(".")]}return[wr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[LR,""]],[/Linux|debian/i,["Linux",""]]];var _m="utf8",eC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tC(e){return typeof e=="string"&&eC.test(e)}function Xn(e,t){return tC(e)?e:t()}function Pm(e){return e?.replace(/\/+$/,"")}async function bm(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){if(i>0)await new Promise((n)=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function pl(){return new Date().toISOString()}function de(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var vm=(e)=>e instanceof Error;function fl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var iC={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}},GD=iC.info;function ml(e){if(Zf(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(He(e))return{arrayValue:{values:e.map((t)=>ml(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function xi(e){let t=[];for(let r in e){let i=e[r];if(!(Xf(i)||Mt(i)))t.push({key:r,value:ml(i)})}return t}var Ri=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function hl(e){return String(e)+"000000"}function gl(e,t,r,i){let n="";if(i)n=Object.keys(i).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(i[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${n}`}function wm(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function yl(e,t,r){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":r}}function _l(e,t,r,i){return{resourceMetrics:[{resource:{attributes:xi(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function Zn(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 $m=1;class es{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,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,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}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 r,i;try{r=t.attributes?{...t.attributes}:void 0,i=gl(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let n=this._series.get(i);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(i,n)}let s=this._typeByName.get(t.name);if(s===void 0)this._typeByName.set(t.name,t.type);else if(s!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(n,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(Ri.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[wm(t,Ri)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=He(t)?t:[t],i=e;for(let n of r)try{let s=n(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=de(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(r.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:",r.error);return}}_buildPayload(e){return _l(this._buildMetrics(e),yl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=hl(Date.now()),r=new Map;for(let i of e.values()){let n=gl(i.type,i.name,i.unit,void 0),s=r.get(n);if(!s){if(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count")s.sum={aggregationTemporality:$m,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:$m,dataPoints:[]};r.set(n,s)}let o=xi(i.attributes??{}),a=hl(i.windowStartMs);if(i.type==="count"){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(c)}else if(i.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(c)}else if(i.hist){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ri};s.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let i=this._series.get(t);if(!i){if(this._admitNewSeries())this._series.set(t,r);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,r.windowStartMs),i.type){case"count":i.total=(i.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(i.hist){i.hist.count+=r.hist.count,i.hist.sum+=r.hist.sum,i.hist.min=Math.min(i.hist.min,r.hist.min),i.hist.max=Math.max(i.hist.max,r.hist.max);for(let n=0;n<i.hist.bucketCounts.length;n++)i.hist.bucketCounts[n]+=r.hist.bucketCounts[n]}else i.hist=r.hist;break}}}}class Pl{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((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}var ve={};s_(ve,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ds,DOMExceptionCoercer:()=>km,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ci,ErrorCoercer:()=>ss,ErrorEventCoercer:()=>Dm,ErrorPropertiesBuilder:()=>is,EventCoercer:()=>Lm,ExceptionStepsBuffer:()=>Um,ObjectCoercer:()=>ls,PrimitiveCoercer:()=>cs,PromiseRejectionEventCoercer:()=>qm,ReduceableCache:()=>Mm,StringCoercer:()=>os,chromeStackLineParser:()=>bl,createDefaultStackParser:()=>wl,createStackParser:()=>Am,geckoStackLineParser:()=>vl,getUtf8ByteLength:()=>Bm,nodeStackLineParser:()=>jm,opera10StackLineParser:()=>xm,opera11StackLineParser:()=>Rm,resolveExceptionStepsConfig:()=>$l,reverseAndStripFrames:()=>Tm,stripReservedExceptionStepFields:()=>IC,winjsStackLineParser:()=>Sm});var ts,Em,rs;function Im(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(rs&&r.length===Em)return rs;return Em=r.length,rs=r.reduce((i,n)=>{if(!ts)ts={};let s=ts[n];if(s)i[s[0]]=s[1];else{let o=e(n);for(let a=o.length-1;a>=0;a--){let u=o[a]?.filename,l=t[n];if(u&&l){i[u]=l,ts[n]=[u,l];break}}}return i},{}),rs}var aC=4;class is{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&He(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 r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let i;if(e.stack!=""&&e.stack!=null)i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)r.stacktrace={type:"raw",frames:e.stack};let i=[r];if(e.cause!=null)i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return i}buildParsingContext(e){return{chunkIdMap:Im(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=aC))return;{let a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return{...t,syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:(s)=>i(s,r),next:(s)=>i(s,r+1)}}}var se="?";function Je(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!Mt(i))s.lineno=i;if(!Mt(n))s.colno=n;return s}var ns=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:se,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var lC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dC=/\((\S*)(?::(\d+))(?::(\d+))\)/,bl=(e,t)=>{let r=lC.exec(e);if(r){let[,n,s,o]=r;return Je(t,n,se,+s,+o)}let i=cC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=dC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ns(i[1]||se,i[2]);return Je(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var uC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vl=(e,t)=>{let r=uC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=pC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let n=r[3],s=r[1]||se;return[s,n]=ns(s,n),Je(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var fC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Sm=(e,t)=>{let r=fC.exec(e);return r?Je(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var mC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,xm=(e,t)=>{let r=mC.exec(e);return r?Je(t,r[2],r[3]||se,+r[1]):void 0},hC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Rm=(e,t)=>{let r=hC.exec(e);return r?Je(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var gC=/^\s*[-]{4,}$/,yC=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,_C=/^Promise\.(?:all|any)$/,PC=/^index \d+$/,bC="node:internal/promise",jm=(e,t)=>{let r=e.match(yC);if(r){let i,n,s,o,a;if(r[1]){s=r[1];let l=s.lastIndexOf(".");if(s[l-1]===".")l--;if(l>0){i=s.slice(0,l),n=s.slice(l+1);let d=i.indexOf(".Module");if(d>0)s=s.slice(d+1),i=i.slice(0,d)}o=void 0}if(n)o=i,a=n;if(n==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||se,s=o?`${o}.${a}`:a;let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(c?.match(/\/[A-Z]:/))c=c.slice(1);if(!c&&r[5]&&!u)c=r[5];if(_C.test(s)&&PC.test(c||""))c=bC;return{filename:c?decodeURI(c):void 0,module:void 0,function:s,lineno:Cm(r[3]),colno:Cm(r[4]),in_app:vC(c||"",u),platform:t}}if(e.match(gC))return{filename:e,platform:t}};function vC(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 Cm(e){return parseInt(e||"",10)||void 0}var Fm=/\(error: (.*)\)/,Om=50;function Tm(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Om).map((r)=>({...r,filename:r.filename||wC(t).filename,function:r.function||se}))}function wC(e){return e[e.length-1]||{}}function wl(){return Am("web:javascript",bl,vl)}function Am(e,...t){return(r,i=0)=>{let n=[],s=r.split(`
|
|
55
|
-
`);for(let o=i;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let c=Fm.test(a)?a.replace(Fm,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){n.push(l);break}}if(n.length>=Om)break}}return Tm(n)}}class km{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=lt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?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 Ut(e,"DOMException")}isDOMError(e){return Ut(e,"DOMError")}}class ss{match(e){return em(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 r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Dm{constructor(){}match(e){return tm(e)&&e.error!=null}coerce(e,t){let r=t.apply(e.error);if(!r)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return r}}var $C=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class os{match(e){return typeof e=="string"}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match($C);if(i)t=i[1],r=i[2];return[t,r]}}var Nm=["fatal","error","warning","log","info","debug"];function as(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t)){if(i===r.length)return n;return n.length<=t?n:`${n.slice(0,t)}...`}}return""}class ls{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);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 vr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")i+=` with message: '${e.message}'`;return i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=as(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return lt(e)&&!Yf(e)&&Nm.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(vm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class Lm{match(e){return vr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${as(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class cs{match(e){return Wn(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class qm{match(e){return Ut(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!vr(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);if(Wn(r))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(r)}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 Mm{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 Ci={MESSAGE:"$message",TIMESTAMP:"$timestamp"},EC=new Set([Ci.MESSAGE,Ci.TIMESTAMP]),ds={enabled:!0,max_bytes:32768};function $l(e){if(!e)return{...ds};return{enabled:e.enabled??ds.enabled,max_bytes:SC(e.max_bytes,ds.max_bytes)}}function IC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(EC.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class Um{constructor(e){this._entries=[],this._totalBytes=0,this._config=$l(e)}setConfig(e){this._config=$l(e),this._trimToMaxBytes()}add(e){let t=xC(e);if(!t)return;let r=Bm(t.json);if(r>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,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 SC(e,t){if(!Ei(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function xC(e){let t;try{t=br(e)}catch{return}try{let r=JSON.parse(t);if(!$i(r))return;let i=r,n=i[Ci.MESSAGE],s=i[Ci.TIMESTAMP];if(!lt(n)||n.trim().length===0)return;if(!lt(s)&&!Ei(s))return;return{step:i,json:t}}catch{return}}function Bm(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let i=0;i<t.length;i++)if(t[i]==="%")r+=1,i+=2;else r+=1;return r}class St 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 Gt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var Km=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Gm(e){if(e instanceof St){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 RC(e){return typeof e=="object"&&(e instanceof St||zm(e))}function zm(e){return e instanceof Gt}function CC(e){if(e instanceof St)return e.status===502||e.status===504;if(!(e instanceof Gt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Er(e){return typeof e=="object"&&e instanceof St&&e.status===413}function ji(e){if(e instanceof St)return e.status===408||e.status===429||e.status>=500;return zm(e)}function Vm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var El="default";class us{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new is([new ss,new ls,new os,new cs],wl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ol,this._events=new Pl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=am("[PostHog]",this.logMsgIfDebug.bind(this)),n)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=Pm(i||"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:ji},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)||n,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=!nl()||(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(Ee.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,i)=>this._logger.info(r,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};if(Km(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=vi(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",n,i)})}async captureStatelessImmediate(e,t,r,i){let n=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",n,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",n,i)})}async aliasStatelessImmediate(e,t,r,i){let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",n,i)}groupIdentifyStateless(e,t,r,i,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,n,s){let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,i)}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`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((i)=>i.json()).catch((i)=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},r={},i={},n={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)c.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)c.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:CC},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:il(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof St)return{type:"api_error",statusCode:e.status};if(e instanceof Gt){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,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,i,n,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=bi(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,i,n,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,i,n,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},n,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},n,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,i,n,s);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o={geoip_disable:n??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,i,o);if(!a.success)return;let c=a.response;if(c.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(c.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:c?.requestId,quotaLimited:c.quotaLimited};return c}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"}},i=(await this.fetchWithRetry(e,t).then((n)=>{if(n.status!==200||!n.json){let s=`Surveys API could not be loaded: ${n.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return n.json()}).catch((n)=>{this._logger.error("Surveys API could not be loaded",n),this._events.emit("error",n)}))?.surveys;if(i)this._logger.info("Surveys fetched from API: ",JSON.stringify(i));return i??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ee.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ee.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ee.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return El}persistedQueueKeyForRoute(e){return Ee.Queue}getActiveQueueRoutes(){return[El]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(n)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:i}),this.setPersistedProperty(n,s),this._events.emit(e,i),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r){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 i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:i,...n}=e,s=Vm(n.properties)?n.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(i!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:i};if(s)n.properties=s;return n.uuid=Xn(n.uuid,Ie),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:pl(),uuid:Xn(t?.uuid,Ie)};if(t?.disableGeoip??this.disableGeoip){if(!Vm(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await Gm(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((n)=>!!n),i=0;while(!0){let n=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(n.length===0)return;if(i>0)this._logger.debug(`flush() re-checking ${n.length} pending promise(s) before flushing`);await Promise.all(n.map((s)=>s.catch(()=>{}))),i++}}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,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>fl([t])).then(()=>{if(this.pendingFlushPromise===i)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),fl([i]).then(()=>{if(this.flushPromises.delete(i),this.pendingFlushPromise===i)this.pendingFlushPromise=null;if(this.flushPromise===i)this.flushPromise=null}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=El){let i={api_key:this.apiKey,batch:e,sent_at:pl()};if(this.historicalMigration)i.historical_migration=!0;let n=br(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await qt(n,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||n};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((i)=>this.getRouteQueue(i).length>0))return;let t=[],r;for(let i of e)try{await this._flushRoute(i,t)}catch(n){if(r===void 0)r=n}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let n=i.length,s=0;while(i.length>0&&s<n){let o=i.slice(0,this.maxBatchSize),a=o.map((l)=>l.message===void 0?l.message:this.normalizeMessage(l.message)),c=async()=>{let d=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,d),i=d,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Er(l))return!1;return ji(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Er(l)&&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(!(l instanceof Gt))await c();throw this._events.emit("error",l),l}await c(),t.push(...a),s+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(s instanceof Gt)return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(ji(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,i){let n=t.body?t.body:"",s=-1;try{s=n instanceof Blob?n.size:Buffer.byteLength(n,_m)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await bm(async()=>{let o=new AbortController,a=i??this.requestTimeout,c=de(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(d){throw new Gt(d)}finally{clearTimeout(c)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new St(u,s);return u},{...this._retryOptions,...r})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let r=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!RC(n))throw n;await Gm(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),r()])}finally{clearTimeout(i)}}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 Jm=require("fs"),Qm=require("readline"),ps=new ve.ReduceableCache(25),Ym=new ve.ReduceableCache(20),Il=7,AC=1000,kC=1e4;async function Xm(e){let t={};for(let n=e.length-1;n>=0;n--){let s=e[n],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||qC(o)||MC(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Ym.get(n))continue;let s=t[n];if(!s)continue;s.sort((c,u)=>c-u);let o=BC(s);if(o.every((c)=>UC(n,c)))continue;let a=GC(ps,n,{});i.push(DC(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)NC(e,ps);return ps.reduce(),e}function DC(e,t,r){return new Promise((i)=>{let n=Jm.createReadStream(e),s=Qm.createInterface({input:n});function o(){n.destroy(),i()}let a=0,c=0,u=t[c];if(u===void 0)return void o();let l=u[0],d=u[1];function p(){Ym.set(e,1),s.close(),s.removeAllListeners(),o()}n.on("error",p),s.on("error",p),s.on("close",o),s.on("line",(f)=>{if(a++,a<l)return;if(r[a]=VC(f,0),a>=d){if(c===t.length-1){s.close(),s.removeAllListeners();return}c++;let m=t[c];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],d=m[1]}})})}function NC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;LC(r.lineno,r,i)}}function LC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=Zm(e);n<e;n++){let s=r[n];if(s===void 0)return void Wm(t);t.pre_context.push(s)}if(r[e]===void 0)return void Wm(t);t.context_line=r[e];let i=eh(e);t.post_context=[];for(let n=e+1;n<=i;n++){let s=r[n];if(s===void 0)break;t.post_context.push(s)}}function Wm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function qC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function MC(e){if(e.lineno!==void 0&&e.lineno>kC)return!0;if(e.colno!==void 0&&e.colno>AC)return!0;return!1}function UC(e,t){let r=ps.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function BC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Hm(r),n=[];while(!0){if(t===e.length-1){n.push(i);break}let s=e[t+1];if(typeof s!="number")break;if(s<=i[1])i[1]=s+Il;else n.push(i),i=Hm(s);t++}return n}function Hm(e){return[Zm(e),eh(e)]}function Zm(e){return Math.max(1,e-Il)}function eh(e){return e+Il}function GC(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function VC(e,t){let r=e,i=r.length;if(i<=150)return r;if(t>i)t=i;let n=Math.max(t-60,0);if(n<5)n=0;let s=Math.min(n+140,i);if(s>i-5)s=i;if(s===i)n=Math.max(s-140,0);if(r=r.slice(n,s),n>0)r=`...${r}`;if(s<i)r+="...";return r}var Ir=require("path");function th(e=process.cwd()){let t=Ir.sep==="\\",r=(n)=>t?n.replace(/\\/g,"/"):n,i=r(e);return async(n)=>{for(let s of n)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Ir.isAbsolute(s.filename))s.filename=r(Ir.relative(i,r(s.filename)))}return n}}var rh="5.46.1";var ct={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Vt{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 r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let n=this._flags[i];if(n)t[i]=n;else r.push(i)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let n=i.enabled===!1?!1:i.variant??!0;if(e[`$feature/${r}`]=n,i.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Vt({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],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)i.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(ct.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(ct.QUOTA_LIMITED);if(t===void 0)n.push(ct.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function ih(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var KC=60000,zC=1152921504606847000,WC=["is_not","is_set"];class Sr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Sr.prototype)}}function ah(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);ah(this,q)}}class Qe extends Error{constructor(e){super(e);ah(this,Qe)}}class Sl{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:n,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=n,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},r={},i={},n={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:n}}async getFeatureFlag(e,t,r={},i={},n={}){await this.loadFeatureFlags();let s,o;if(!this.loadedSuccessfullyOnce)return s;if(o=this.featureFlagsByKey[e],o!==void 0){let a=this.createEvaluationContext(t,r,i,n);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},n=this.featureFlags.length==0,s=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=c,u)i[a.key]=u}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:i,skipLoadCheck:n=!1}=r;if(!n)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let o=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:n,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new q("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let c=this.groupTypeMapping[String(a)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new q("Flag has unknown group type index");if(!(c in i))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"&&(n?.$device_id===void 0||n?.$device_id===null||n?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=s[c];return await this.matchFeatureFlagProperties(e,i[c],u,t)}{let c=this.getBucketingValueForFlag(e,r,n);if(c===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 q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,n,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=r?.$device_id;if(i==null||i==="")return;return i}return t}getFeatureFlagPayload(e,t){let r=null;if(t!==!1&&t!=null){if(typeof t=="boolean")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(r!=null){if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{}return r}}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,n=e.key;if(!this.featureFlagsByKey)throw new q("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new q(`Flag dependency property for '${n}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new q(`Flag dependency property for '${n}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new q(`Circular dependency detected for flag '${n}' (empty dependency chain)`);for(let a of s){if(!(a in i)){let u=this.featureFlagsByKey[a];if(u)if(u.active)try{let l=await this.computeFlagValueLocally(u,r);i[a]=l}catch(l){throw new q(`Error evaluating flag dependency '${a}' for flag '${n}': ${l}`)}else i[a]=!1;else throw new q(`Missing flag dependency '${a}' for flag '${n}'`)}if(i[a]==null)throw new q(`Dependency '${a}' could not be evaluated`)}let o=i[n];return this.flagEvaluatesToExpectedValue(e.value,o)}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,r,i){let n=e.filters||{},s=n.groups||[],o=n.aggregation_group_type_index,a=n.early_exit??!1,{groups:c,groupProperties:u}=i,l=!1,d;for(let p of s)try{let f=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:o,m=r,h=t;if(f!==o){if(f!=null){let y=this.groupTypeMapping[String(f)];if(!y||!(y in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(y in u)){l=!0;continue}m=u[y],h=c[y]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let y=p.variant,P=n.multivariate?.variants||[];d=y&&P.some((v)=>v.key===y)?y:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof Qe)throw f;if(f instanceof q)l=!0;else throw f}if(d!==void 0)return d;if(l)throw new q("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,n){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let c=a.type,u=!1;if(c==="cohort"){let l=await ch(a,i,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,i,n));u=a.operator==="not_in"?!l:l}else u=c==="flag"?await this.evaluateFlagDependency(a,i,n):lh(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await nh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await nh(e.key,t,"variant"),i=this.variantLookupTable(e).find((n)=>r>=n.valueMin&&r<n.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{i=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:o.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,r)=>(t[r.key]=r,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((r)=>r.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((r)=>r.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(KC,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(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}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 Sr(`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 Sr(`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 Sr(`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 r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(n){this.onError?.(Error(`Failed to store in cache: ${n}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){if(e instanceof Sr)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=de(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(r)}}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((r,i)=>setTimeout(()=>i(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function nh(e,t,r=""){let i=await ih(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/zC}function lh(e,t,r){let{key:i,value:n}=e,s=e.operator||"exact";if(i in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new q(`Property ${i} not found in propertyValues`)}let o=t[i];if(o==null&&!WC.includes(s)){if(r)r(`Property ${i} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(u,l){if(Array.isArray(u))return u.map((d)=>String(d).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,d){if(d==="gt")return u>l;if(d==="gte")return u>=l;if(d==="lt")return u<l;if(d==="lte")return u<=l;throw Error(`Invalid operator: ${d}`)}switch(s){case"exact":return a(n,o);case"is_not":return!a(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return sh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return sh(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof n=="number"?n:parseFloat(String(n)),l;if(l=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(u)&&Number.isFinite(l))return c(l,u,s);return c(String(o),String(n),s)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q("Date operations cannot be performed on boolean values");let u=XC(String(n));if(u==null)u=oh(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=oh(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return Oe(oe(String(o)),oe(String(n)))===0;case"semver_neq":return Oe(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return Oe(oe(String(o)),oe(String(n)))>0;case"semver_gte":return Oe(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return Oe(oe(String(o)),oe(String(n)))<0;case"semver_lte":return Oe(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:d}=JC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:d}=QC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:d}=YC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}default:throw new q(`Unknown operator: ${s}`)}}function HC(e,t){if(!(e in t))throw new Qe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function ch(e,t,r,i=!1,n){let s=String(e.value);HC(s,r);let o=r[s];return dh(o,t,r,i,n)}async function dh(e,t,r,i=!1,n){if(!e)return!0;let{type:s,values:o}=e;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let u=await dh(c,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("Can't match cohort without a given cohort property value");return s==="AND"}for(let c of o)try{let u;if(c.type==="cohort")u=await ch(c,t,r,i,n);else if(c.type==="flag"){if(!n)throw new q(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(c)}else u=lh(c,t);let l=c.negation||!1;if(s==="AND"){if(!u&&!l)return!1;if(u&&l)return!1}else{if(u&&!l)return!0;if(!u&&l)return!0}}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("can't match cohort without a given cohort property value");return s==="AND"}function sh(e){try{return new RegExp(e),!0}catch(t){return!1}}function uh(e,t){if(!/^\d+$/.test(e))throw new q(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new q(`Invalid semver: ${t}`);return parseInt(e,10)}function oe(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new q(`Invalid semver: ${e}`);let i=r.split("."),n=(c)=>{if(c===void 0||c==="")return 0;return uh(c,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function Oe(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function JC(e){let t=oe(e),r=[t[0],t[1],t[2]],i=[t[0],t[1]+1,0];return{lower:r,upper:i}}function QC(e){let t=oe(e),[r,i,n]=t,s=[r,i,n],o;return o=r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,n+1],{lower:s,upper:o}}function YC(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(c)=>{try{return uh(c,e)}catch{throw new q(`Invalid wildcard semver: ${e}`)}},s=n(i[0]),o,a;if(i.length===1)o=[s,0,0],a=[s+1,0,0];else{let c=n(i[1]);o=[s,c,0],a=[s,c+1,0]}return{lower:o,upper:a}}function oh(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 q(`${e} is in an invalid date format`)}throw new q(`The date provided ${e} must be a string, number, or date object`)}function XC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let s=r.groups.interval;if(s=="h")i.setUTCHours(i.getUTCHours()-n);else if(s=="d")i.setUTCDate(i.getUTCDate()-n);else if(s=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(s=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(s!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}function ZC(e,t){let r=!1;return Object.assign((i)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(i)},{_posthogErrorHandler:!0})}function ph(e,t){globalThis.process?.on("uncaughtException",ZC(e,t))}function fh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ej=2000;class Ye{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new sl({...im(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return $i(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,i,n){let s={...n},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())ph(this.onException.bind(this),this.onFatalError.bind(this)),fh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ye.isPreviouslyCapturedError(e)){let r=await Ye.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),n=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(n))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(ej),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class xl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function tj(e){return e==="v0"||e==="v1"}function mh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return tj(e)?e:"v0"}var Fi="analytics",Oi="ai";function hh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class xr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(xr.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let n=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(i instanceof Error)n+=` (${i.message})`;return n}}function Rl(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 rj(e){return typeof e=="string"?e:void 0}var ij=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Rl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Rl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Rl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:rj}],nj=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function sj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oj(e){if(typeof e=="string"){let r=new Date(e);return Number.isNaN(r.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 gh(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function aj(e){let r={...sj(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of ij)if(s in r){let c=a(r[s]);if(c!==void 0)i[o]=c;delete r[s]}let n={};for(let{property:s,field:o}of nj)if(s in r){let a=r[s];if(typeof a=="string")n[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,gh(r,"$set",e.$set),gh(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:oj(e.timestamp),...n,options:i,properties:r}}function yh(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(aj)};if(r)i.historical_migration=!0;return i}var lj="/i/v1/analytics/events",cj=30000,dj=new Set([408,500,502,503,504]);class Cl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??cj,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>de(i,r))),this.generateRequestId=t.generateRequestId??Ie,this.compress=t.compress??qt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=yh(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${lj}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let c=1;c<=a;c++){let u=c===a,l=br({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),d;try{d=await this.sendOnce(n,l,c,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(c));continue}let{status:p}=d;if(p<200||p>=300){if(!u&&dj.has(p)){let y=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(c,y));continue}let g=await this.buildHttpError(d,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${p} response body`))}let m=this.classify(o,f,s);if(m.length===0)return this.surfacePartialDrops(t,s);if(u)return void this.onError(new xr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(c,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);if(c!==null)s=c,n["Content-Encoding"]="gzip"}let o=new AbortController,a=de(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:n,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)i["User-Agent"]=this.config.userAgent;return i}classify(e,t,r){let i=t.results??{},n=[];for(let s of e){let o=i[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")n.push(s)}}return n}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let s=parseInt(r,10);return Number.isFinite(s)&&s>0?1000*s:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let n=i-this.now();return n>0?n:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let i=r.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let i=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,i){this.onError(new xr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new xr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var uj=100,_h=30000,pj=50000,fj=50,mj=500,hj="https://us.i.posthog.com",Ph=new Set;function fs(e,t){if(Ph.has(e))return;Ph.add(e),console.warn(`[PostHog] ${t}`)}function gj(e){return typeof e=="string"?e.trim():""}function yj(e){return(typeof e=="string"?e.trim():"")||void 0}function _j(e){return(typeof e=="string"?e.trim():"")||hj}function Pj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function bj(e){if(!e)return{};let t={};for(let[i,n]of Object.entries(e))t[`$feature/${i}`]=n;let r=Object.keys(e).filter((i)=>e[i]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class jl extends us{constructor(e,t={}){let r=gj(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:_j(t.host),personalApiKey:yj(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new xl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=mh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,uj):_h,typeof i.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0);if(typeof i.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0);if(!this.disabled&&i.personalApiKey){if(i.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(i.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Sl({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation})}this.errorTracking=new Ye(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||pj}enqueue(e,t,r){super.enqueue(e,t,r),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 s,o=new Promise((a)=>{s=a});try{e(o)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??mj,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??fj;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},n)}_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"&&hh(e)?Oi:Fi}persistedQueueKeyForRoute(e){return e===Oi?Ee.AiQueue:Ee.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Fi,Oi]:[Fi]}async sendBatch(e,t,r=Fi){if(this.captureMode!=="v1"||r===Oi)return super.sendBatch(e,t,r);let i=e.filter((n)=>n!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Cl({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 rh}get metrics(){if(!this._metrics)this._metrics=new es(this,Zn(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,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:n,event:s,properties:o,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c):this.enqueue(e,u,c)}).catch((n)=>{if(n)console.error(n)}))}_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:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let i={};if(Object.keys(t).length>0)i.$set=t;if(Object.keys(r).length>0)i.$set_once=r;this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=Pj(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}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=_h){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",(n)=>{clearTimeout(r),i(),t(n>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,r={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let n=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let E=this._flagOverrides[e];if(E===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,y,P,v,w;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let E=this.featureFlagsPoller?.featureFlagsByKey[e];if(E)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(E,d,{matchValue:i});if(x){f=!0;let T=x.value;y=E.id,v="Evaluated locally",w=E.has_experiment,p={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof Qe||x instanceof q)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!f&&!a){let E=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,o,[e]);if(E===void 0)g=ct.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(ct.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(ct.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(ct.FLAG_MISSING);else{y=T.metadata?.id,P=T.metadata?.version,v=T.reason?.description??T.reason?.code,w=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}p={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(n){let E=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,x={$feature_flag:e,$feature_flag_response:E,$feature_flag_id:y,$feature_flag_version:P,$feature_flag_reason:v,locally_evaluated:f,[`$feature/${e}`]:E,$feature_flag_request_id:m,$feature_flag_evaluated_at:f?Date.now():h};if(w!==void 0)x.$feature_flag_has_experiment=w;if(f&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(T!==void 0)x.$feature_flag_definitions_loaded_at=T}if(g)x.$feature_flag_error=g;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:E,groups:s,disableGeoip:o,properties:x})}if(p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)p={...p,payload:this._payloadOverrides[e]};return p}async getFeatureFlag(e,t,r){fs("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return i.variant??!0}async getFeatureFlagPayload(e,t,r,i){if(fs("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 n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(n===void 0)return;return n.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:n}=this._resolveDistinctId(t,r);if(!i)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,i,{...n,sendFeatureFlagEvents:n?.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 r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(i){}return r}async isFeatureEnabled(e,t,r){fs("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)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:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,c,u,s,o);f={...f,...g.flags||{}},m={...m,...g.payloads||{}}}if(this._flagOverrides!==void 0)f={...f,...this._flagOverrides};if(this._payloadOverrides!==void 0)m={...m,...this._payloadOverrides};return{featureFlags:f,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),P=new Set;if(y)for(let[w,I]of Object.entries(y.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:y.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},P.add(w)}if((y?y.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,s,o);if(w){this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt,h=Boolean(w.errorsWhileComputingFlags),g=Array.isArray(w.quotaLimited)&&w.quotaLimited.includes("feature_flags");for(let[I,E]of Object.entries(w.flags)){if(P.has(I))continue;let x;if(E.metadata?.payload!==void 0)try{x=JSON.parse(E.metadata.payload)}catch{x=E.metadata.payload}p[I]={key:I,enabled:E.enabled,variant:E.variant,payload:x,id:E.metadata?.id,version:E.metadata?.version,reason:E.reason?.description??E.reason?.code,locallyEvaluated:!1,hasExperiment:E.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[w,I]of Object.entries(this._flagOverrides)){if(I===void 0){delete p[w];continue}let E=p[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:E?.payload,id:E?.id,version:E?.version,reason:E?.reason,locallyEvaluated:E?.locallyEvaluated??!1,hasExperiment:E?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[w,I]of Object.entries(this._payloadOverrides)){let E=p[w];if(E)p[w]={...E,payload:I}}return new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:n,disableGeoip:s,flags:p,requestId:f,evaluatedAt:m,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:h,quotaLimited:g})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:n,disableGeoip:s,properties:o}=e,a=n&&Object.keys(n).length>0?`_${JSON.stringify(Object.entries(n).sort(([u],[l])=>u<l?-1:u>l?1:0))}`:"",c=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(c);else this.distinctIdHasSentFlagCalls[t]=new Set([c]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:n,disableGeoip:s})}_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:r,distinctId:i,disableGeoip:n}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((i)=>[i,!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 r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((i)=>de(i,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}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)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.options.requestTimeout),r.signal=n.signal}try{return await this.fetch(t,r)}catch(n){this._events.emit("error",n);return}finally{if(i)clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[n,s]of Object.entries(e))if(rm(s)&&t&&n in t){let o={};for(let[a,c]of Object.entries(s))o[String(a)]=String(c);i[String(n)]=o}else r[String(n)]=String(s);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let n=i?.personProperties||{},s=i?.groupProperties||{},o=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,n,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let n={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...i?.[o]||{}};return{allPersonProperties:n,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,n){if(!Ye.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:i,flags:n},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!Ye.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((s)=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:n,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=e,d=this.context?.get(),p=t.includeContextProperties??!0,f=r||d?.distinctId,m=p?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};if(!f)f=Ie(),m.$process_person_profile=!1;if(p&&d?.sessionId&&!m.$session_id)m.$session_id=d.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?vi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(o){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(a){fs("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 P=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,P);return bj(v)}return{}}).catch(()=>({})).then((P)=>{let v=g.groups||s;return{...P,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"){if(Jf(y.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",y.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:y,options:{timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let n of r){if(i=n(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}}var bh=require("async_hooks");class Fl{constructor(){this.storage=new bh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function vj(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(n==="*"||n.includes(o.level)))return o;if(!o.tags)o.tags={};let c=o.tags[vh.POSTHOG_ID_TAG];if(c===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();o.tags["PostHog Person URL"]=l;let d=o.exception?.values||[],p=d.map((m)=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map((h)=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags};if(t&&r)f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:c,properties:f});return o}}class vh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,n){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(vj(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ol extends jl{getLibraryId(){return"posthog-node"}initializeContext(){return new Fl}createErrorPropertiesBuilder(){return new ve.ErrorPropertiesBuilder([new ve.EventCoercer,new ve.ErrorCoercer,new ve.ObjectCoercer,new ve.StringCoercer,new ve.PrimitiveCoercer],ve.createStackParser("node:javascript",ve.nodeStackLineParser),[zf(),Xm,th()])}}var $h=require("crypto"),Z=require("fs/promises"),Y=require("path");var wh={name:"@toloka-platform/sdk",version:"0.1.0-preview.3",private:!1,description:"Preview. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"dist/cli/toloka.js"},files:["README.md","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"preview"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build",test:"vitest run",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","posthog-node":"5.46.1"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},engines:{bun:"1.4.0"}};var Kt=wh.version,Xe="@toloka-platform/sdk",hs="toloka-build",Eh=`.claude/skills/${hs}/SKILL.md`,Ih=`.cursor/rules/${hs}.mdc`,Rr="AGENTS.md",ms="<!-- toloka:begin -->",Ti="<!-- toloka:end -->",$j=/<!-- toloka:sdk-version ([^\s>]+) -->/u,Ej=/<!-- toloka:skill-digest sha256:([a-f0-9]{64}) -->/u,Ij=[Eh,Ih,Rr],Sh="toloka-pipeline-as-code",xh=Y.join(".claude","skills",Sh),Rh=Y.join(".cursor","rules",`${Sh}.mdc`),Sj=[xh,Rh],xj=[Y.join(xh,"SKILL.md"),Rh],Rj=[["SKILL.md",new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/node-semantics.md",new URL("../../skills/references/node-semantics.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/workflow-and-cli.md",new URL("../../skills/references/workflow-and-cli.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")]],Ai=(e)=>e instanceof Error&&("code"in e)&&e.code==="ENOENT",gs=async(e)=>{try{return await Z.readFile(e,"utf8")}catch(t){if(Ai(t))return;throw t}},Tl=async(e)=>{try{return(await Z.lstat(e)).isDirectory()}catch(t){if(Ai(t))return!1;throw t}},Cj=async(e)=>{try{return(await Z.lstat(e)).isFile()}catch(t){if(Ai(t))return!1;throw t}},Ch=async(e,t)=>{let r=e;for(let i of t.split("/")){r=Y.join(r,i);try{let n=await Z.lstat(r);_(!n.isSymbolicLink(),`Refusing to write through symbolic link ${r}.`)}catch(n){if(Ai(n))return;throw n}}};async function jh(){let e=$h.createHash("sha256");for(let[t,r]of Rj)e.update(t),e.update("\x00"),e.update(await Z.readFile(r)),e.update("\x00");return e.digest("hex")}var jj=new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts"),Fj=`node_modules/${Xe}/skills/references/`,Oj=async(e)=>{let n=(await Z.readFile(jj,"utf8")).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/u,"").replace(/^#\s.*\r?\n+/u,"").replaceAll("](references/",`](${Fj}`).replaceAll("](../examples/",`](node_modules/${Xe}/examples/`);return e==="##"?n:n.replaceAll(/^## /gmu,"### ")},Al=async(e,t)=>`Generated by \`${Xe}\` version \`${Kt}\`.
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
`)}}}var pg=require("crypto"),Xt=require("fs/promises"),Ss=require("path");var Er=require("path");function cm(){let e=WR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function WR(e=process.argv[1]?Er.dirname(process.argv[1]):process.cwd(),t=Er.sep==="\\"){let r=t?lm(e):e;return(i)=>{if(!i)return;let n=t?lm(i):i,{dir:s,base:o,ext:a}=Er.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let d=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${d}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${d}`:d}return d}}function lm(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var pl=(e)=>{if("flags"in e){let t=dm(e.flags),r=um(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Xn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,HR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function HR(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var dm=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Ci(r)]).filter(([,t])=>t!==void 0)),um=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map((r)=>{let i=t[r].metadata?.payload;return[r,i?Xn(i):void 0]}))},Ci=(e)=>e===void 0?void 0:e.variant??e.enabled,Xn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var JR=["$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"],Oi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return JR.forEach(i),t.forEach(i),r};var Se=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 fl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var YR="NativeGzipValidationError",XR=31,ZR=139,eC=8,tC=(e)=>e.length>=2&&e[0]===XR&&e[1]===ZR;var ji,rC=()=>{if(ji)return ji;ji=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;ji[e]=t>>>0}return ji},iC=(e)=>{let t=rC(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Zn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=YR,t},nC=async(e,t)=>{if(e.size<18)Zn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!tC(r)||r[2]!==eC)Zn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==iC(t))Zn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Zn("invalid-size")};async function Kt(e,t=!0,r){try{let i=new TextEncoder().encode(e),n=new globalThis.CompressionStream("gzip"),s=n.writable.getWriter(),o=s.write(i).then(()=>s.close()).catch(async(u)=>{try{await s.abort(u)}catch{}throw u}),a=new Response(n.readable).blob(),[d]=await Promise.all([a,o]);return await nC(d,i),d}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var sC=["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"],pm=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return sC.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function Ir(e){let t=[];return JSON.stringify(e,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i=="function"||typeof i=="symbol")return;if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i})??"null"}var aC=Array.isArray,fm=Object.prototype,r1=fm.hasOwnProperty,es=fm.toString,Ze=aC||function(e){return es.call(e)==="[object Array]"};var Fi=(e)=>e===Object(e)&&!Ze(e);var zt=(e)=>e===void 0,ht=(e)=>es.call(e)=="[object String]",mm=(e)=>ht(e)&&e.trim().length===0,hm=(e)=>e===null;var Ti=(e)=>es.call(e)=="[object Number]"&&e===e;var gm=(e)=>es.call(e)==="[object Boolean]";var ym=(e)=>e instanceof Error;function ts(e){return e===null||typeof e!="object"}function Wt(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function _m(e){return Wt(e,"ErrorEvent")}function Sr(e){return typeof Event<"u"&&lC(e,Event)}function bm(e){return Wt(e,"Object")}function lC(e,t){try{return e instanceof t}catch{return!1}}function ki(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ti(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return i.warn(" cannot be less than min: "+t+". Using min value instead."),t}return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),ki(n||r,t,r,i)}var cC=86400000,dC=1,uC=10;function Pm(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??dC,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??uC}}class ml{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ki(e.bucketSize,0,100,e._logger),this._refillRate=ki(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ki(e.refillInterval,0,cC,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,i=Math.floor(r/this._refillInterval);if(i>0){let n=i*this._refillRate;e.tokens=Math.min(e.tokens+n,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];if(i)this._applyRefill(i,t);else i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i;if(i.tokens===0)return!0;if(i.tokens--,i.tokens===0)this._onBucketRateLimited?.(e);return i.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Ht{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Ht(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>281474976710655||t>4095||r>1073741823||i>4294967295)throw RangeError("invalid field value");let n=new Uint8Array(16);return n[0]=e/1099511627776,n[1]=e/4294967296,n[2]=e/16777216,n[3]=e/65536,n[4]=e/256,n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new Ht(n)}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 r=new Uint8Array(16);for(let i=0;i<16;i+=4){let n=parseInt(t.substring(2*i,2*i+8),16);r[i+0]=n>>>24,r[i+1]=n>>>16,r[i+2]=n>>>8,r[i+3]=n}return new Ht(r)}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 Ht(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class wm{constructor(e){this.timestamp=0,this.counter=0,this.random=e??pC()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}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 Ht.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,Ht.ofInner(e)}}var pC=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),vm,xe=()=>fC().toString(),fC=()=>(vm||(vm=new wm)).generate();class hl{add(e){let t=xe(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((i)=>i.id<=t&&!r.has(i.promise)).map((i)=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function mC(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var $m=(e,t,r)=>{function i(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{i("debug",...s)},info:(...s)=>{i("log",...s)},warn:(...s)=>{i("warn",...s)},error:(...s)=>{i("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>$m(`${e} ${s}`,t,r)}},hC=(e)=>e();function Em(e,t=hC){return $m(e,t,mC())}var Rr="Mobile",is="iOS",xr="Android",Cm="Tablet",m1=xr+" "+Cm;var yC="Apple",h1=yC+" Watch",Om="Safari",ns="BlackBerry",jm="Samsung",_C=jm+"Browser",bC=jm+" Internet",ss="Chrome",PC=ss+" OS",vC=ss+" "+is,Fm="Internet Explorer",wC=Fm+" "+Rr,yl="Opera",g1=yl+" Mini",Tm="Edge",$C="Microsoft "+Tm,_l="Firefox",EC=_l+" "+is,bl="Nintendo",Pl="PlayStation",rs="Xbox",IC=xr+" "+Rr,SC=Rr+" "+Om,Ai="Windows",xC=Ai+" Phone";var km="Generic",y1=km+" "+Rr.toLowerCase(),_1=km+" "+Cm.toLowerCase(),RC="Konqueror",CC="Oculus Browser",Im="Vivaldi",OC="Yandex",Sm="Whale",jC="DuckDuckGo",FC="Pale Moon",xm="Waterfox",Rm="Brave",TC="Google Search App",H="(\\d+(\\.\\d+)?)",gl=new RegExp("Version/"+H);var b1=new RegExp(rs,"i"),P1=new RegExp(Pl+" \\w+","i"),v1=new RegExp(bl+" \\w+","i"),kC=new RegExp(ns+"|PlayBook|BB10","i"),AC={"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 w1={[wC]:[new RegExp("rv:"+H)],[$C]:[new RegExp(Tm+"?\\/"+H)],[ss]:[new RegExp("("+ss+"|CrMo)\\/"+H)],[vC]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[Om]:[gl],[SC]:[gl],[yl]:[new RegExp("("+yl+"|OPR)\\/"+H)],[_l]:[new RegExp(_l+"\\/"+H)],[EC]:[new RegExp("FxiOS\\/"+H)],[RC]:[new RegExp("Konqueror[:/]?"+H,"i")],[ns]:[new RegExp(ns+" "+H),gl],[IC]:[new RegExp("android\\s"+H,"i")],[bC]:[new RegExp(_C+"\\/"+H)],[CC]:[new RegExp("OculusBrowser\\/"+H)],[Im]:[new RegExp(Im+"\\/"+H)],[OC]:[new RegExp("YaBrowser\\/"+H)],[Sm]:[new RegExp(Sm+"\\/"+H)],[Rm]:[new RegExp(Rm+"\\/"+H)],[jC]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[FC]:[new RegExp("PaleMoon\\/"+H)],[xm]:[new RegExp(xm+"\\/"+H)],[TC]:[new RegExp("GSA\\/"+H)],[Fm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var $1=[[new RegExp(rs+"; "+rs+" (.*?)[);]","i"),(e)=>[rs,e&&e[1]||""]],[new RegExp(bl,"i"),[bl,""]],[new RegExp(Pl,"i"),[Pl,""]],[kC,[ns,""]],[new RegExp(Ai,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[xC,""];if(new RegExp(Rr).test(t)&&!/IEMobile\b/.test(t))return[Ai+" "+Rr,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=AC[i]||"";if(/arm/i.test(t))n="RT";return[Ai,n]}return[Ai,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[is,t.join(".")]}return[is,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=zt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+xr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+xr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[xr,t.join(".")]}return[xr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[PC,""]],[/Linux|debian/i,["Linux",""]]];var Am="utf8",DC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function NC(e){return typeof e=="string"&&DC.test(e)}function os(e,t){return NC(e)?e:t()}function Dm(e){return e?.replace(/\/+$/,"")}async function Nm(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){if(i>0)await new Promise((n)=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function vl(){return new Date().toISOString()}function ue(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Lm=(e)=>e instanceof Error;function wl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var qC={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}},A1=qC.info;function $l(e){if(gm(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(Ze(e))return{arrayValue:{values:e.map((t)=>$l(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function Di(e){let t=[];for(let r in e){let i=e[r];if(!(hm(i)||zt(i)))t.push({key:r,value:$l(i)})}return t}var Ni=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function El(e){return String(e)+"000000"}function Il(e,t,r,i){let n="";if(i)n=Object.keys(i).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(i[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${n}`}function qm(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Sl(e,t,r){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":r}}function xl(e,t,r,i){return{resourceMetrics:[{resource:{attributes:Di(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function as(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 Mm=1;class ls{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,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,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}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 r,i;try{r=t.attributes?{...t.attributes}:void 0,i=Il(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let n=this._series.get(i);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(i,n)}let s=this._typeByName.get(t.name);if(s===void 0)this._typeByName.set(t.name,t.type);else if(s!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(n,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(Ni.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[qm(t,Ni)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=Ze(t)?t:[t],i=e;for(let n of r)try{let s=n(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=ue(()=>{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,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(r.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:",r.error);return}}_buildPayload(e){return xl(this._buildMetrics(e),Sl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=El(Date.now()),r=new Map;for(let i of e.values()){let n=Il(i.type,i.name,i.unit,void 0),s=r.get(n);if(!s){if(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count")s.sum={aggregationTemporality:Mm,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:Mm,dataPoints:[]};r.set(n,s)}let o=Di(i.attributes??{}),a=El(i.windowStartMs);if(i.type==="count"){let d={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(d)}else if(i.type==="gauge"){let d={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(d)}else if(i.hist){let d={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ni};s.histogram.dataPoints.push(d)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let i=this._series.get(t);if(!i){if(this._admitNewSeries())this._series.set(t,r);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,r.windowStartMs),i.type){case"count":i.total=(i.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(i.hist){i.hist.count+=r.hist.count,i.hist.sum+=r.hist.sum,i.hist.min=Math.min(i.hist.min,r.hist.min),i.hist.max=Math.max(i.hist.max,r.hist.max);for(let n=0;n<i.hist.bucketCounts.length;n++)i.hist.bucketCounts[n]+=r.hist.bucketCounts[n]}else i.hist=r.hist;break}}}}class Rl{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((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}var $e={};U_($e,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>_s,DOMExceptionCoercer:()=>Xm,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Li,ErrorCoercer:()=>fs,ErrorEventCoercer:()=>Zm,ErrorPropertiesBuilder:()=>us,EventCoercer:()=>th,ExceptionStepsBuffer:()=>nh,ObjectCoercer:()=>gs,PrimitiveCoercer:()=>ys,PromiseRejectionEventCoercer:()=>rh,ReduceableCache:()=>ih,StringCoercer:()=>ms,chromeStackLineParser:()=>Cl,createDefaultStackParser:()=>jl,createStackParser:()=>Ym,geckoStackLineParser:()=>Ol,getUtf8ByteLength:()=>sh,nodeStackLineParser:()=>Wm,opera10StackLineParser:()=>Vm,opera11StackLineParser:()=>Km,resolveExceptionStepsConfig:()=>Fl,reverseAndStripFrames:()=>Qm,stripReservedExceptionStepFields:()=>aO,winjsStackLineParser:()=>Gm});var cs,Um,ds;function Bm(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(ds&&r.length===Um)return ds;return Um=r.length,ds=r.reduce((i,n)=>{if(!cs)cs={};let s=cs[n];if(s)i[s[0]]=s[1];else{let o=e(n);for(let a=o.length-1;a>=0;a--){let u=o[a]?.filename,l=t[n];if(u&&l){i[u]=l,cs[n]=[u,l];break}}}return i},{}),ds}var GC=4;class us{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&Ze(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 r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let i;if(e.stack!=""&&e.stack!=null)i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)r.stacktrace={type:"raw",frames:e.stack};let i=[r];if(e.cause!=null)i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return i}buildParsingContext(e){return{chunkIdMap:Bm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=GC))return;{let a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return{...t,syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:(s)=>i(s,r),next:(s)=>i(s,r+1)}}}var se="?";function et(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!zt(i))s.lineno=i;if(!zt(n))s.colno=n;return s}var ps=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:se,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var VC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,KC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,zC=/\((\S*)(?::(\d+))(?::(\d+))\)/,Cl=(e,t)=>{let r=VC.exec(e);if(r){let[,n,s,o]=r;return et(t,n,se,+s,+o)}let i=KC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=zC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ps(i[1]||se,i[2]);return et(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var WC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,HC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ol=(e,t)=>{let r=WC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=HC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let n=r[3],s=r[1]||se;return[s,n]=ps(s,n),et(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var JC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Gm=(e,t)=>{let r=JC.exec(e);return r?et(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var QC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Vm=(e,t)=>{let r=QC.exec(e);return r?et(t,r[2],r[3]||se,+r[1]):void 0},YC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Km=(e,t)=>{let r=YC.exec(e);return r?et(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var XC=/^\s*[-]{4,}$/,ZC=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,eO=/^Promise\.(?:all|any)$/,tO=/^index \d+$/,rO="node:internal/promise",Wm=(e,t)=>{let r=e.match(ZC);if(r){let i,n,s,o,a;if(r[1]){s=r[1];let l=s.lastIndexOf(".");if(s[l-1]===".")l--;if(l>0){i=s.slice(0,l),n=s.slice(l+1);let c=i.indexOf(".Module");if(c>0)s=s.slice(c+1),i=i.slice(0,c)}o=void 0}if(n)o=i,a=n;if(n==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||se,s=o?`${o}.${a}`:a;let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(d?.match(/\/[A-Z]:/))d=d.slice(1);if(!d&&r[5]&&!u)d=r[5];if(eO.test(s)&&tO.test(d||""))d=rO;return{filename:d?decodeURI(d):void 0,module:void 0,function:s,lineno:zm(r[3]),colno:zm(r[4]),in_app:iO(d||"",u),platform:t}}if(e.match(XC))return{filename:e,platform:t}};function iO(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 zm(e){return parseInt(e||"",10)||void 0}var Hm=/\(error: (.*)\)/,Jm=50;function Qm(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Jm).map((r)=>({...r,filename:r.filename||nO(t).filename,function:r.function||se}))}function nO(e){return e[e.length-1]||{}}function jl(){return Ym("web:javascript",Cl,Ol)}function Ym(e,...t){return(r,i=0)=>{let n=[],s=r.split(`
|
|
55
|
+
`);for(let o=i;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let d=Hm.test(a)?a.replace(Hm,"$1"):a;if(!d.match(/\S*Error: /)){for(let u of t){let l=u(d,e);if(l){n.push(l);break}}if(n.length>=Jm)break}}return Qm(n)}}class Xm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=ht(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?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 Wt(e,"DOMException")}isDOMError(e){return Wt(e,"DOMError")}}class fs{match(e){return ym(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 r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Zm{constructor(){}match(e){return _m(e)&&e.error!=null}coerce(e,t){let r=t.apply(e.error);if(!r)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return r}}var sO=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ms{match(e){return typeof e=="string"}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(sO);if(i)t=i[1],r=i[2];return[t,r]}}var eh=["fatal","error","warning","log","info","debug"];function hs(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t)){if(i===r.length)return n;return n.length<=t?n:`${n.slice(0,t)}...`}}return""}class gs{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);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 Sr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")i+=` with message: '${e.message}'`;return i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=hs(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return ht(e)&&!mm(e)&&eh.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(Lm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class th{match(e){return Sr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${hs(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class ys{match(e){return ts(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class rh{match(e){return Wt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Sr(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);if(ts(r))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(r)}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 ih{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 Li={MESSAGE:"$message",TIMESTAMP:"$timestamp"},oO=new Set([Li.MESSAGE,Li.TIMESTAMP]),_s={enabled:!0,max_bytes:32768};function Fl(e){if(!e)return{..._s};return{enabled:e.enabled??_s.enabled,max_bytes:lO(e.max_bytes,_s.max_bytes)}}function aO(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(oO.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class nh{constructor(e){this._entries=[],this._totalBytes=0,this._config=Fl(e)}setConfig(e){this._config=Fl(e),this._trimToMaxBytes()}add(e){let t=cO(e);if(!t)return;let r=sh(t.json);if(r>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,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 lO(e,t){if(!Ti(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function cO(e){let t;try{t=Ir(e)}catch{return}try{let r=JSON.parse(t);if(!Fi(r))return;let i=r,n=i[Li.MESSAGE],s=i[Li.TIMESTAMP];if(!ht(n)||n.trim().length===0)return;if(!ht(s)&&!Ti(s))return;return{step:i,json:t}}catch{return}}function sh(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let i=0;i<t.length;i++)if(t[i]==="%")r+=1,i+=2;else r+=1;return r}class jt extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class Jt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var lh=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function oh(e){if(e instanceof jt){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function dO(e){return typeof e=="object"&&(e instanceof jt||ch(e))}function ch(e){return e instanceof Jt}function uO(e){if(e instanceof jt)return e.status===502||e.status===504;if(!(e instanceof Jt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Cr(e){return typeof e=="object"&&e instanceof jt&&e.status===413}function qi(e){if(e instanceof jt)return e.status===408||e.status===429||e.status>=500;return ch(e)}function ah(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tl="default";class bs{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new us([new fs,new gs,new ms,new ys],jl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new hl,this._events=new Rl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=Em("[PostHog]",this.logMsgIfDebug.bind(this)),n)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=Dm(i||"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:qi},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)||n,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=!fl()||(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(Se.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Se.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Se.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,i)=>this._logger.info(r,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};if(lh(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=Oi(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",n,i)})}async captureStatelessImmediate(e,t,r,i){let n=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",n,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",n,i)})}async aliasStatelessImmediate(e,t,r,i){let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",n,i)}groupIdentifyStateless(e,t,r,i,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,n,s){let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,i)}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`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((i)=>i.json()).catch((i)=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},r={},i={},n={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,d={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)d.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)d.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(d)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:uO},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:pl(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof jt)return{type:"api_error",statusCode:e.status};if(e instanceof Jt){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,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,i,n,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=Ci(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,i,n,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,i,n,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},n,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},n,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,i,n,s);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o={geoip_disable:n??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,i,o);if(!a.success)return;let d=a.response;if(d.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(d.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:d?.requestId,quotaLimited:d.quotaLimited};return d}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"}},i=(await this.fetchWithRetry(e,t).then((n)=>{if(n.status!==200||!n.json){let s=`Surveys API could not be loaded: ${n.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return n.json()}).catch((n)=>{this._logger.error("Surveys API could not be loaded",n),this._events.emit("error",n)}))?.surveys;if(i)this._logger.info("Surveys fetched from API: ",JSON.stringify(i));return i??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Se.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Se.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Se.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Tl}persistedQueueKeyForRoute(e){return Se.Queue}getActiveQueueRoutes(){return[Tl]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(n)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:i}),this.setPersistedProperty(n,s),this._events.emit(e,i),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=ue(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r){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 i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:i,...n}=e,s=ah(n.properties)?n.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(i!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:i};if(s)n.properties=s;return n.uuid=os(n.uuid,xe),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:vl(),uuid:os(t?.uuid,xe)};if(t?.disableGeoip??this.disableGeoip){if(!ah(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await oh(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((n)=>!!n),i=0;while(!0){let n=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(n.length===0)return;if(i>0)this._logger.debug(`flush() re-checking ${n.length} pending promise(s) before flushing`);await Promise.all(n.map((s)=>s.catch(()=>{}))),i++}}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,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>wl([t])).then(()=>{if(this.pendingFlushPromise===i)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),wl([i]).then(()=>{if(this.flushPromises.delete(i),this.pendingFlushPromise===i)this.pendingFlushPromise=null;if(this.flushPromise===i)this.flushPromise=null}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=Tl){let i={api_key:this.apiKey,batch:e,sent_at:vl()};if(this.historicalMigration)i.historical_migration=!0;let n=Ir(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await Kt(n,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||n};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((i)=>this.getRouteQueue(i).length>0))return;let t=[],r;for(let i of e)try{await this._flushRoute(i,t)}catch(n){if(r===void 0)r=n}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let n=i.length,s=0;while(i.length>0&&s<n){let o=i.slice(0,this.maxBatchSize),a=o.map((l)=>l.message===void 0?l.message:this.normalizeMessage(l.message)),d=async()=>{let c=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,c),i=c,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Cr(l))return!1;return qi(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Cr(l)&&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(!(l instanceof Jt))await d();throw this._events.emit("error",l),l}await d(),t.push(...a),s+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await Kt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Cr(s))return!1;return qi(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(s instanceof Jt)return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await Kt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Cr(s))return!1;return qi(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(qi(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,i){let n=t.body?t.body:"",s=-1;try{s=n instanceof Blob?n.size:Buffer.byteLength(n,Am)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await Nm(async()=>{let o=new AbortController,a=i??this.requestTimeout,d=ue(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(c){throw new Jt(c)}finally{clearTimeout(d)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new jt(u,s);return u},{...this._retryOptions,...r})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let r=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!dO(n))throw n;await oh(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=ue(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),r()])}finally{clearTimeout(i)}}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 ph=require("fs"),fh=require("readline"),Ps=new $e.ReduceableCache(25),mh=new $e.ReduceableCache(20),kl=7,gO=1000,yO=1e4;async function hh(e){let t={};for(let n=e.length-1;n>=0;n--){let s=e[n],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||vO(o)||wO(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(mh.get(n))continue;let s=t[n];if(!s)continue;s.sort((d,u)=>d-u);let o=EO(s);if(o.every((d)=>$O(n,d)))continue;let a=IO(Ps,n,{});i.push(_O(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)bO(e,Ps);return Ps.reduce(),e}function _O(e,t,r){return new Promise((i)=>{let n=ph.createReadStream(e),s=fh.createInterface({input:n});function o(){n.destroy(),i()}let a=0,d=0,u=t[d];if(u===void 0)return void o();let l=u[0],c=u[1];function p(){mh.set(e,1),s.close(),s.removeAllListeners(),o()}n.on("error",p),s.on("error",p),s.on("close",o),s.on("line",(f)=>{if(a++,a<l)return;if(r[a]=SO(f,0),a>=c){if(d===t.length-1){s.close(),s.removeAllListeners();return}d++;let m=t[d];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],c=m[1]}})})}function bO(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;PO(r.lineno,r,i)}}function PO(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=gh(e);n<e;n++){let s=r[n];if(s===void 0)return void dh(t);t.pre_context.push(s)}if(r[e]===void 0)return void dh(t);t.context_line=r[e];let i=yh(e);t.post_context=[];for(let n=e+1;n<=i;n++){let s=r[n];if(s===void 0)break;t.post_context.push(s)}}function dh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function vO(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function wO(e){if(e.lineno!==void 0&&e.lineno>yO)return!0;if(e.colno!==void 0&&e.colno>gO)return!0;return!1}function $O(e,t){let r=Ps.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function EO(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=uh(r),n=[];while(!0){if(t===e.length-1){n.push(i);break}let s=e[t+1];if(typeof s!="number")break;if(s<=i[1])i[1]=s+kl;else n.push(i),i=uh(s);t++}return n}function uh(e){return[gh(e),yh(e)]}function gh(e){return Math.max(1,e-kl)}function yh(e){return e+kl}function IO(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function SO(e,t){let r=e,i=r.length;if(i<=150)return r;if(t>i)t=i;let n=Math.max(t-60,0);if(n<5)n=0;let s=Math.min(n+140,i);if(s>i-5)s=i;if(s===i)n=Math.max(s-140,0);if(r=r.slice(n,s),n>0)r=`...${r}`;if(s<i)r+="...";return r}var Or=require("path");function _h(e=process.cwd()){let t=Or.sep==="\\",r=(n)=>t?n.replace(/\\/g,"/"):n,i=r(e);return async(n)=>{for(let s of n)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Or.isAbsolute(s.filename))s.filename=r(Or.relative(i,r(s.filename)))}return n}}var bh="5.46.1";var gt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Qt{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 r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let n=this._flags[i];if(n)t[i]=n;else r.push(i)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let n=i.enabled===!1?!1:i.variant??!0;if(e[`$feature/${r}`]=n,i.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Qt({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],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)i.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(gt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(gt.QUOTA_LIMITED);if(t===void 0)n.push(gt.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function Ph(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var xO=60000,RO=1152921504606847000,CO=["is_not","is_set"];class jr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,jr.prototype)}}function Eh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);Eh(this,q)}}class tt extends Error{constructor(e){super(e);Eh(this,tt)}}class Al{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:n,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=n,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},r={},i={},n={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:n}}async getFeatureFlag(e,t,r={},i={},n={}){await this.loadFeatureFlags();let s,o;if(!this.loadedSuccessfullyOnce)return s;if(o=this.featureFlagsByKey[e],o!==void 0){let a=this.createEvaluationContext(t,r,i,n);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(d){if(d instanceof tt||d instanceof q)this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${e}: ${d.message}`));else if(d instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${d}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},n=this.featureFlags.length==0,s=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async(a)=>{try{let{value:d,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=d,u)i[a.key]=u}catch(d){if(d instanceof tt||d instanceof q)this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${a.key}: ${d.message}`));else if(d instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${d}`));n=!0}})),{response:r,payloads:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:i,skipLoadCheck:n=!1}=r;if(!n)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let o=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:n,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new q("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let d=this.groupTypeMapping[String(a)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new q("Flag has unknown group type index");if(!(d in i))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"&&(n?.$device_id===void 0||n?.$device_id===null||n?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=s[d];return await this.matchFeatureFlagProperties(e,i[d],u,t)}{let d=this.getBucketingValueForFlag(e,r,n);if(d===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 q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,d,n,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=r?.$device_id;if(i==null||i==="")return;return i}return t}getFeatureFlagPayload(e,t){let r=null;if(t!==!1&&t!=null){if(typeof t=="boolean")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(r!=null){if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{}return r}}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,n=e.key;if(!this.featureFlagsByKey)throw new q("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new q(`Flag dependency property for '${n}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new q(`Flag dependency property for '${n}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new q(`Circular dependency detected for flag '${n}' (empty dependency chain)`);for(let a of s){if(!(a in i)){let u=this.featureFlagsByKey[a];if(u)if(u.active)try{let l=await this.computeFlagValueLocally(u,r);i[a]=l}catch(l){throw new q(`Error evaluating flag dependency '${a}' for flag '${n}': ${l}`)}else i[a]=!1;else throw new q(`Missing flag dependency '${a}' for flag '${n}'`)}if(i[a]==null)throw new q(`Dependency '${a}' could not be evaluated`)}let o=i[n];return this.flagEvaluatesToExpectedValue(e.value,o)}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,r,i){let n=e.filters||{},s=n.groups||[],o=n.aggregation_group_type_index,a=n.early_exit??!1,{groups:d,groupProperties:u}=i,l=!1,c;for(let p of s)try{let f=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:o,m=r,h=t;if(f!==o){if(f!=null){let _=this.groupTypeMapping[String(f)];if(!_||!(_ in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(_ in u)){l=!0;continue}m=u[_],h=d[_]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let _=p.variant,b=n.multivariate?.variants||[];c=_&&b.some((v)=>v.key===_)?_:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof tt)throw f;if(f instanceof q)l=!0;else throw f}if(c!==void 0)return c;if(l)throw new q("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,n){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let d=a.type,u=!1;if(d==="cohort"){let l=await Sh(a,i,this.cohorts,this.debugMode,(c)=>this.evaluateFlagDependency(c,i,n));u=a.operator==="not_in"?!l:l}else u=d==="flag"?await this.evaluateFlagDependency(a,i,n):Ih(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await vh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await vh(e.key,t,"variant"),i=this.variantLookupTable(e).find((n)=>r>=n.valueMin&&r<n.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{i=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:o.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,r)=>(t[r.key]=r,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((r)=>r.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((r)=>r.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(xO,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(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}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 jr(`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 jr(`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 jr(`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 r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(n){this.onError?.(Error(`Failed to store in cache: ${n}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){if(e instanceof jr)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=ue(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(r)}}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((r,i)=>setTimeout(()=>i(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function vh(e,t,r=""){let i=await Ph(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/RO}function Ih(e,t,r){let{key:i,value:n}=e,s=e.operator||"exact";if(i in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new q(`Property ${i} not found in propertyValues`)}let o=t[i];if(o==null&&!CO.includes(s)){if(r)r(`Property ${i} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(u,l){if(Array.isArray(u))return u.map((c)=>String(c).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function d(u,l,c){if(c==="gt")return u>l;if(c==="gte")return u>=l;if(c==="lt")return u<l;if(c==="lte")return u<=l;throw Error(`Invalid operator: ${c}`)}switch(s){case"exact":return a(n,o);case"is_not":return!a(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return wh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return wh(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof n=="number"?n:parseFloat(String(n)),l;if(l=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(u)&&Number.isFinite(l))return d(l,u,s);return d(String(o),String(n),s)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q("Date operations cannot be performed on boolean values");let u=kO(String(n));if(u==null)u=$h(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=$h(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return ke(oe(String(o)),oe(String(n)))===0;case"semver_neq":return ke(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return ke(oe(String(o)),oe(String(n)))>0;case"semver_gte":return ke(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return ke(oe(String(o)),oe(String(n)))<0;case"semver_lte":return ke(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:c}=jO(String(n));return ke(u,l)>=0&&ke(u,c)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:c}=FO(String(n));return ke(u,l)>=0&&ke(u,c)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:c}=TO(String(n));return ke(u,l)>=0&&ke(u,c)<0}default:throw new q(`Unknown operator: ${s}`)}}function OO(e,t){if(!(e in t))throw new tt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Sh(e,t,r,i=!1,n){let s=String(e.value);OO(s,r);let o=r[s];return xh(o,t,r,i,n)}async function xh(e,t,r,i=!1,n){if(!e)return!0;let{type:s,values:o}=e;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let d of o)try{let u=await xh(d,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof tt)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${d} locally: ${u}`);a=!0}else throw u}if(a)throw new q("Can't match cohort without a given cohort property value");return s==="AND"}for(let d of o)try{let u;if(d.type==="cohort")u=await Sh(d,t,r,i,n);else if(d.type==="flag"){if(!n)throw new q(`Flag dependency '${d.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(d)}else u=Ih(d,t);let l=d.negation||!1;if(s==="AND"){if(!u&&!l)return!1;if(u&&l)return!1}else{if(u&&!l)return!0;if(!u&&l)return!0}}catch(u){if(u instanceof tt)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${d} locally: ${u}`);a=!0}else throw u}if(a)throw new q("can't match cohort without a given cohort property value");return s==="AND"}function wh(e){try{return new RegExp(e),!0}catch(t){return!1}}function Rh(e,t){if(!/^\d+$/.test(e))throw new q(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new q(`Invalid semver: ${t}`);return parseInt(e,10)}function oe(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new q(`Invalid semver: ${e}`);let i=r.split("."),n=(d)=>{if(d===void 0||d==="")return 0;return Rh(d,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function ke(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function jO(e){let t=oe(e),r=[t[0],t[1],t[2]],i=[t[0],t[1]+1,0];return{lower:r,upper:i}}function FO(e){let t=oe(e),[r,i,n]=t,s=[r,i,n],o;return o=r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,n+1],{lower:s,upper:o}}function TO(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(d)=>{try{return Rh(d,e)}catch{throw new q(`Invalid wildcard semver: ${e}`)}},s=n(i[0]),o,a;if(i.length===1)o=[s,0,0],a=[s+1,0,0];else{let d=n(i[1]);o=[s,d,0],a=[s,d+1,0]}return{lower:o,upper:a}}function $h(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 q(`${e} is in an invalid date format`)}throw new q(`The date provided ${e} must be a string, number, or date object`)}function kO(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let s=r.groups.interval;if(s=="h")i.setUTCHours(i.getUTCHours()-n);else if(s=="d")i.setUTCDate(i.getUTCDate()-n);else if(s=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(s=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(s!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}function AO(e,t){let r=!1;return Object.assign((i)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(i)},{_posthogErrorHandler:!0})}function Ch(e,t){globalThis.process?.on("uncaughtException",AO(e,t))}function Oh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var DO=2000;class rt{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new ml({...Pm(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Fi(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,i,n){let s={...n},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Ch(this.onException.bind(this),this.onFatalError.bind(this)),Oh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!rt.isPreviouslyCapturedError(e)){let r=await rt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),n=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(n))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(DO),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class Dl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function NO(e){return e==="v0"||e==="v1"}function jh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return NO(e)?e:"v0"}var Mi="analytics",Ui="ai";function Fh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class Fr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(Fr.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let n=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(i instanceof Error)n+=` (${i.message})`;return n}}function Nl(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 LO(e){return typeof e=="string"?e:void 0}var qO=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Nl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Nl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Nl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:LO}],MO=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function UO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function BO(e){if(typeof e=="string"){let r=new Date(e);return Number.isNaN(r.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 Th(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function GO(e){let r={...UO(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of qO)if(s in r){let d=a(r[s]);if(d!==void 0)i[o]=d;delete r[s]}let n={};for(let{property:s,field:o}of MO)if(s in r){let a=r[s];if(typeof a=="string")n[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,Th(r,"$set",e.$set),Th(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:BO(e.timestamp),...n,options:i,properties:r}}function kh(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(GO)};if(r)i.historical_migration=!0;return i}var VO="/i/v1/analytics/events",KO=30000,zO=new Set([408,500,502,503,504]);class Ll{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??KO,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>ue(i,r))),this.generateRequestId=t.generateRequestId??xe,this.compress=t.compress??Kt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=kh(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${VO}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let d=1;d<=a;d++){let u=d===a,l=Ir({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),c;try{c=await this.sendOnce(n,l,d,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(d));continue}let{status:p}=c;if(p<200||p>=300){if(!u&&zO.has(p)){let _=this.parseRetryAfter(c);await this.cancelBody(c),await this.sleep(this.backoffDelay(d,_));continue}let g=await this.buildHttpError(c,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(c)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${p} response body`))}let m=this.classify(o,f,s);if(m.length===0)return this.surfacePartialDrops(t,s);if(u)return void this.onError(new Fr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(c);await this.sleep(this.backoffDelay(d,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);if(d!==null)s=d,n["Content-Encoding"]="gzip"}let o=new AbortController,a=ue(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:n,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)i["User-Agent"]=this.config.userAgent;return i}classify(e,t,r){let i=t.results??{},n=[];for(let s of e){let o=i[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")n.push(s)}}return n}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let s=parseInt(r,10);return Number.isFinite(s)&&s>0?1000*s:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let n=i-this.now();return n>0?n:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let i=r.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let i=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,i){this.onError(new Fr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Fr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var WO=100,Ah=30000,HO=50000,JO=50,QO=500,YO="https://us.i.posthog.com",Dh=new Set;function vs(e,t){if(Dh.has(e))return;Dh.add(e),console.warn(`[PostHog] ${t}`)}function XO(e){return typeof e=="string"?e.trim():""}function ZO(e){return(typeof e=="string"?e.trim():"")||void 0}function ej(e){return(typeof e=="string"?e.trim():"")||YO}function tj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function rj(e){if(!e)return{};let t={};for(let[i,n]of Object.entries(e))t[`$feature/${i}`]=n;let r=Object.keys(e).filter((i)=>e[i]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class ql extends bs{constructor(e,t={}){let r=XO(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:ej(t.host),personalApiKey:ZO(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new Dl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=jh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,WO):Ah,typeof i.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0);if(typeof i.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0);if(!this.disabled&&i.personalApiKey){if(i.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(i.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Al({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation})}this.errorTracking=new rt(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||HO}enqueue(e,t,r){super.enqueue(e,t,r),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 s,o=new Promise((a)=>{s=a});try{e(o)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??QO,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??JO;this._waitUntilCycle.timer=ue(()=>{this.resolveWaitUntilFlush()},n)}_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"&&Fh(e)?Ui:Mi}persistedQueueKeyForRoute(e){return e===Ui?Se.AiQueue:Se.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Mi,Ui]:[Mi]}async sendBatch(e,t,r=Mi){if(this.captureMode!=="v1"||r===Ui)return super.sendBatch(e,t,r);let i=e.filter((n)=>n!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Ll({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 bh}get metrics(){if(!this._metrics)this._metrics=new ls(this,as(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,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:n,event:s,properties:o,options:a})=>{let d={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,d):this.enqueue(e,u,d)}).catch((n)=>{if(n)console.error(n)}))}_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:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let i={};if(Object.keys(t).length>0)i.$set=t;if(Object.keys(r).length>0)i.$set_once=r;this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=tj(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}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=Ah){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",(n)=>{clearTimeout(r),i(),t(n>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,r={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let n=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let E=this._flagOverrides[e];if(E===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:d,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,_,b,v,w;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let E=this.featureFlagsPoller?.featureFlagsByKey[e];if(E)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(E,c,{matchValue:i});if(x){f=!0;let T=x.value;_=E.id,v="Evaluated locally",w=E.has_experiment,p={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof tt||x instanceof q)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!f&&!a){let E=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,d,u,o,[e]);if(E===void 0)g=gt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(gt.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(gt.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(gt.FLAG_MISSING);else{_=T.metadata?.id,b=T.metadata?.version,v=T.reason?.description??T.reason?.code,w=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}p={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(n){let E=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,x={$feature_flag:e,$feature_flag_response:E,$feature_flag_id:_,$feature_flag_version:b,$feature_flag_reason:v,locally_evaluated:f,[`$feature/${e}`]:E,$feature_flag_request_id:m,$feature_flag_evaluated_at:f?Date.now():h};if(w!==void 0)x.$feature_flag_has_experiment=w;if(f&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(T!==void 0)x.$feature_flag_definitions_loaded_at=T}if(g)x.$feature_flag_error=g;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:E,groups:s,disableGeoip:o,properties:x})}if(p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)p={...p,payload:this._payloadOverrides[e]};return p}async getFeatureFlag(e,t,r){vs("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return i.variant??!0}async getFeatureFlagPayload(e,t,r,i){if(vs("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 n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(n===void 0)return;return n.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:n}=this._resolveDistinctId(t,r);if(!i)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,i,{...n,sendFeatureFlagEvents:n?.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 r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(i){}return r}async isFeatureEnabled(e,t,r){vs("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)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:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:d,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(c.distinctId,c.groups,d,u,s,o);f={...f,...g.flags||{}},m={...m,...g.payloads||{}}}if(this._flagOverrides!==void 0)f={...f,...this._flagOverrides};if(this._payloadOverrides!==void 0)m={...m,...this._payloadOverrides};return{featureFlags:f,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:d,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,o),b=new Set;if(_)for(let[w,I]of Object.entries(_.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:_.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},b.add(w)}if((_?_.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,d,u,s,o);if(w){this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt,h=Boolean(w.errorsWhileComputingFlags),g=Array.isArray(w.quotaLimited)&&w.quotaLimited.includes("feature_flags");for(let[I,E]of Object.entries(w.flags)){if(b.has(I))continue;let x;if(E.metadata?.payload!==void 0)try{x=JSON.parse(E.metadata.payload)}catch{x=E.metadata.payload}p[I]={key:I,enabled:E.enabled,variant:E.variant,payload:x,id:E.metadata?.id,version:E.metadata?.version,reason:E.reason?.description??E.reason?.code,locallyEvaluated:!1,hasExperiment:E.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[w,I]of Object.entries(this._flagOverrides)){if(I===void 0){delete p[w];continue}let E=p[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:E?.payload,id:E?.id,version:E?.version,reason:E?.reason,locallyEvaluated:E?.locallyEvaluated??!1,hasExperiment:E?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[w,I]of Object.entries(this._payloadOverrides)){let E=p[w];if(E)p[w]={...E,payload:I}}return new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:n,disableGeoip:s,flags:p,requestId:f,evaluatedAt:m,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:h,quotaLimited:g})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:n,disableGeoip:s,properties:o}=e,a=n&&Object.keys(n).length>0?`_${JSON.stringify(Object.entries(n).sort(([u],[l])=>u<l?-1:u>l?1:0))}`:"",d=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(d))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(d);else this.distinctIdHasSentFlagCalls[t]=new Set([d]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:n,disableGeoip:s})}_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:r,distinctId:i,disableGeoip:n}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((i)=>[i,!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 r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((i)=>ue(i,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}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)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let n=new AbortController;i=ue(()=>{n.abort()},this.options.requestTimeout),r.signal=n.signal}try{return await this.fetch(t,r)}catch(n){this._events.emit("error",n);return}finally{if(i)clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[n,s]of Object.entries(e))if(bm(s)&&t&&n in t){let o={};for(let[a,d]of Object.entries(s))o[String(a)]=String(d);i[String(n)]=o}else r[String(n)]=String(s);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let n=i?.personProperties||{},s=i?.groupProperties||{},o=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[u,l]of Object.entries(t||{}))d[u]=String(l);return await this.getAllFlags(e,{groups:d,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[u,l]of Object.entries(t||{}))d[u]=String(l);return await this.getAllFlags(e,{groups:d,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,n,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let n={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...i?.[o]||{}};return{allPersonProperties:n,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,n){if(!rt.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(rt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:i,flags:n},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!rt.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(rt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((s)=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:n,groups:s,flags:o,sendFeatureFlags:a,timestamp:d,disableGeoip:u,uuid:l}=e,c=this.context?.get(),p=t.includeContextProperties??!0,f=r||c?.distinctId,m=p?{...this.props,...c?.properties||{},...n||{}}:{...n||{}};if(!f)f=xe(),m.$process_person_profile=!1;if(p&&c?.sessionId&&!m.$session_id)m.$session_id=c.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?Oi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:d,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(a){vs("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 b=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,b);return rj(v)}return{}}).catch(()=>({})).then((b)=>{let v=g.groups||s;return{...b,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"){if(pm(_.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",_.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:_,options:{timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let n of r){if(i=n(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}}var Nh=require("async_hooks");class Ml{constructor(){this.storage=new Nh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function ij(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(n==="*"||n.includes(o.level)))return o;if(!o.tags)o.tags={};let d=o.tags[Lh.POSTHOG_ID_TAG];if(d===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${d}`,u).toString();o.tags["PostHog Person URL"]=l;let c=o.exception?.values||[],p=c.map((m)=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map((h)=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:c[0]?.value||o.message,$exception_type:c[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:c[0]?.value||o.message,$sentry_exception_type:c[0]?.type,$sentry_tags:o.tags};if(t&&r)f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:d,properties:f});return o}}class Lh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,n){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(ij(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ul extends ql{getLibraryId(){return"posthog-node"}initializeContext(){return new Ml}createErrorPropertiesBuilder(){return new $e.ErrorPropertiesBuilder([new $e.EventCoercer,new $e.ErrorCoercer,new $e.ObjectCoercer,new $e.StringCoercer,new $e.PrimitiveCoercer],$e.createStackParser("node:javascript",$e.nodeStackLineParser),[cm(),hh,_h()])}}var ee=require("fs/promises"),fe=require("path");var qh={name:"@toloka-platform/sdk",version:"0.1.0-preview.5",private:!1,description:"Preview. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"preview"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts",test:"vitest run",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","posthog-node":"5.46.1"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},engines:{bun:"1.4.0"}};var Mh=require("fs/promises"),Uh=require("path"),ws=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),$s=(e)=>ws(e,"ENOENT"),Tr=async(e)=>{try{return await Mh.lstat(e)}catch(t){if($s(t))return;throw t}},Bi=async(e,t,r="write")=>{let i=e;for(let n of t.split("/")){i=Uh.join(i,n);let s=await Tr(i);if(s===void 0)return;y(!s.isSymbolicLink(),`Refusing to ${r} through symbolic link ${i}.`)}};var Kh=require("crypto"),Y=require("fs/promises"),pe=require("path"),zh=require("url");var sj=(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},Gi=(e)=>{if(e instanceof re){let t=sj(e);return t===void 0?e.message:`${e.message}
|
|
56
|
+
${t}`}return e instanceof Error?e.message:String(e)};var Bl=zh.fileURLToPath(new URL("../../skills","file:///Users/gzarip/code/potato-sdk-dx/packages/sdk/src/cli/skill.ts")),Es="catalog.json",Ar=".agents/skills",kr="SKILL.md",Wh="skills",Bh=500,Gh=1048576,Hh=64,oj=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,aj=/^[a-f0-9]{64}$/u,Jh=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Vh=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),Gl=(e)=>typeof e==="string"&&e.trim().length>0,lj=(e)=>typeof e==="string"&&e.length<=Hh&&oj.test(e),cj=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),dj=(e,t)=>{y(Jh(e),t("every skill must be an object."));let{id:r,name:i,description:n,tags:s,version:o,digest:a,files:d}=e;return y(lj(r),t(`skill id ${JSON.stringify(r)} must be at most ${Hh} lowercase letters, digits, and single hyphens.`)),y(Gl(i),t(`skill ${r} needs a name.`)),y(Gl(n),t(`skill ${r} needs a description.`)),y(Vh(s),t(`skill ${r} tags must be strings.`)),y(Gl(o),t(`skill ${r} needs a version.`)),y(typeof a==="string"&&aj.test(a),t(`skill ${r} digest must be the sha256 hex digest of its files.`)),y(Vh(d)&&d.includes(kr),t(`skill ${r} files must include ${kr}.`)),y(d.every(cj),t(`skill ${r} files must be relative paths inside its directory.`)),y(new Set(d).size===d.length,t(`skill ${r} lists a file more than once.`)),{id:r,name:i,description:n,tags:s,version:o,digest:a,files:d}},uj=(e,t)=>{try{return JSON.parse(e)}catch(r){throw Error(`Invalid skill catalog ${t}: ${Gi(r)}`)}},Qh=async(e)=>{try{return(await Y.stat(e)).isFile()}catch(t){if(ws(t,"ENOENT","ENOTDIR"))return!1;throw t}},Yh=async(e)=>{let t=pe.join(e,Wh);if(await Qh(pe.join(t,Es)))return t;let r=pe.dirname(e);return r===e?void 0:Yh(r)};async function pj(e=process.argv[1]){let t=e===void 0?void 0:await Y.realpath(e),r=t===void 0?void 0:await Yh(pe.dirname(t));if(r!==void 0)return r;let i=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return y(await Qh(pe.join(Bl,Es)),`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${Wh}/${Es} in a directory above its runtime entry, but ${i}, and the source checkout catalog ${Bl} is absent. Reinstall @toloka-platform/sdk.`),Bl}var Vl=async()=>fj(await pj());async function fj(e){let t=pe.join(e,Es),r=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:i}=await Y.stat(t);y(i<=Gh,r(`the manifest is ${i} bytes; the limit is ${Gh} bytes.`));let n=uj(await Y.readFile(t,"utf8"),t);y(Jh(n)&&Array.isArray(n.skills),r("expected an object with a skills array.")),y(n.skills.length<=Bh,r(`${n.skills.length} skills exceed the limit of ${Bh}.`));let s=n.skills.map((a)=>dj(a,r)),o=new Set;for(let a of s)y(!o.has(a.id),r(`skill id ${a.id} appears more than once.`)),o.add(a.id);return{root:e,manifestPath:t,skills:s}}async function Xh(e,t){let r=Kh.createHash("sha256");for(let i of t.toSorted())r.update(i),r.update("\x00"),r.update(await Y.readFile(pe.join(e,i))),r.update("\x00");return r.digest("hex")}var mj=(e,t)=>{let r=t.trim().toLowerCase();return e.filter((i)=>[i.id,i.name,i.description,...i.tags].some((n)=>n.toLowerCase().includes(r)))};async function hj(e,t){let r=pe.join(e,Ar,t.id);if(await Tr(r)===void 0)return"not-installed";try{return await Xh(r,t.files)===t.digest?"current":"stale"}catch(i){if(ws(i,"ENOENT","ENOTDIR"))return"stale";throw i}}var Zh=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(r)=>({...r,status:await hj(e,r)}))),gj=async(e,t,r,i)=>{await e(r,i);try{await e(t,r)}catch(n){try{await e(i,r)}catch(s){throw Error(`Failed to replace ${r}; the previous version is preserved at ${i}. ${Gi(s)}`,{cause:n})}throw n}await Y.rm(i,{recursive:!0,force:!0})};async function yj({catalog:e,sourceRoot:t,skillId:r,force:i=!1,rename:n=Y.rename}){let s=e.skills.find((c)=>c.id===r);y(s,`Skill ${JSON.stringify(r)} is not in the catalog. Run \`toloka skill list\` to see the available skills.`);let o=`${Ar}/${s.id}`;await Bi(t,o);let a=pe.join(t,o),d=await Tr(a);y(d===void 0||i,`${o} already exists. Re-run with --force to replace it with the catalog version of ${s.id}.`);let u=pe.dirname(a);await Y.mkdir(u,{recursive:!0});let l=await Y.mkdtemp(pe.join(u,`.${s.id}.tmp-`));try{for(let c of s.files){let p=pe.join(l,c);await Y.mkdir(pe.dirname(p),{recursive:!0}),await Y.copyFile(pe.join(e.root,s.id,c),p)}if(y(await Xh(l,s.files)===s.digest,`Skill ${s.id} failed its digest check: the packaged files do not match the catalog digest ${s.digest}. Nothing was installed.`),d===void 0)await n(l,a);else await gj(n,l,a,`${l}.backup`)}catch(c){throw await Y.rm(l,{recursive:!0,force:!0}),c}return{skill:s,directory:a,replaced:d!==void 0}}var eg=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let r=Math.max(...e.map((n)=>n.id.length)),i=Math.max(...e.map((n)=>n.status.length));return e.flatMap((n)=>[`${n.id.padEnd(r)} ${n.status.padEnd(i)} ${n.name}`,` ${n.description}`]).join(`
|
|
57
|
+
`)};async function tg({sourceRoot:e,json:t,io:r}){let i=await Vl();r.stdout(eg(await Zh({sourceRoot:e,skills:i.skills}),t))}async function rg({sourceRoot:e,query:t,json:r,io:i}){let n=await Vl(),s=await Zh({sourceRoot:e,skills:mj(n.skills,t)});if(r||s.length>0){i.stdout(eg(s,r));return}i.stdout(`No skills match ${JSON.stringify(t)}. Run \`toloka skill list\` to see the catalog.`)}async function ig({sourceRoot:e,skillId:t,force:r,io:i}){let n=await Vl(),s=await yj({catalog:n,sourceRoot:e,skillId:t,force:r}),o=`${Ar}/${s.skill.id}`,a=s.skill.files.length;i.stdout(`${s.replaced?"Replaced":"Installed"} ${s.skill.id} in ${o} (${a} ${a===1?"file":"files"}). Start with ${o}/${kr}.`)}var Ve=qh.version,Ke="@toloka-platform/sdk",Hl="toloka-bootstrap",sg=`.claude/skills/${Hl}/SKILL.md`,og=`.cursor/rules/${Hl}.mdc`,Yt="AGENTS.md",_j=[sg,og,Yt],Dr={begin:"<toloka>",end:"</toloka>"},Kl={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},zl=/<!-- toloka:sdk-version ([^\s>]+) -->/u,ag=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),Nr=async(e)=>{try{return await ee.readFile(e,"utf8")}catch(t){if($s(t))return;throw t}},Wl=async(e)=>{try{return(await ee.lstat(e)).isDirectory()}catch(t){if($s(t))return!1;throw t}},Jl=(e)=>zl.test(e),lg=`Generated by \`${Ke}\` version \`${Ve}\`.
|
|
58
|
+
<!-- toloka:sdk-version ${Ve} -->`,bj=`${Dr.begin}
|
|
58
59
|
|
|
59
|
-
|
|
60
|
-
Use the globally installed \`toloka\` binary. Install it with \`bun add --global ${Xe}@preview\` if it is not on \`PATH\`.
|
|
60
|
+
## Toloka Agent Bootstrap
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
${lg}
|
|
63
|
+
Re-run \`toloka init\` to refresh this block. Keep your own instructions outside it.
|
|
63
64
|
|
|
64
|
-
|
|
65
|
-
name: ${hs}
|
|
66
|
-
description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka. Use when the user wants to create, adopt, inspect, plan, or apply a pipeline project as code.
|
|
67
|
-
---
|
|
65
|
+
This repository works with the Toloka platform through the \`toloka\` CLI. Before starting a Toloka task:
|
|
68
66
|
|
|
69
|
-
|
|
67
|
+
1. Run \`toloka --help\`, then \`toloka <resource> --help\` for the resource you need.
|
|
68
|
+
2. Run \`toloka skill search <query>\` to find a bundled skill for the task; \`toloka skill list\` shows every skill and whether it is installed.
|
|
69
|
+
3. Run \`toloka skill install <skill-id>\` and read \`${Ar}/<skill-id>/${kr}\` before acting; add \`--force\` to refresh a stale skill.
|
|
70
|
+
4. Follow the installed skill. When no skill matches, continue with the CLI help and never invent commands or SDK helpers.
|
|
71
|
+
5. To report a Toloka platform problem or unexpected failure to support, run \`toloka skill search report-issue\` and install \`toloka-report-issue\` before collecting evidence.
|
|
70
72
|
|
|
71
|
-
${
|
|
72
|
-
description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka
|
|
73
|
-
alwaysApply: false
|
|
74
|
-
---
|
|
73
|
+
${Dr.end}`,cg=`# Toloka Agent Bootstrap pointer
|
|
75
74
|
|
|
76
|
-
|
|
75
|
+
${lg}
|
|
77
76
|
|
|
78
|
-
|
|
79
|
-
|
|
77
|
+
Read the \`${Dr.begin}\` block in \`${Yt}\` 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 \`${Ar}/<skill-id>/${kr}\` before acting.
|
|
78
|
+
`,Pj=`---
|
|
79
|
+
name: ${Hl}
|
|
80
|
+
description: Toloka platform work with the toloka CLI and ${Ke}, such as pipeline projects, datasets, runs, secrets, and issue reporting. Use when the user mentions Toloka or the toloka CLI. Start by reading the ${Dr.begin} Agent Bootstrap block in ${Yt}, then find and install the matching skill.
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
${cg}`,vj=`---
|
|
84
|
+
description: Toloka Agent Bootstrap pointer for the toloka CLI and ${Ke}
|
|
85
|
+
alwaysApply: true
|
|
86
|
+
---
|
|
80
87
|
|
|
81
|
-
${(
|
|
82
|
-
${Ti}`,Dj=(e,t)=>{let r=e.indexOf(ms),i=e.indexOf(Ti),n=r!==-1,s=i!==-1,o=e.includes(`\r
|
|
88
|
+
${cg}`,ng=(e,t,r)=>{let i=e.indexOf(t.begin),n=e.indexOf(t.end);if(i===-1&&n===-1)return;return y(i!==-1&&n!==-1&&i<n,`Malformed Toloka block in ${r}: expected one ${t.begin} followed by one ${t.end}. Repair the file by hand, then re-run \`toloka init\`.`),y(!e.includes(t.begin,i+t.begin.length)&&!e.includes(t.end,n+t.end.length),`Multiple Toloka blocks in ${r}: keep exactly one ${t.begin} ... ${t.end} block, then re-run \`toloka init\`.`),{beginIndex:i,endIndex:n+t.end.length}},wj=(e,t)=>{let r=ng(e,Dr,t),i=ng(e,Kl,t);y(r===void 0||i===void 0,`Ambiguous Toloka blocks in ${t}: both ${Dr.begin} and ${Kl.begin} are present. Keep one, then re-run \`toloka init\`.`);let n=e.includes(`\r
|
|
83
89
|
`)?`\r
|
|
84
90
|
`:`
|
|
85
|
-
`,
|
|
86
|
-
`,o
|
|
87
|
-
`),
|
|
88
|
-
`,{mode:384}),await
|
|
89
|
-
${e.map((s)=>`${
|
|
91
|
+
`,s=bj.replaceAll(`
|
|
92
|
+
`,n),o=r??i;if(o!==void 0)return`${e.slice(0,o.beginIndex)}${s}${e.slice(o.endIndex)}`;if(e.length===0)return`${s}${n}`;let a=e.endsWith(`${n}${n}`)?"":e.endsWith(n)?n:`${n}${n}`;return`${e}${a}${s}${n}`},$j=async(e)=>{if(await Wl(fe.join(e,"node_modules",Ke)))return!0;let t=await Nr(fe.join(e,"package.json"));if(t===void 0)return!1;let r=JSON.parse(t);return y(typeof r==="object"&&r!==null,"package.json must contain a JSON object."),["dependencies","devDependencies"].some((i)=>{let n=Reflect.get(r,i);return typeof n==="object"&&n!==null&&typeof Reflect.get(n,Ke)==="string"})},Ej=async(e,t)=>{if(await Nr(e)===t)return!1;return await ee.mkdir(fe.dirname(e),{recursive:!0}),await ee.writeFile(e,t,"utf8"),!0},Ij=async(e,t)=>{let r=fe.join(e,t),i=await Nr(r);y(i===void 0||Jl(i),`Refusing to overwrite ${r}: it carries no \`<!-- toloka:sdk-version ... -->\` marker, so it is not a pointer generated by ${Ke}. Move it aside, then re-run \`toloka init\`.`)},Sj=async(e)=>(await Promise.all(ag.map(async(r)=>{let i=fe.join(e,r.file);if(await Tr(i)===void 0)return;return await Bi(e,r.file,"remove legacy agent entry point"),Jl(await ee.readFile(i,"utf8"))?r:void 0}))).filter((r)=>r!==void 0),xj=async(e,t)=>{if(await ee.rm(fe.join(e,t.file),{force:!0}),t.directory===void 0)return;let r=fe.join(e,t.directory);if((await ee.readdir(r)).length===0)await ee.rmdir(r)},Rj=(e,t,r,i)=>[`${r.length===0&&i.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${Ke} ${Ve} in ${e}:`,...t.map((n)=>` ${n}`),...i.map((n)=>` removed ${n} (replaced by the ${Yt} Agent Bootstrap)`)].join(`
|
|
93
|
+
`),Cj=async(e,t)=>{if(t===void 0)return;let r=await Ie(e);if(y(r===void 0||r.projectId===t,`This directory is already bound to ${r?.projectId}.`),r!==void 0)return;return await Gt(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function dg(e,t={}){await ee.mkdir(e,{recursive:!0});let r=await ee.realpath(e),i=fe.join(r,Yt),n=await Nr(i),s=wj(n??"",i),[o,a]=await Promise.all([Wl(fe.join(r,".claude")),Wl(fe.join(r,".cursor","rules"))]),u=[...o||!o&&!a&&n===void 0?[{relativePath:sg,source:Pj}]:[],...a?[{relativePath:og,source:vj}]:[]],l=[...u,{relativePath:Yt,source:s}];await Promise.all(l.map((b)=>Bi(r,b.relativePath))),await Promise.all(u.map((b)=>Ij(r,b.relativePath)));let c=await Sj(r),p=await Cj(r,t.projectId),f=p===void 0?[]:[p];for(let b of l)if(await Ej(fe.join(r,b.relativePath),b.source))f.push(b.relativePath);for(let b of c)await xj(r,b);let m=c.map((b)=>b.file),h=await $j(r),g=[...l.map((b)=>b.relativePath),...p===void 0?[]:[p]],_=h?void 0:`Warning: ${Ke} is not listed in dependencies or devDependencies in ${fe.join(r,"package.json")}. Run \`bun add --dev ${Ke}\` before using \`toloka\`, then re-run \`toloka init\`.`;return{targetDirectory:r,files:g,writtenFiles:f,removedFiles:m,sdkVersion:Ve,dependencyReady:h,output:Rj(r,g,f,m),..._===void 0?{}:{warning:_}}}async function ug(e){let t=[],r=new Set,i=(s,o)=>{t.push(s);let a=zl.exec(o)?.[1];if(a!==void 0)r.add(a)};for(let{file:s}of ag){let o=await Nr(fe.join(e,s));if(o!==void 0&&Jl(o))i(s,o)}for(let s of _j){let o=await Nr(fe.join(e,s));if(o===void 0)continue;let a=zl.exec(o)?.[1];if(o.includes(Kl.begin)||a!==void 0&&a!==Ve)i(s,o)}if(t.length===0)return;return`Warning: Agent instructions generated by ${r.size===0?`an earlier ${Ke} build`:`${Ke} ${[...r].toSorted().join(", ")}`} are out of date (${t.join(", ")}). The installed ${Ve} manages one Agent Bootstrap in ${Yt} plus pointer files. Re-run \`toloka init\`.`}var Oj="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",jj="https://eu.posthog.com",Fj={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0},Is=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},Tj=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};function kj(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(Tj(t))return!1;if(Is(t))return!0;if(Is(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(Is(e.CI??process.env.CI))return!1;if(Is(process.env.VITEST))return!1;return!0}var Aj={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,fields:!0,load:!0,upload:!0},secret:{set:!0},skill:{list:!0,search:!0,install:!0}},Dj={apply:!0,"auth-status":!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},Ql=(e)=>{let t=e[0];if(t===void 0)return"help";let r=Aj[t];if(r===void 0)return Dj[t]===!0?t:"unknown";let i=e[1];return i!==void 0&&r[i]===!0?`${t} ${i}`:t};function fg(e){if(e.includes("-v")||e.includes("--version"))return"version";let t=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i===void 0)continue;if(i==="--help"||i==="-h")break;if(i.startsWith("-")){if(Fj[i]===!0)r+=1;continue}t.push(i)}return Ql(t)}function Nj(e){if(e===void 0)return{error_code:"command_failed"};if(e instanceof re||e instanceof or)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var Lj=(e)=>Ss.join(Ss.dirname(Ge(e)),"anonymous-id"),qj=async(e)=>{let t=Lj(e);await ll(t);try{let i=(await Xt.readFile(t,"utf8")).trim();if(i.length>0)return await Xt.chmod(t,384),i}catch(i){if(!(i instanceof Error&&("code"in i)&&i.code==="ENOENT"))throw i}let r=pg.randomUUID();return await Xt.writeFile(t,`${r}
|
|
94
|
+
`,{mode:384}),await Xt.chmod(t,384),r},Mj=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){y(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.")},async shutdown(){}});function mg(e){let{environment:t}=e;if(e.client===void 0&&!kj(t))return Mj();let{client:r,distinctId:i}=e,n,s=[],o=(l)=>{s.push(l)};r?.on?.("error",o);let a=async()=>{if(r!==void 0&&i!==void 0)return;if(r===void 0){let l=new Ul(Oj,{host:jj,flushAt:1,flushInterval:0});l.on("error",o),r=l}i??=await qj(t)},d=()=>({sdk_version:Ve,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),u=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(l){u=u.then(()=>{if(r===void 0||i===void 0)return;if(n===l.id)return;if(n=l.id,i!==l.id)r.alias({distinctId:l.id,alias:i});i=l.id}).catch(()=>{})},captureCommand(l){u=u.then(()=>{if(r===void 0||i===void 0)return;let c=d();if(l.outcome==="failed"){let p=Nj(l.error);r.capture({distinctId:i,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...c,command:Ql(l.command.split(" ")),duration_ms:l.durationMs,exit_code:l.exitCode,...p}});return}r.capture({distinctId:i,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...c,command:Ql(l.command.split(" ")),duration_ms:l.durationMs,exit_code:l.exitCode,outcome:l.outcome}})}).catch(()=>{})},submitIssueReport(l){let c=u.then(async()=>{y(r&&i,"PostHog issue reporting could not be initialized."),s.length=0,r.capture({distinctId:i,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...d(),report_id:l.reportId,report_text:l.reportText,report_length_bytes:new TextEncoder().encode(l.reportText).length,authored_by:l.authoredBy,platform:l.platform,$process_person_profile:!1}}),await r.flush();let p=s[0];if(s.length=0,p!==void 0)throw p});return u=c.catch(()=>{}),c},async shutdown(){try{await u,await r?.shutdown(2000)}catch{}}}}var Br=require("fs/promises"),Ur=require("path");var _g=Symbol("sourceReference"),bg={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},Uj={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 Ft(e,t){return e<t?-1:e>t?1:0}function hg(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Pg(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function vg(e,t){let[r,...i]=Pg(e),s=`${(r??t).toLowerCase()}${i.map((a)=>`${a.slice(0,1).toUpperCase()}${a.slice(1).toLowerCase()}`).join("")}`,o=/^\d/.test(s)?`_${s}`:s;return Object.hasOwn(Uj,o)?`${o}Value`:o}function Bj(e,t){return Pg(e).map((r)=>r.toLowerCase()).join("-")||t}function Yl(e,t,r){let i=new Map,n=new Set;for(let d of e){y(!n.has(d.key),`Naming key "${d.key}" is duplicated`),n.add(d.key);let u=t(d),l=i.get(u)??[];l.push(d),i.set(u,l)}let s=new Set(i.keys()),o=new Set,a=new Map;for(let[d,u]of[...i.entries()].toSorted(([l],[c])=>Ft(l,c))){let l=u.toSorted((c,p)=>Ft(c.key,p.key));for(let c of l){let p=d;if(l.length>1||r!==void 0&&Object.hasOwn(r,p))p=`${d}_${hg(c.key)}`;let f=2;while(o.has(p)||r!==void 0&&Object.hasOwn(r,p)||p!==d&&s.has(p))p=`${d}_${hg(c.key)}_${f}`,f+=1;o.add(p),a.set(c.key,p)}}return a}function Gj(e){return typeof e==="object"&&e!==null&&_g in e}function te(e){return" ".repeat(e)}function Ae(e,t=0){if(Gj(e))return e.name;if(y(e!==void 0,"Cannot emit an undefined source value"),typeof e==="number")y(Number.isFinite(e),"Cannot emit a non-finite number");if(e===null||typeof e!=="object"){let n=JSON.stringify(e);return y(n!==void 0,`Cannot emit a ${typeof e} source value`),n}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
|
|
95
|
+
${e.map((s)=>`${te(t+1)}${Ae(s,t+1)}`).join(`,
|
|
90
96
|
`)}
|
|
91
|
-
${
|
|
92
|
-
${r.map(([n,s])=>{let o=n==="__proto__"?`[${JSON.stringify(n)}]`:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?n:JSON.stringify(n);return`${
|
|
97
|
+
${te(t)}]`}let r=Object.entries(e).filter(([,n])=>n!==void 0).toSorted(([n],[s])=>Ft(n,s));if(r.length===0)return"{}";return`{
|
|
98
|
+
${r.map(([n,s])=>{let o=n==="__proto__"?`[${JSON.stringify(n)}]`:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?n:JSON.stringify(n);return`${te(t+1)}${o}: ${Ae(s,t+1)}`}).join(`,
|
|
93
99
|
`)}
|
|
94
|
-
${
|
|
100
|
+
${te(t)}}`}function Vi(e,t){return{field:t(e.id),optional:e.optional}}function xs(e,t){let{fieldProxyId:r,relations:i,...n}=e;return{...n,field:t(r),...i===void 0?{}:{relations:i.map(({id:s,...o})=>({...o,field:t(s)}))}}}function Xl(e,t){let{targetEntity:r,...i}=e;return{...i,targetEntity:t(r)}}function gg(e,t){return{...e,gradedEntities:e.gradedEntities.map((r)=>Xl(r,t))}}function Vj(e,t){switch(e.type){case"root":{let{datasetId:r,itemFilter:i,startedFieldProxies:n,completedFieldProxies:s,...o}=e.settings;return{...o,started:n.output.map((a)=>Vi(a,t)),completed:s.input.map((a)=>Vi(a,t))}}case"code":{let{fieldProxies:r,...i}=e.settings;return{...i,fieldProxies:{input:r.input.map((n)=>Vi(n,t)),output:r.output.map((n)=>Vi(n,t))}}}case"generation":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>xs(o,t)),output:r.output.map((o)=>xs(o,t))},qualityCriteria:i.map((o)=>Xl(o,t)),...n===void 0?{}:{exam:gg(n,t)}}}case"match":{let{conditions:r,fieldProxies:i,...n}=e.settings;return{...n,conditions:r.map(({predicates:s,...o})=>({...o,predicates:s.map(({fieldProxyId:a,...d})=>({...d,field:t(a)}))})),fieldProxies:{input:i.input.map((s)=>Vi(s,t))}}}case"quorum":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>xs(o,t)),output:r.output.map((o)=>xs(o,t))},qualityCriteria:i.map((o)=>Xl(o,t)),...n===void 0?{}:{exam:gg(n,t)}}}}}function Kj(e,t,r,i){let n=new Set,o=Vj(e,(l)=>{let c=i.get(l);return y(c,`Node "${e.id}" references unknown field "${l}"`),n.add(c),{name:c,[_g]:!0}}),a=[...n].toSorted(Ft),d=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],u=e.type==="root"?[`${te(1)}${Ae(o,1)}`,`${te(1)}${Ae({id:e.id},1)}`]:[`${te(1)}${Ae(e.settings.about.name,1)}`,`${te(1)}${Ae(o,1)}`,`${te(1)}${Ae({id:e.id},1)}`];return{binding:t,path:r,source:`${d.join(`
|
|
95
101
|
`)}
|
|
96
102
|
|
|
97
103
|
export const ${t} = ${e.type}(
|
|
98
104
|
${u.join(`,
|
|
99
105
|
`)}
|
|
100
106
|
);
|
|
101
|
-
`}}function
|
|
107
|
+
`}}function wg(e,t){if(e.length===0)return`export {};
|
|
102
108
|
`;return`import { field } from '@toloka-platform/sdk';
|
|
103
109
|
|
|
104
|
-
${e.map((i)=>{let n=t(i),s=[`${
|
|
110
|
+
${e.map((i)=>{let n=t(i),s=[`${te(1)}${Ae(i.name,1)}`,`${te(1)}${Ae(i.jsonSchema,1)}`,...i.options===void 0?[]:[`${te(1)}${Ae(i.options,1)}`]];return{binding:n,source:`export const ${n} = field(
|
|
105
111
|
${s.join(`,
|
|
106
112
|
`)}
|
|
107
|
-
);`}}).toSorted((i,n)=>
|
|
113
|
+
);`}}).toSorted((i,n)=>Ft(i.binding,n.binding)).map(({source:i})=>i).join(`
|
|
108
114
|
|
|
109
115
|
`)}
|
|
110
|
-
`}function
|
|
111
|
-
${
|
|
112
|
-
${
|
|
113
|
-
${
|
|
114
|
-
${
|
|
115
|
-
${
|
|
116
|
+
`}function $g(e){let t=new Map(e.map((i)=>[i,`field:${i.options?.id??i.name}`])),r=Yl(e.map((i)=>({key:t.get(i)??"",name:i.name,fallback:"field"})),({name:i,fallback:n})=>vg(i,n),bg);return wg(e,(i)=>{let n=t.get(i);y(n,`Field "${i.name}" has no source key`);let s=r.get(n);return y(s,`Field "${i.name}" has no source binding`),s})}function zj(e,t){return wg(e.fields.map((r)=>({name:r.name,jsonSchema:r.jsonSchema,options:{id:r.id}})),(r)=>{let i=r.options?.id;y(i,`Field "${r.name}" has no source ID`);let n=t.get(i);return y(n,`Field "${i}" has no source binding`),n})}function yg(e,t,r,i){let n=r.get(e.node);y(n,`Connection references unknown node "${e.node}"`);let s=i.get(n.id);switch(y(s,`Node "${n.id}" has no source binding`),n.type){case"root":return y(e.handle===(t==="output"?"started":"completed"),`Root ${t} handle "${e.handle}" cannot be authored`),`${s}.${t==="output"?"started":"completed"}`;case"code":case"generation":case"quorum":return y(e.handle===t,`${n.type} ${t} handle "${e.handle}" cannot be authored`),`${s}.${t}`;case"match":if(t==="input")return y(e.handle==="input",`Match input handle "${e.handle}" cannot be authored`),`${s}.input`;if(e.handle==="default")return`${s}.default`;let o=/^matched_(\d+)$/.exec(e.handle);y(o,`Match output handle "${e.handle}" cannot be authored`);let a=o[1];return y(a!==void 0,`Match output handle "${e.handle}" has no index`),y(String(Number(a))===a,`Match output handle "${e.handle}" is not canonical`),`${s}.matched(${a})`}}function Wj(e,t,r,i,n){let s=new Map(e.nodes.map((c)=>[c.id,c])),o=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...i.values()].toSorted(Ft).join(", ")} } from './fields';`],...r.toSorted((c,p)=>Ft(c.path,p.path)).flatMap(({binding:c,path:p})=>[`import { ${c} } from './${p.slice(0,-3)}';`])],a=e.fields.map(({id:c})=>{let p=i.get(c);return y(p,`Field "${c}" has no source binding`),p}),d=e.nodes.map(({id:c})=>{let p=n.get(c);return y(p,`Node "${c}" has no source binding`),p}),u=e.connections.map((c)=>{let p=yg(c.from,"output",s,n),f=yg(c.to,"input",s,n);if(Object.keys(c.settings).length===0)return`connect(${p}, ${f})`;return`connect(
|
|
117
|
+
${te(3)}${p},
|
|
118
|
+
${te(3)}${f},
|
|
119
|
+
${te(3)}${Ae(c.settings,3)}
|
|
120
|
+
${te(2)})`}),l=(c,p)=>{if(c.length===0)return"[]";return`[
|
|
121
|
+
${c.map((f)=>`${te(p+1)}${f}`).join(`,
|
|
116
122
|
`)}
|
|
117
|
-
${
|
|
123
|
+
${te(p)}]`};return`${o.join(`
|
|
118
124
|
`)}
|
|
119
125
|
|
|
120
126
|
export default definePipeline({
|
|
121
|
-
dataset: ${
|
|
127
|
+
dataset: ${Ae(t)},
|
|
122
128
|
fields: ${l(a,1)},
|
|
123
|
-
nodes: ${l(
|
|
129
|
+
nodes: ${l(d,1)},
|
|
124
130
|
connections: ${l(u,1)}
|
|
125
131
|
});
|
|
126
|
-
`}function Kh(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((u)=>({key:`field:${u.id}`,name:u.name,fallback:"field"})),...e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type}))],i=Dl(r,({name:u,fallback:l})=>Bh(u,l),Mh),n=Dl(e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type})),({name:u,fallback:l})=>tF(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return _(l,`Field "${u.id}" has no allocated binding`),[u.id,l]})),o=new Map(e.nodes.map((u)=>{let l=i.get(`node:${u.id}`);return _(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),d=n.get(`node:${u.id}`);return _(l&&d,`Node "${u.id}" has no allocated source name`),nF(u,l,`nodes/${d}/node.ts`,s)}),c=[{path:"fields.ts",source:sF(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:oF(e,t.dataset,a,s,o)}].toSorted((u,l)=>xt(u.path,l.path));return Object.fromEntries(c.map(({path:u,source:l})=>[u,l]))}var dt=require("fs/promises"),Wt=require("path");var pg=xe(Ja(),1),fg=xe(cg(),1);var dg={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"}},required:["audienceType"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var mg=new pg.default({strict:!1});fg.default(mg);var ug=mg.compile(dg),qF=(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 Wl(e){if(ug(e))return;let t=ug.errors;_(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=qF(n),o=`${s.path}
|
|
127
|
-
${s.reason}`;if(r.has(o))continue;r.add(o),i.push(s)}throw
|
|
128
|
-
`)},
|
|
129
|
-
`)}}async function
|
|
130
|
-
`)}}var
|
|
131
|
-
`)},
|
|
132
|
-
Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";
|
|
133
|
-
${g}`,...
|
|
134
|
-
`)}}var
|
|
132
|
+
`}function Eg(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((u)=>({key:`field:${u.id}`,name:u.name,fallback:"field"})),...e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type}))],i=Yl(r,({name:u,fallback:l})=>vg(u,l),bg),n=Yl(e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type})),({name:u,fallback:l})=>Bj(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return y(l,`Field "${u.id}" has no allocated binding`),[u.id,l]})),o=new Map(e.nodes.map((u)=>{let l=i.get(`node:${u.id}`);return y(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),c=n.get(`node:${u.id}`);return y(l&&c,`Node "${u.id}" has no allocated source name`),Kj(u,l,`nodes/${c}/node.ts`,s)}),d=[{path:"fields.ts",source:zj(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:Wj(e,t.dataset,a,s,o)}].toSorted((u,l)=>Ft(u.path,l.path));return Object.fromEntries(d.map(({path:u,source:l})=>[u,l]))}var yt=require("fs/promises"),Zt=require("path");var Kg=Ce(nl(),1),zg=Ce(Bg(),1);var Gg={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var Wg=new Kg.default({strict:!1});zg.default(Wg);var Vg=Wg.compile(Gg),SF=(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 lc(e){if(Vg(e))return;let t=Vg.errors;y(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=SF(n),o=`${s.path}
|
|
133
|
+
${s.reason}`;if(r.has(o))continue;r.add(o),i.push(s)}throw or.fromIssues(i)}var xF=Symbol("fieldDefinition"),RF=Symbol.for("@toloka-platform/sdk/pipeline-definition"),Jg=Symbol("portDefinition"),CF=Symbol("nodeFieldReferences");function Qg(e,t){return{node:e,handle:t,direction:"input",[Jg]:"input"}}function Yg(e,t){return{node:e,handle:t,direction:"output",[Jg]:"output"}}function Xg(e){return typeof e==="object"&&e!==null&&xF in e}function cc(e,t){if(Xg(e)){t.push(e);return}if(Array.isArray(e)){for(let r of e)cc(r,t);return}if(typeof e==="object"&&e!==null)for(let r of Object.values(e))cc(r,t)}function OF(e){let t=[];return cc(e,t),t}function Hg(e){return Xg(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function jF(e,t={}){let r=t.id??"root",{started:i,completed:n,...s}=e;return{id:r,type:"root",settings:{...s,startedFieldProxies:{output:i.map(Hg)},completedFieldProxies:{input:n.map(Hg)}},started:Yg(r,"started"),completed:Qg(r,"completed"),[CF]:OF(e)}}var tU=Object.assign(jF,{started:Yg("root","started"),completed:Qg("root","completed")});function FF(e){return typeof e==="object"&&e!==null&&RF in e}function Os(e){y(FF(e),"Invalid pipeline definition: expected a value returned by definePipeline"),y(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;y(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),y(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}lc(e.graph)}function Wi(e,t){let r={version:e.graph.version,fields:e.graph.fields.map((i)=>({...i})),nodes:e.graph.nodes.map((i)=>i.type==="root"?{...i,settings:{...i.settings,datasetId:t.datasetId}}:i),connections:e.graph.connections.map((i)=>({from:{...i.from},to:{...i.to},settings:{...i.settings}}))};return lc(r),r}function Zg(e){let t=new Set;for(let r of e.nodes){if(r.type!=="code")continue;for(let i of r.settings.envVars??[])if(i.type==="secret")t.add(i.secretName)}return[...t].toSorted((r,i)=>r.localeCompare(i))}var Hi=require("fs/promises"),_e=require("path"),ey=require("url");var ty=async(e)=>{let t;try{t=await Hi.readdir(e,{withFileTypes:!0})}catch(i){if(i instanceof Error&&Reflect.get(i,"code")==="ENOENT")return[];throw i}let r=[];for(let i of t.toSorted((n,s)=>n.name.localeCompare(s.name))){let n=_e.join(e,i.name);if(i.isDirectory())r.push(...await ty(n));else if(i.isFile()&&i.name==="pipeline.ts")r.push(n)}return r},TF="toloka.json",kF=async(e)=>{try{return(await Hi.stat(_e.join(e,TF))).isFile()}catch{return!1}};async function ry(e){let t=_e.resolve(e);for(;;){if(await kF(t))return t;let r=_e.dirname(t);if(r===t)return;t=r}}async function js(e){let t=await ty(_e.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(i)=>{let n=await Hi.stat(i),s=ey.pathToFileURL(i);s.searchParams.set("version",`${n.mtimeMs}-${n.size}`);let o=await import(s.href);y(typeof o==="object"&&o!==null,`Invalid ${i}: expected a module`);let a=Reflect.get(o,"default");Os(a);let d=_e.relative(e,_e.dirname(i)).split(_e.sep).join("/");return{sourceDirectory:d,name:_e.basename(d),definition:a}}))).toSorted((i,n)=>i.sourceDirectory.localeCompare(n.sourceDirectory))}}var AF=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,uc=(e)=>{if(Array.isArray(e))return e.map(uc);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,uc(r)]))},Ee=(e)=>JSON.stringify(uc(e)),iy=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),sy=(e,t)=>{if(!iy(e)||!iy(t))return t;return Object.fromEntries(Object.keys(e).map((r)=>[r,sy(e[r],t[r])]))},DF=(e,t)=>Ee(e)===Ee(sy(e,t)),Ji=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},pc=(e)=>{let t=Reflect.get(e.settings,"about");if(typeof t==="object"&&t!==null){let r=Reflect.get(t,"name");if(typeof r==="string"&&r.length>0)return`${r} (${e.id})`}return e.id},NF=(e)=>`${e.name} (${e.id})`,LF=(e,t)=>{let r=t.get(e.from.node),i=t.get(e.to.node),n=r===void 0?e.from.node:pc(r),s=i===void 0?e.to.node:pc(i);return`${n}.${e.from.handle} -> ${s}.${e.to.handle}`},Fs=(e)=>new Map(e.map((t)=>[t.id,t])),dc=(e,t,r,i)=>{let n=[];for(let[s,o]of[...e].toSorted(([a],[d])=>a.localeCompare(d))){let a=t.get(s);if(a===void 0)n.push(i(o,"added"));else if(!r(o,a))n.push(i(o,"changed"))}for(let[s,o]of[...t].toSorted(([a],[d])=>a.localeCompare(d)))if(!e.has(s))n.push(i(o,"removed"));return n};function qF(e,t){let r=Fs(e.nodes),i=Fs(t.nodes),n=new Map(e.connections.map((o)=>[Ee(o),o])),s=new Map(t.connections.map((o)=>[Ee(o),o]));return[...dc(Fs(e.fields),Fs(t.fields),(o,a)=>Ee(o)===Ee(a),(o,a)=>({kind:"field",action:a,label:NF(o),id:o.id})),...dc(r,i,DF,(o,a)=>({kind:"node",action:a,label:pc(o),id:o.id})),...dc(n,s,()=>!0,(o,a)=>({kind:"connection",action:a,label:LF(o,a==="removed"?i:r)})),...Ee(e.layout)===Ee(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var fc=(e,t)=>{let r=t.nodes.find((n)=>n.type==="root"),i=r===void 0?{}:{...r.settings.itemFilter===void 0?{}:{itemFilter:r.settings.itemFilter},...r.settings.itemLimit===void 0?{}:{itemLimit:r.settings.itemLimit}};return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((n)=>n.type==="root"?{...n,settings:{...i,...n.settings}}:n)}},Ts=(e)=>{let t=new Map;for(let r of e.pipelines){let i=t.get(r.definition.dataset);if(i===void 0)i=new Map,t.set(r.definition.dataset,i);for(let n of r.definition.graph.fields){let s=i.get(n.name);if(y(s===void 0||Ee(s.jsonSchema)===Ee(n.jsonSchema),`Dataset "${r.definition.dataset}" has conflicting schemas for field "${n.name}".`),s===void 0)i.set(n.name,n)}}return[...t].toSorted(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({name:r,fields:[...i.values()].toSorted((n,s)=>n.name.localeCompare(s.name))}))},MF=(e)=>{let t=new Set;for(let r of e.pipelines)y(AF.test(r.sourceDirectory),`Invalid pipeline source directory ${r.sourceDirectory}`),y(!t.has(r.sourceDirectory),`Pipeline source directory ${r.sourceDirectory} is declared more than once`),t.add(r.sourceDirectory),Os(r.definition);Ts(e)},UF=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.datasetId);if(i!==void 0)return y(i.name===e,`Dataset ${i.id} is bound as "${e}" but is named "${i.name}".`),i;let n=r.filter((s)=>s.name===e);return y(n.length<=1,`Project has multiple datasets named "${e}".`),n[0]},BF=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.pipelineId);if(i!==void 0)return i;let n=r.filter((s)=>s.name===e.name);return y(n.length<=1,`Project has multiple pipelines named "${e.name}".`),n[0]},GF=(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}`}},VF=(e,t)=>{if(e.length===0)return"No changes.";let r=e.length===1?"change":"changes",i=[`Plan: ${e.length} ${r}`,...e.map(GF)];if(t.length>0){i.push("","Required secrets are missing:");for(let n of t)i.push(` ${n}`);i.push("Run `toloka secret set <name>` before apply.")}return i.join(`
|
|
134
|
+
`)},KF=async(e,t,r,i)=>{let n=t.map((o)=>({desired:o,dataset:UF(o.name,r?.datasets[o.name],i)})),s=await Promise.all(n.map(async({dataset:o})=>o===void 0?[]:Ji(e.datasets.listAllFields({datasetId:o.id}))));return n.map(({desired:o,dataset:a},d)=>{let u=s[d]??[],l=new Map(u.map((c)=>[c.name,c]));return{...o,...a===void 0?{}:{dataset:a},liveFields:u,missingFields:o.fields.filter((c)=>!l.has(c.name)),conflictingFields:o.fields.filter((c)=>{let p=l.get(c.name);return p!==void 0&&Ee(p.jsonSchema)!==Ee(c.jsonSchema)})}})},zF=async(e,t,r,i,n)=>{let s=t.pipelines.map((a)=>({source:a,pipeline:BF(a,r?.pipelines[a.sourceDirectory],n)})),o=await Promise.all(s.map(async({pipeline:a})=>a===void 0?void 0:e.pipelines.getGraph({pipelineId:a.id})));return s.map(({source:a,pipeline:d},u)=>{let l=o[u],c=i.find((f)=>f.name===a.definition.dataset)?.dataset,p=[];if(d!==void 0&&l!==void 0)p=c===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:qF(fc(Wi(a.definition,{datasetId:c.id}),l.graph),l.graph);return{source:a,...d===void 0?{}:{pipeline:d},...l===void 0?{}:{snapshot:l},graphChanges:p}})},WF=(e,t,r,i,n)=>{let s=[];for(let o of n)s.push({kind:"pipeline",action:"removed",label:o});for(let o of i)s.push({kind:"dataset",action:"removed",label:o});for(let o of e){if(o.dataset===void 0)s.push({kind:"dataset",action:"added",label:o.name});for(let a of o.missingFields)s.push({kind:"datasetField",action:"added",label:a.name,dataset:o.name});for(let a of o.conflictingFields)s.push({kind:"datasetField",action:"changed",label:a.name,dataset:o.name})}for(let o of t)if(o.pipeline===void 0)s.push({kind:"pipeline",action:"added",label:o.source.sourceDirectory});else for(let a of o.graphChanges)s.push({...a,pipeline:o.source.sourceDirectory});for(let o of r)s.push({kind:"secret",action:"missing",label:o});return s},ks=async(e,t)=>{let r=t.source??await js(t.sourceRoot);MF(r);let i=await Ie(t.sourceRoot),n=t.projectId??i?.projectId;y(n,de);let s=i?.projectId===n?i:void 0,o=new Set(r.pipelines.flatMap(({definition:b})=>Zg(b.graph))),a=t.listAllSecrets===!0||o.size>0,[d,u,l]=await Promise.all([Ji(e.pipelines.listAll({projectId:n})),Ji(e.datasets.listAll({projectId:n})),a?e.secrets.list({projectId:n}):Promise.resolve([])]),c=Ts(r),p=Object.keys(s?.datasets??{}).filter((b)=>!c.some((v)=>v.name===b)).toSorted(),f=Object.keys(s?.pipelines??{}).filter((b)=>!r.pipelines.some((v)=>v.sourceDirectory===b)).toSorted(),m=await KF(e,c,s,u),h=await zF(e,r,s,m,d),g=new Set(l.map((b)=>b.name)),_=[...o].filter((b)=>!g.has(b)).toSorted();return{projectId:n,source:r,state:i,datasets:m,pipelines:h,livePipelines:d,liveDatasets:u,liveSecrets:l,changes:WF(m,h,_,p,f),missingSecrets:_,removedDatasets:p,removedPipelines:f}},ny=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",HF=(e)=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},JF=(e)=>{let t=Map.groupBy(e,(r)=>ny(r.name));return new Map(e.map((r)=>{let i=ny(r.name),n=(t.get(i)?.length??0)>1;return[r.id,`pipelines/${n?`${i}-${HF(r.id)}`:i}`]}))};async function oy(e,t){let r=(await Ji(e.pipelines.listAll({projectId:t.projectId}))).toSorted((b,v)=>b.name.localeCompare(v.name)||b.id.localeCompare(v.id)),i=await Promise.all(r.map((b)=>e.pipelines.getGraph({pipelineId:b.id}))),n=new Set;for(let b of i){let v=b.graph.nodes.find((w)=>w.type==="root");y(v?.settings.datasetId,"Every imported pipeline must have a bound dataset."),n.add(v.settings.datasetId)}let s=await Ji(e.datasets.listAll({projectId:t.projectId})),o=[];for(let b of[...n].toSorted()){let v=s.find((w)=>w.id===b);y(v,`Project ${t.projectId} has no dataset ${b}.`),o.push(v)}let a=new Map(o.map((b)=>[b.id,b])),d=JF(r),u={},l={},c={};for(let[b,v]of r.entries()){let w=i[b];y(w,`Pipeline ${v.id} has no graph snapshot.`);let I=w.graph.nodes.find((R)=>R.type==="root");y(I?.settings.datasetId,`Pipeline ${v.id} has no dataset binding.`);let E=a.get(I.settings.datasetId);y(E,`Pipeline ${v.id} references unknown dataset ${I.settings.datasetId}.`);let x=c[E.name];y(x===void 0||x.datasetId===E.id,`Project has multiple referenced datasets named "${E.name}".`),c[E.name]={datasetId:E.id};let T=d.get(v.id);y(T,`Pipeline ${v.id} has no source directory.`),l[T]={pipelineId:v.id};for(let[R,V]of Object.entries(Eg(w.graph,{dataset:E.name})))u[`${T}/${R}`]=V}await yt.mkdir(t.sourceRoot,{recursive:!0});let p=Zt.join(t.sourceRoot,"pipelines"),f=!1;try{f=(await yt.stat(p)).isDirectory()}catch(b){if(!(b instanceof Error)||!("code"in b)||b.code!=="ENOENT")throw b}if(y(!f||t.force===!0,`Folder already exists: ${p}. Pass --force to replace it.`),f)await yt.rm(p,{recursive:!0,force:!0});for(let[b,v]of Object.entries(u).toSorted(([w],[I])=>w.localeCompare(I))){let w=Zt.join(t.sourceRoot,b);await yt.mkdir(Zt.dirname(w),{recursive:!0}),await yt.writeFile(w,v,"utf8")}let m={projectId:t.projectId,pipelines:l,datasets:c};await Gt(t.sourceRoot,m);let h=[...Object.keys(u),Kn].toSorted(),g=r.length===1?"pipeline":"pipelines",_=o.length===1?"dataset":"datasets";return{state:m,files:h,output:`Imported project ${t.projectId} with ${r.length} ${g} and ${o.length} ${_} into ${Zt.resolve(t.sourceRoot)}.`}}async function ay(e,t){let r=await ks(e,t);return{projectId:r.projectId,changes:r.changes,missingSecrets:r.missingSecrets,output:VF(r.changes,r.missingSecrets)}}async function ly(e,t){let r=t.projectId;y(r,de);let i=await e.projects.get({projectId:r}),n=await ks(e,{...t,listAllSecrets:!0}),s=n.changes.length,o=s===0?"Source has no pending changes.":`Source has ${s} pending change${s===1?"":"s"}.`;return{projectId:r,output:[`Project: ${r} (${i.name})`,`Team: ${i.teamId}`,`Pipelines: ${n.livePipelines.length}`,`Datasets: ${n.liveDatasets.length}`,`Secrets: ${n.liveSecrets.length}`,o].join(`
|
|
135
|
+
`)}}async function cy(e,t){let r=await ks(e,t);y(r.removedPipelines.length===0,`Refusing to delete pipelines absent from source: ${r.removedPipelines.join(", ")}.`),y(r.removedDatasets.length===0,`Refusing to delete datasets absent from source: ${r.removedDatasets.join(", ")}. Dataset items are never deleted.`),y(r.missingSecrets.length===0,`Required secrets are missing: ${r.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`);let i=r.datasets.flatMap((l)=>l.conflictingFields.map((c)=>`${l.name}.${c.name}`));y(i.length===0,`Dataset field schemas conflict with source: ${i.join(", ")}. Existing fields are never rewritten.`);let n=0,s=new Map;for(let l of r.datasets){let c=l.dataset;if(c===void 0)c=await e.datasets.create({projectId:r.projectId,name:l.name}),n+=1;if(s.set(l.name,c.id),l.missingFields.length>0)await e.datasets.createFields({datasetId:c.id,fields:l.missingFields.map((p)=>({name:p.name,jsonSchema:p.jsonSchema}))}),n+=l.missingFields.length}let o=new Map;for(let l of r.pipelines){let c=s.get(l.source.definition.dataset);y(c,`Dataset ${l.source.definition.dataset} has no resolved ID.`);let p=Wi(l.source.definition,{datasetId:c});if(l.pipeline===void 0){let m=await e.pipelines.import({projectId:r.projectId,name:l.source.name,graph:p});await e.pipelines.attachDataset({pipelineId:m.id,datasetId:c}),o.set(l.source.sourceDirectory,m.id),n+=2;continue}if(o.set(l.source.sourceDirectory,l.pipeline.id),l.graphChanges.length===0)continue;let f=l.snapshot;y(f,`Pipeline ${l.pipeline.id} has no graph snapshot.`),await e.pipelines.replaceGraph({pipelineId:l.pipeline.id,graph:fc(p,f.graph),expectedVersion:f.version}),n+=1}let a={projectId:r.projectId,pipelines:Object.fromEntries(r.source.pipelines.map((l)=>{let c=o.get(l.sourceDirectory);return y(c,`Pipeline ${l.sourceDirectory} has no resolved ID.`),[l.sourceDirectory,{pipelineId:c}]})),datasets:Object.fromEntries(r.datasets.map((l)=>{let c=s.get(l.name);return y(c,`Dataset ${l.name} has no resolved ID.`),[l.name,{datasetId:c}]}))};if(Ee(r.state)!==Ee(a))await Gt(t.sourceRoot,a);let d=n===0?"unchanged":"changed",u=n===0?"No changes.":`Applied ${n} ${n===1?"write":"writes"} to project ${r.projectId}.`;return{action:d,state:a,changes:r.changes,writes:n,output:u}}var QF=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),YF=(e)=>e.issues.map((t)=>{let r=QF(t);return` ${t.severity} ${t.code}${r.length===0?"":` ${r}`}: ${t.message}`});async function dy(e,t){let r=await ks(e,t),i=[];for(let o of r.pipelines){let a=r.datasets.find((l)=>l.name===o.source.definition.dataset)?.dataset;if(o.pipeline===void 0){i.push({sourceDirectory:o.source.sourceDirectory,skipped:"pipeline is not on the platform yet; run toloka apply first"});continue}if(a===void 0){i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,skipped:`dataset "${o.source.definition.dataset}" is not on the platform yet; run toloka apply first`});continue}let d=o.snapshot===void 0?Wi(o.source.definition,{datasetId:a.id}):fc(Wi(o.source.definition,{datasetId:a.id}),o.snapshot.graph),u=await e.pipelines.validateGraph({pipelineId:o.pipeline.id,graph:d});i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,report:u})}let n=i.every((o)=>o.report?.valid!==!1),s=i.flatMap((o)=>{if(o.skipped!==void 0)return[`- ${o.sourceDirectory}: skipped (${o.skipped})`];return y(o.report,`Pipeline ${o.sourceDirectory} is missing a validation report`),[o.report.valid?`- ${o.sourceDirectory}: valid`:`- ${o.sourceDirectory}: invalid`,...YF(o.report)]});return{projectId:r.projectId,results:i,valid:n,output:s.length===0?"No pipelines to validate.":s.join(`
|
|
136
|
+
`)}}var py="uploaded",XF=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ZF=(e)=>XF.test(e)?e.toLowerCase():void 0,hc=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),mc=(e)=>{if(!hc(e))return"unknown";if(Array.isArray(e.anyOf)){let i=[...new Set(e.anyOf.map(mc))];return i.length===0?"unknown":i.join(" | ")}let t=e.type,r=typeof t==="string"?[t]:Array.isArray(t)?t.filter((i)=>typeof i==="string"):[];if(r.length===0)return"unknown";return r.map((i)=>{if(i!=="array")return i;let n=mc(e.items);return n==="unknown"?"array":`array<${n}>`}).join(" | ")},eT=(e)=>{if(e.length===0)return"No inferred fields are available yet.";return["Inferred fields:",...e.toSorted((t,r)=>t.jsonPath.localeCompare(r.jsonPath)).map((t)=>`${" ".repeat(t.depth)}- ${t.jsonPath}: ${mc(t.jsonSchema)}`)].join(`
|
|
137
|
+
`)},fy=async(e)=>{let t=e.source??await js(e.sourceRoot),r=Ts(t).find((i)=>i.name===e.datasetName);return r===void 0?[]:r.fields.map((i)=>({name:i.name,jsonSchema:i.jsonSchema}))},uy=(e)=>`${e.name} (${e.id})`,my=async(e,t)=>{let r=[];for await(let i of e.datasets.listAll({projectId:t}))r.push(i);return r.toSorted((i,n)=>{let s=i.name.localeCompare(n.name);return s===0?i.id.localeCompare(n.id):s})},gc=async(e,t,r)=>{let i=await Ie(t.sourceRoot),n=t.projectId??i?.projectId;y(n,de);let s=t.datasetName,o=await my(e,n),a=(f)=>o.filter((m)=>m.name===f).length<=1,d=ZF(s),u=o.find((f)=>f.id===s||f.id.toLowerCase()===d);if(u!==void 0)return{datasetId:u.id,name:u.name,nameIsUnique:a(u.name)};let l=o.filter((f)=>f.name===s);if(y(l.length<=1,`Project ${n} has multiple datasets named "${s}": ${l.map(uy).join(", ")}.`),l.length===1){let[f]=l;return y(f,`Dataset "${s}" has no resolved ID.`),{datasetId:f.id,name:f.name,nameIsUnique:!0}}let c=i?.projectId===n?i.datasets[s]:void 0;if(c!==void 0){let f=o.find((m)=>m.id===c.datasetId);if(f!==void 0)return{datasetId:f.id,name:f.name,nameIsUnique:a(f.name)}}y(r&&d===void 0,o.length===0?`Dataset "${s}" does not exist in project ${n}. Run toloka apply first.`:`Dataset "${s}" does not exist in project ${n}. This project has: ${o.map(uy).join(", ")}.`),y((await fy(t)).length>0,`Dataset "${s}" does not exist in project ${n} and no pipeline in source declares it. Bind a pipeline to it in source so its columns are known, or upload to an existing dataset.`);let p=await e.datasets.create({projectId:n,name:s});return{datasetId:p.id,name:p.name,nameIsUnique:!0}},tT=async(e)=>(await Br.readFile(e,"utf8")).split(/\r?\n/u).map((r,i)=>({line:r,lineNumber:i+1})).filter(({line:r})=>r.trim().length>0).map(({line:r,lineNumber:i})=>{let n;try{n=JSON.parse(r)}catch{y(!1,`${Ur.basename(e)}:${i} is not valid JSON`)}return y(hc(n),`${Ur.basename(e)}:${i} must contain a JSON object`),n});async function hy(e,t){let r=await tT(t.filePath),i=await gc(e,t,!0),n=i.datasetId,s=new Map;for await(let b of e.datasets.listAllFields({datasetId:n})){if(b.internal||b.name===py)continue;s.set(b.name,{name:b.name,jsonSchema:b.jsonSchema})}for(let b of await fy({...t,datasetName:i.name}))if(!s.has(b.name))s.set(b.name,b);let o=[...s.values()],a=JSON.stringify(r),d=new TextEncoder().encode(a),u=await e.datasets.startUpload({datasetId:n,filename:Ur.basename(t.filePath),format:"json",declaredSizeBytes:d.byteLength,fields:o}),l=await(t.fetch??globalThis.fetch)(u.uploadUrl,{method:"PUT",headers:{"Content-Type":"application/json","x-ms-blob-type":"BlockBlob"},body:d});y(l.ok,`Dataset upload failed with HTTP ${l.status}.`),await e.datasets.finalizeUpload({uploadId:u.job.id});let c=await e.waitFor({type:"datasetUpload",uploadId:u.job.id},t.waitFor),p=i.nameIsUnique?i.name:i.datasetId,f=c.status==="failed"&&c.error?.startsWith("Schema incompatible with existing upload")===!0?`
|
|
138
|
+
Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";y(c.status==="succeeded",`${c.error??`Dataset upload ${c.id} failed.`}${f}`);let m=`Uploaded ${c.result.itemsIngested} rows to dataset ${i.name}.`,h=[],g,_;try{h=(await e.datasets.getInferredFields({datasetId:n})).fields,g=eT(h)}catch(b){_=`Upload succeeded, but inferred fields could not be fetched: ${b instanceof Error?b.message:String(b)}`}return{datasetId:n,rowsUploaded:c.result.itemsIngested,inferredFields:h,output:g===void 0?m:`${m}
|
|
139
|
+
${g}`,..._===void 0?{}:{warning:_}}}async function gy(e,t){let r=await gc(e,t,!1),i=await e.datasets.getInferredFields({datasetId:r.datasetId}),n=i.fields.filter((o)=>o.depth===1),s=$g(n.map(({name:o,jsonSchema:a})=>({name:o,jsonSchema:a})));return{datasetId:r.datasetId,inferredFields:i.fields,declarations:s,output:n.length===0?`Dataset ${r.name} has no inferred fields yet.`:s}}async function yy(e,t){let r=await my(e,t.projectId);if(r.length===0)return{output:"This project has no datasets."};return{output:r.map((i)=>`${i.name} ${i.id}`).join(`
|
|
140
|
+
`)}}var rT=async(e)=>{let t=await e.fetch(e.downloadUrl);y(t.ok,`Dataset export download failed with HTTP ${t.status}.`);let r=await t.text(),i;try{i=JSON.parse(r)}catch(s){throw Error(`Dataset export ${e.exportId} is not valid JSON.`,{cause:s})}y(Array.isArray(i),`Dataset export ${e.exportId} is not a JSON array.`);let n=[];for(let[s,o]of i.entries())y(hc(o),`Dataset export ${e.exportId} row ${s} is not a JSON object.`),n.push(o);return n};async function _y(e,t){let r=await gc(e,t,!1),i=[];for await(let d of e.datasets.listAllFields({datasetId:r.datasetId})){if(d.internal||d.name===py)continue;i.push(d.name)}y(i.length>0,`Dataset ${r.name} has no fields to export.`);let n=await e.datasets.startExport({datasetId:r.datasetId,fields:i}),s;try{s=await e.waitFor({type:"datasetExport",exportId:n.id},t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs})}catch(d){throw y(!(d instanceof re&&d.code==="wait_timeout"),`Stopped waiting for dataset export ${n.id}; raise --timeout to wait longer.`),d}y(s.result.downloadUrl,`Dataset export ${s.id} succeeded without a download URL.`);let o=await rT({downloadUrl:s.result.downloadUrl,exportId:s.id,fetch:t.fetch??globalThis.fetch}),a=t.limit===void 0?o:o.slice(0,t.limit);return await Br.mkdir(Ur.dirname(t.outPath),{recursive:!0}),await Br.writeFile(t.outPath,a.length===0?"":`${a.map((d)=>JSON.stringify(d)).join(`
|
|
135
141
|
`)}
|
|
136
|
-
`),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function Mg(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 gO=["emacs","vim"],yO=new Set(gO);function _O(e){return yO.has(e)}function Ug(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(_O)))}var Ui=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",xs=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var rc=(e)=>e.name==="backspace";var ic=(e)=>"1234567890".includes(e.name),nc=(e)=>e.name==="enter"||e.name==="return";class sc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class oc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Rs extends Error{name="ExitPromptError"}class ac extends Error{name="HookError"}class Bi extends Error{name="ValidationError"}var Kg=require("async_hooks");var Cs=require("async_hooks");var Bg=new Cs.AsyncLocalStorage;function PO(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Gg(e,t){let r=PO(e);return Bg.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Ht(){let e=Bg.getStore();if(!e)throw new ac("[Inquirer] Hook functions can only be called from within a prompt");return e}function lc(){return Ht().rl}function cc(e){let t=(...r)=>{let i=Ht(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Cs.AsyncResource.bind(t)}function Ar(e){let t=Ht(),{index:r}=t,i={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},n=e(i);return t.index++,n}function Vg(){Ht().handleChange()}var Jt={queue(e){let t=Ht(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(lc());if(i!=null&&typeof i!=="function")throw new Bi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Ht();cc(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Ht();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function bO(e){return typeof e==="function"}function tt(e){return Ar((t)=>{let r=Kg.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),Vg()});if(t.initialized)return[t.get(),r];let i=bO(e)?e():e;return t.set(i),[i,r]})}function Qt(e,t){Ar((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))Jt.queue(e);r.set(t)})}var ke=require("util");var Ae=xe(require("process"));function vO(){if(!Ae.default.platform.startsWith("win"))return Ae.default.env.TERM!=="linux";return Boolean(Ae.default.env.CI)||Boolean(Ae.default.env.WT_SESSION)||Boolean(Ae.default.env.TERMINUS_SUBLIME)||Ae.default.env.ConEmuTask==="{cmd::Cmder}"||Ae.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ae.default.env.TERM_PROGRAM==="vscode"||Ae.default.env.TERM==="xterm-256color"||Ae.default.env.TERM==="alacritty"||Ae.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var zg={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"},Wg={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"},wO={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"},$O={...zg,...Wg},EO={...zg,...wO},IO=vO(),SO=IO?$O:EO,kr=SO,RM=Object.entries(Wg);var xO={prefix:{idle:ke.styleText("blue","?"),done:ke.styleText("green",kr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>ke.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>ke.styleText("cyan",e),message:(e)=>ke.styleText("bold",e),error:(e)=>ke.styleText("red",`> ${e}`),defaultAnswer:(e)=>ke.styleText("dim",`(${e})`),help:(e)=>ke.styleText("dim",e),highlight:(e)=>ke.styleText("cyan",e),key:(e)=>ke.styleText("cyan",ke.styleText("bold",`<${e}>`))}};function Hg(){return{...xO,keybindings:Ug()}}function Jg(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 Qg(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Jg(s)&&Jg(n)?Qg(s,n):n}return t}function Gi(...e){let t=[Hg(),...e.filter((r)=>r!=null)];return Qg(...t)}function dc({status:e="idle",theme:t}){let[r,i]=tt(!1),[n,s]=tt(0),{prefix:o,spinner:a}=Gi(t);if(Qt(()=>{if(e==="loading"){let u,l=-1,d=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Vi(e,t){return Ar((r)=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,s)=>n!==t[s])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function Yt(e){return tt({current:e})[0]}function uc(e){let t=Yt(e);t.current=e,Qt((r)=>{let i=!1,n=cc((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var my=xe(Xg(),1);var Zg=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),ey=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ty=(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 jO=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,FO=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ry=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,OO=/\t{1,1000}/y,iy=/[\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,TO=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,AO=/\p{M}+/gu,kO={limit:1/0,ellipsis:""},ny=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?ny(n,kO,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.emojiWidth??2,l=2,d=r.regularWidth??1,p=r.wideWidth??2,f=[[TO,d],[jO,0],[FO,a],[OO,c],[iy,u],[ry,p]],m=0,h=0,g=e.length,y=0,P=!1,v=g,w=Math.max(0,i-s),I=0,E=0,x=0,T=0;e:while(!0){if(E>I||h>=g&&h>m){let R=e.slice(I,E)||e.slice(m,h);y=0;for(let V of R.replaceAll(AO,"")){let J=V.codePointAt(0)||0;if(ey(J))T=2;else if(ty(J))T=p;else T=d;if(x+T>w)v=Math.min(v,Math.max(I,m)+y);if(x+T>i){P=!0;break e}y+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,X]=f[R];if(J.lastIndex=h,J.test(e)){if(y=J===ry?Zg(e.slice(h,J.lastIndex)):J===iy?1:J.lastIndex-h,T=y*X,x+T>w)v=Math.min(v,h+Math.floor((w-x)/X));if(x+T>i){P=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:P?w:x,index:P?v:g,truncated:P,ellipsed:P&&i>=s}},sy=ny;var DO={limit:1/0,ellipsis:"",ellipsisWidth:0},NO=(e,t={})=>sy(e,DO,t).width,ut=NO;var js="\x1B",dy="\x9B",LO=39,fc="\x07",uy="[",qO="]",py="m",mc=`${qO}8;;`,oy=new RegExp(`(?:\\${uy}(?<code>\\d+)m|\\${mc}(?<uri>.*)${fc})`,"y"),ay=(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},ly=(e)=>`${js}${uy}${e}${py}`,cy=(e)=>`${js}${mc}${e}${fc}`,pc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:ut(o),c=i.next(),u=i.next(),l=0;while(!c.done){let d=c.value,p=ut(d);if(a+p<=r)e[e.length-1]+=d;else e.push(d),a=0;if(d===js||d===dy)n=!0,s=t.startsWith(mc,l+1);if(n){if(s){if(d===fc)n=!1,s=!1}else if(d===py)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;c=u,u=i.next(),l+=d.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},MO=(e)=>{let t=e.split(" "),r=t.length;while(r){if(ut(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},UO=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],c=0;for(let d=0;d<o.length;d++){let p=o[d];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=ut(h)}if(d!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=ut(p);if(r.hard&&f>t){let m=t-c,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");pc(a,p,t),c=ut(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){pc(a,p,t),c=ut(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){pc(a,p,t),c=ut(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}if(r.trim!==!1)a=a.map((d)=>MO(d));let u=a.join(`
|
|
137
|
-
`),l=!1;for(let
|
|
138
|
-
`){if(s)i+=
|
|
139
|
-
`){if(n&&
|
|
140
|
-
`)}function
|
|
141
|
-
`).flatMap((r)=>
|
|
142
|
+
`),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function by(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 iT=["emacs","vim"],nT=new Set(iT);function sT(e){return nT.has(e)}function Py(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(sT)))}var Qi=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",As=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var yc=(e)=>e.name==="backspace";var _c=(e)=>"1234567890".includes(e.name),bc=(e)=>e.name==="enter"||e.name==="return";class Pc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class vc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Ds extends Error{name="ExitPromptError"}class wc extends Error{name="HookError"}class Yi extends Error{name="ValidationError"}var Ey=require("async_hooks");var Ns=require("async_hooks");var vy=new Ns.AsyncLocalStorage;function oT(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function wy(e,t){let r=oT(e);return vy.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function er(){let e=vy.getStore();if(!e)throw new wc("[Inquirer] Hook functions can only be called from within a prompt");return e}function $c(){return er().rl}function Ec(e){let t=(...r)=>{let i=er(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Ns.AsyncResource.bind(t)}function Gr(e){let t=er(),{index:r}=t,i={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},n=e(i);return t.index++,n}function $y(){er().handleChange()}var tr={queue(e){let t=er(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e($c());if(i!=null&&typeof i!=="function")throw new Yi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=er();Ec(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=er();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function aT(e){return typeof e==="function"}function st(e){return Gr((t)=>{let r=Ey.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),$y()});if(t.initialized)return[t.get(),r];let i=aT(e)?e():e;return t.set(i),[i,r]})}function rr(e,t){Gr((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))tr.queue(e);r.set(t)})}var Ne=require("util");var De=Ce(require("process"));function lT(){if(!De.default.platform.startsWith("win"))return De.default.env.TERM!=="linux";return Boolean(De.default.env.CI)||Boolean(De.default.env.WT_SESSION)||Boolean(De.default.env.TERMINUS_SUBLIME)||De.default.env.ConEmuTask==="{cmd::Cmder}"||De.default.env.TERM_PROGRAM==="Terminus-Sublime"||De.default.env.TERM_PROGRAM==="vscode"||De.default.env.TERM==="xterm-256color"||De.default.env.TERM==="alacritty"||De.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Iy={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"},Sy={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"},cT={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"},dT={...Iy,...Sy},uT={...Iy,...cT},pT=lT(),fT=pT?dT:uT,Vr=fT,jU=Object.entries(Sy);var mT={prefix:{idle:Ne.styleText("blue","?"),done:Ne.styleText("green",Vr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>Ne.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>Ne.styleText("cyan",e),message:(e)=>Ne.styleText("bold",e),error:(e)=>Ne.styleText("red",`> ${e}`),defaultAnswer:(e)=>Ne.styleText("dim",`(${e})`),help:(e)=>Ne.styleText("dim",e),highlight:(e)=>Ne.styleText("cyan",e),key:(e)=>Ne.styleText("cyan",Ne.styleText("bold",`<${e}>`))}};function xy(){return{...mT,keybindings:Py()}}function Ry(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 Cy(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Ry(s)&&Ry(n)?Cy(s,n):n}return t}function Xi(...e){let t=[xy(),...e.filter((r)=>r!=null)];return Cy(...t)}function Ic({status:e="idle",theme:t}){let[r,i]=st(!1),[n,s]=st(0),{prefix:o,spinner:a}=Xi(t);if(rr(()=>{if(e==="loading"){let u,l=-1,c=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(c),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Zi(e,t){return Gr((r)=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,s)=>n!==t[s])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function ir(e){return st({current:e})[0]}function Sc(e){let t=ir(e);t.current=e,rr((r)=>{let i=!1,n=Ec((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var Wy=Ce(jy(),1);var Fy=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),Ty=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ky=(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 yT=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_T=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ay=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,bT=/\t{1,1000}/y,Dy=/[\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,PT=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,vT=/\p{M}+/gu,wT={limit:1/0,ellipsis:""},Ny=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?Ny(n,wT,r).width:0),o=0,a=r.controlWidth??0,d=r.tabWidth??8,u=r.emojiWidth??2,l=2,c=r.regularWidth??1,p=r.wideWidth??2,f=[[PT,c],[yT,0],[_T,a],[bT,d],[Dy,u],[Ay,p]],m=0,h=0,g=e.length,_=0,b=!1,v=g,w=Math.max(0,i-s),I=0,E=0,x=0,T=0;e:while(!0){if(E>I||h>=g&&h>m){let R=e.slice(I,E)||e.slice(m,h);_=0;for(let V of R.replaceAll(vT,"")){let J=V.codePointAt(0)||0;if(Ty(J))T=2;else if(ky(J))T=p;else T=c;if(x+T>w)v=Math.min(v,Math.max(I,m)+_);if(x+T>i){b=!0;break e}_+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,Z]=f[R];if(J.lastIndex=h,J.test(e)){if(_=J===Ay?Fy(e.slice(h,J.lastIndex)):J===Dy?1:J.lastIndex-h,T=_*Z,x+T>w)v=Math.min(v,h+Math.floor((w-x)/Z));if(x+T>i){b=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:b?w:x,index:b?v:g,truncated:b,ellipsed:b&&i>=s}},Ly=Ny;var $T={limit:1/0,ellipsis:"",ellipsisWidth:0},ET=(e,t={})=>Ly(e,$T,t).width,_t=ET;var Ls="\x1B",Gy="\x9B",IT=39,Rc="\x07",Vy="[",ST="]",Ky="m",Cc=`${ST}8;;`,qy=new RegExp(`(?:\\${Vy}(?<code>\\d+)m|\\${Cc}(?<uri>.*)${Rc})`,"y"),My=(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},Uy=(e)=>`${Ls}${Vy}${e}${Ky}`,By=(e)=>`${Ls}${Cc}${e}${Rc}`,xc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:_t(o),d=i.next(),u=i.next(),l=0;while(!d.done){let c=d.value,p=_t(c);if(a+p<=r)e[e.length-1]+=c;else e.push(c),a=0;if(c===Ls||c===Gy)n=!0,s=t.startsWith(Cc,l+1);if(n){if(s){if(c===Rc)n=!1,s=!1}else if(c===Ky)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;d=u,u=i.next(),l+=c.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},xT=(e)=>{let t=e.split(" "),r=t.length;while(r){if(_t(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},RT=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],d=0;for(let c=0;c<o.length;c++){let p=o[c];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,d=_t(h)}if(c!==0){if(d>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),d=0;if(d||r.trim===!1)a[a.length-1]+=" ",d++}let f=_t(p);if(r.hard&&f>t){let m=t-d,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");xc(a,p,t),d=_t(a.at(-1)??"");continue}if(d+f>t&&d&&f){if(r.wordWrap===!1&&d<t){xc(a,p,t),d=_t(a.at(-1)??"");continue}a.push(""),d=0}if(d+f>t&&r.wordWrap===!1){xc(a,p,t),d=_t(a.at(-1)??"");continue}a[a.length-1]+=p,d+=f}if(r.trim!==!1)a=a.map((c)=>xT(c));let u=a.join(`
|
|
143
|
+
`),l=!1;for(let c=0;c<u.length;c++){let p=u[c];if(i+=p,!l){if(l=p>="\uD800"&&p<="\uDBFF",l)continue}else l=!1;if(p===Ls||p===Gy){qy.lastIndex=c+1;let m=qy.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);n=h===IT?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(u[c+1]===`
|
|
144
|
+
`){if(s)i+=By("");let f=n?My(n):void 0;if(n&&f)i+=Uy(f)}else if(p===`
|
|
145
|
+
`){if(n&&My(n))i+=Uy(n);if(s)i+=By(s)}}return i},CT=/\r?\n/;function zy(e,t,r){return String(e).normalize().split(CT).map((i)=>RT(i,t,r)).join(`
|
|
146
|
+
`)}function en(e,t){return e.split(`
|
|
147
|
+
`).flatMap((r)=>zy(r,t,{trim:!1,wordWrap:!1}).split(`
|
|
142
148
|
`).map((i)=>i.trimEnd())).join(`
|
|
143
|
-
`)}function
|
|
144
|
-
`)}),
|
|
145
|
-
`)}var
|
|
146
|
-
`).length,
|
|
147
|
-
`).pop()??"";class
|
|
149
|
+
`)}function qs(){return Wy.default({defaultWidth:80,output:$c().output})}function OT({active:e,renderedItems:t,pageSize:r,loop:i}){let n=ir({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:o}=n.current,a=Math.floor(r/2),d=t.reduce((c,p)=>c+p.length,0),u=t.slice(0,e).reduce((c,p)=>c+p.length,0),l=u;if(d>r)if(i){if(l=s,o!=null&&o<e&&e-o<r)l=Math.min(a,Math.abs(e-o)===1?Math.min(s+(t[o]?.length??0),Math.max(u,s)):s+e-o)}else{let c=t.slice(e).reduce((p,f)=>p+f.length,0);l=c<r-a?r-c:Math.min(u,a)}return n.current.lastPointer=l,n.current.lastActive=e,l}function Oc({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let s=qs(),o=(_)=>(_%e.length+e.length)%e.length,a=e.map((_,b)=>{if(_==null)return[];return en(r({item:_,index:b,isActive:b===t}),s).split(`
|
|
150
|
+
`)}),d=a.reduce((_,b)=>_+b.length,0),u=(_)=>a[_]??[],l=OT({active:t,renderedItems:a,pageSize:i,loop:n}),c=u(t).slice(0,i),p=l+c.length<=i?l:i-c.length,f=Array.from({length:i});f.splice(p,c.length,...c);let m=new Set([t]),h=p+c.length,g=o(t+1);while(h<i&&!m.has(g)&&(n&&d>i?g!==t:g>t)){let b=u(g).slice(0,i-h);f.splice(h,b.length,...b),m.add(g),h+=b.length,g=o(g+1)}h=p-1,g=o(t-1);while(h>=0&&!m.has(g)&&(n&&d>i?g!==t:g<t)){let _=u(g),b=_.slice(Math.max(0,_.length-h-1));f.splice(h-b.length+1,b.length,...b),m.add(g),h-=b.length,g=o(g-1)}return f.filter((_)=>typeof _==="string").join(`
|
|
151
|
+
`)}var o_=Ce(require("readline")),a_=require("async_hooks"),l_=Ce(Qy(),1);var nr=[];nr.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")nr.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")nr.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Ms=(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",jc=Symbol.for("signal-exit emitter"),Fc=globalThis,FT=Object.defineProperty.bind(Object);class Yy{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Fc[jc])return Fc[jc];FT(Fc,jc,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],i=r.indexOf(t);if(i===-1)return;if(i===0&&r.length===1)r.length=0;else r.splice(i,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let n of this.listeners[e])i=n(t,r)===!0||i;if(e==="exit")i=this.emit("afterExit",t,r)||i;return i}}class kc{}var TT=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class Xy extends kc{onExit(){return()=>{}}load(){}unload(){}}class Zy extends kc{#r=Tc.platform==="win32"?"SIGINT":"SIGHUP";#t=new Yy;#e;#s;#o;#n={};#i=!1;constructor(e){super();this.#e=e,this.#n={};for(let t of nr)this.#n[t]=()=>{let r=this.#e.listeners(t),{count:i}=this.#t,n=e;if(typeof n.__signal_exit_emitter__==="object"&&typeof n.__signal_exit_emitter__.count==="number")i+=n.__signal_exit_emitter__.count;if(r.length===i){this.unload();let s=this.#t.emit("exit",null,t),o=t==="SIGHUP"?this.#r:t;if(!s)e.kill(e.pid,o)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(e,t){if(!Ms(this.#e))return()=>{};if(this.#i===!1)this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{if(this.#t.removeListener(r,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#i)return;this.#i=!0,this.#t.count+=1;for(let e of nr)try{let t=this.#n[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#l(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#i)return;this.#i=!1,nr.forEach((e)=>{let t=this.#n[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(r){}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#o,this.#t.count-=1}#a(e){if(!Ms(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#o.call(this.#e,this.#e.exitCode)}#l(e,...t){let r=this.#s;if(e==="exit"&&Ms(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let i=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),i}else return r.call(this.#e,e,...t)}}var Tc=globalThis.process,{onExit:e_,load:fB,unload:mB}=TT(Ms(Tc)?new Zy(Tc):new Xy);var s_=require("util");var Ac="\x1B[G",r_="\x1B[?25l",i_="\x1B[?25h",Dc=(e=1)=>e>0?`\x1B[${e}A`:"",Nc=(e=1)=>e>0?`\x1B[${e}B`:"",Lc=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},t_="\x1B[2K",qc=(e)=>e>0?(t_+Dc(1)).repeat(e-1)+t_+Ac:"";var n_=(e)=>e.split(`
|
|
152
|
+
`).length,kT=(e)=>e.split(`
|
|
153
|
+
`).pop()??"";class Us{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 r=kT(e),i=s_.stripVTControlCharacters(r),n=i;if(this.rl.line.length>0)n=n.slice(0,-this.rl.line.length);this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let s=qs();if(e=en(e,s),t=en(t,s),i.length%s===0)e+=`
|
|
148
154
|
`;let o=e+(t?`
|
|
149
|
-
`+t:""),
|
|
150
|
-
`,t+=
|
|
151
|
-
at ${R}`)}let[x,T]=typeof E==="string"?[E]:E;l.render(x,T),
|
|
152
|
-
`).trimEnd()}${
|
|
153
|
-
`)}}var
|
|
154
|
-
`)};try{let n=await e.waitFor({type:"pipelineRun",runId:i.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),s=
|
|
155
|
+
`+t:""),d=Math.floor(i.length/s)-this.cursorPos.rows+(t?n_(t):0);if(d>0)o+=Dc(d);o+=Lc(this.cursorPos.cols),this.write(Nc(this.extraLinesUnderPrompt)+qc(this.height)+o),this.extraLinesUnderPrompt=d,this.height=n_(o)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write(Lc(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=Nc(this.extraLinesUnderPrompt);t+=e?qc(this.height):`
|
|
156
|
+
`,t+=Ac,t+=i_,this.write(t),this.rl.close()}}class Mc extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,n)=>{e=i,t=n}),resolve:e,reject:t}}}var c_=Ce(require("path")),AT=globalThis.setImmediate;function DT(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,i)=>{let n=i.slice(1);return t=n,n},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function Uc(e){let t=DT();return(i,n={})=>{let{input:s=process.stdin,signal:o}=n,a=new Set,d=new l_.default;d.pipe(n.output??process.stdout);let u=o_.createInterface({terminal:!0,input:s,output:d});d.mute();let l=new Us(u),{promise:c,resolve:p,reject:f}=Mc.withResolver(),m=()=>f(new vc);if(o){let g=()=>f(new Pc({cause:o.reason}));if(o.aborted)return g(),Object.assign(c,{cancel:m});o.addEventListener("abort",g),a.add(()=>o.removeEventListener("abort",g))}a.add(e_((g,_)=>{f(new Ds(`User force closed the prompt with ${g} ${_}`))}));let h=()=>f(new Ds("User force closed the prompt with SIGINT"));return u.on("SIGINT",h),a.add(()=>u.removeListener("SIGINT",h)),wy(u,(g)=>{let _=a_.AsyncResource.bind(()=>tr.clearAll());u.on("close",_),a.add(()=>u.removeListener("close",_));let b=()=>{let v=()=>l.checkCursorPos();u.input.on("keypress",v),a.add(()=>u.input.removeListener("keypress",v));let w=null;g(()=>{let I=!1;try{let E=e(i,(R)=>{if(I)p(R);else w={value:R}});if(E===void 0){let R=t[1]?.getFileName();if(R&&!R.startsWith("file://"))R=c_.default.resolve(R);throw Error(`Prompt functions must return a string.
|
|
157
|
+
at ${R}`)}let[x,T]=typeof E==="string"?[E]:E;l.render(x,T),tr.run()}catch(E){f(E)}if(I=!0,w!==null){let{value:E}=w;w=null,p(E)}})};if("readableFlowing"in s)AT(b);else b();return Object.assign(c.then((v)=>(tr.clearAll(),v),(v)=>{throw tr.clearAll(),v}).finally(()=>{a.forEach((v)=>v()),l.done({clearContent:Boolean(n.clearPromptOnDone)}),d.end()}).then(()=>c),{cancel:m})})}}var d_=require("util");class ot{separator=d_.styleText("dim",Array.from({length:15}).join(Vr.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 Kr=require("util");var NT={icon:{cursor:Vr.pointer},style:{disabled:(e)=>Kr.styleText("dim",e),description:(e)=>Kr.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Kr.styleText("bold",t)} ${Kr.styleText("dim",r)}`).join(Kr.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function Bc(e){return!ot.isSeparator(e)&&!e.disabled}function Gc(e){return!ot.isSeparator(e)}function LT(e){return e.map((t)=>{if(ot.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let n=String(t);return{value:t,name:n,short:n,disabled:!1}}let r=t.name??String(t.value),i={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)i.description=t.description;return i})}var u_=Uc((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=Xi(NT,e.theme),{keybindings:s}=n,[o,a]=st("idle"),d=Ic({status:o,theme:n}),u=ir(),l=!s.includes("vim"),c=Zi(()=>LT(e.choices),[e.choices]),p=Zi(()=>{let R=c.findIndex(Gc),V=c.findLastIndex(Gc);if(R===-1)throw new Yi("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:V}},[c]),f=Zi(()=>{if(!("default"in e))return-1;return c.findIndex((R)=>Bc(R)&&R.value===e.default)},[e.default,c]),[m,h]=st(f===-1?p.first:f),g=c[m];if(g==null||ot.isSeparator(g))throw Error("Active index does not point to a choice");let[_,b]=st();Sc((R,V)=>{if(clearTimeout(u.current),_)b(void 0);if(bc(R))if(g.disabled)b(n.i18n.disabledError);else a("done"),t(g.value);else if(Qi(R,s)||As(R,s)){if(V.clearLine(0),r||Qi(R,s)&&m!==p.first||As(R,s)&&m!==p.last){let J=Qi(R,s)?-1:1,Z=m;do Z=(Z+J+c.length)%c.length;while(!Gc(c[Z]));h(Z)}}else if(_c(R)&&!Number.isNaN(Number(V.line))){let J=Number(V.line)-1,Z=-1,Re=c.findIndex((Jr)=>{if(ot.isSeparator(Jr))return!1;return Z++,Z===J}),Hr=c[Re];if(Hr!=null&&Bc(Hr))h(Re);u.current=setTimeout(()=>{V.clearLine(0)},700)}else if(yc(R))V.clearLine(0);else if(l){let J=V.line.toLowerCase(),Z=c.findIndex((Re)=>{if(ot.isSeparator(Re)||!Bc(Re))return!1;return Re.name.toLowerCase().startsWith(J)});if(Z!==-1)h(Z);u.current=setTimeout(()=>{V.clearLine(0)},700)}}),rr(()=>()=>{clearTimeout(u.current)},[]);let v=n.style.message(e.message,o),w=n.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),I=0,E=Oc({items:c,active:m,renderItem({item:R,isActive:V,index:J}){if(ot.isSeparator(R))return I++,` ${R.separator}`;let Z=V?n.icon.cursor:" ",Re=n.indexMode==="number"?`${J+1-I}. `:"";if(R.disabled){let Jr=typeof R.disabled==="string"?R.disabled:"(disabled)",j_=V?n.icon.cursor:"-";return n.style.disabled(`${j_} ${Re}${R.name} ${Jr}`)}return(V?n.style.highlight:(Jr)=>Jr)(`${Z} ${Re}${R.name}`)},pageSize:i,loop:r});if(o==="done")return[d,v,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:x}=g;return`${[[d,v].filter(Boolean).join(" "),E," ",x?n.style.description(x):"",_?n.style.error(_):"",w].filter(Boolean).join(`
|
|
158
|
+
`).trimEnd()}${r_}`});var qT="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",MT=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},UT=(e,t)=>{if(t===void 0||t.projectId!==e)return new Map;let r=new Map;for(let[n,s]of Object.entries(t.pipelines)){let o=r.get(s.pipelineId)??[];o.push(n),r.set(s.pipelineId,o)}let i=new Map;for(let[n,s]of r){let[o,...a]=s;if(o!==void 0&&a.length===0)i.set(n,o)}return i},BT=(e,t)=>{let r=t.get(e.id);return{pipelineId:e.id,name:e.name,...r===void 0?{}:{sourceDirectory:r}}},zr=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,GT=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(zr).join(", ")}.`;async function f_(e){return u_({message:"This project tracks several pipelines. Select one",choices:e})}async function m_(e){let t=await h_(e.client,e.projectId,e.state);if(t.length===0)return{outcome:"reported",output:"This project has no pipelines."};return{outcome:"reported",output:t.map((r)=>r.sourceDirectory===void 0?`${r.name} ${r.pipelineId}`:`${r.name} ${r.pipelineId} ${r.sourceDirectory}`).join(`
|
|
159
|
+
`)}}var h_=async(e,t,r)=>{let i=await MT(e.pipelines.listAll({projectId:t})),n=UT(t,r);return i.map((s)=>BT(s,n)).toSorted((s,o)=>{let a=s.name.localeCompare(o.name);return a===0?s.pipelineId.localeCompare(o.pipelineId):a})},Bs=(e,t,r)=>{if(y(e.length<=1,t),e.length!==1)return;let[i]=e;return y(i,r),i},p_=(e,t)=>{let r=GT(t),i=Bs(t.filter((u)=>u.pipelineId===e),r,r);if(i!==void 0)return i;let n=t.filter((u)=>u.name===e),s=Bs(n,`Multiple pipelines are named ${e}: ${n.map(zr).join(", ")}.`,r);if(s!==void 0)return s;let o=Bs(t.filter((u)=>u.sourceDirectory===e),r,r);if(o!==void 0)return o;let a=t.filter((u)=>{if(u.sourceDirectory===void 0)return!1;let l=u.sourceDirectory.split("/");return l[l.length-1]===e}),d=Bs(a,`Multiple pipelines match ${e}: ${a.map(zr).join(", ")}.`,r);if(d!==void 0)return d;y(!1,r)};async function tn(e){let t=await h_(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return p_(e.pipeline,t);if(y(t.length>0,"This project has no pipelines."),t.length>1&&e.select!==void 0){let r=await e.select(t.map((i)=>({name:zr(i),value:i.pipelineId})));return p_(r,t)}if(t.length===1){let[r]=t;y(r,"This project has no pipelines."),y(!1,`Pass a pipeline name. This project has: ${zr(r)}.`)}y(!1,`This project tracks several pipelines, so name one: ${t.map(zr).join(", ")}.`)}var g_=(e)=>`run ${e.id} is ${e.status}`,y_=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function __(e,t){let r=await tn({client:e,...t}),i=await e.runs.start({pipelineId:r.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${g_(i)} for ${r.name}.`,`Follow it with toloka pipeline status ${r.pipelineId}, or re-run with --wait.`].join(`
|
|
160
|
+
`)};try{let n=await e.waitFor({type:"pipelineRun",runId:i.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),s=y_(n);return{outcome:s,output:s==="failed"?[`Run ${n.id} failed.`,`Inspect items with toloka pipeline results ${n.id} --failed.`].join(`
|
|
155
161
|
`):`Run ${n.id} succeeded.`}}catch(n){if(n instanceof re&&n.code==="wait_timeout")return{outcome:"timedOut",output:[`Stopped waiting for run ${i.id}; it has not reached a terminal state yet and may still be running.`,`Check it with toloka pipeline status ${r.pipelineId}.`].join(`
|
|
156
|
-
`)};throw n}}async function
|
|
157
|
-
`)}}async function
|
|
158
|
-
`)}}async function
|
|
159
|
-
${
|
|
160
|
-
${e.state.error}`};async function
|
|
161
|
-
`)}}var
|
|
162
|
-
`)};async function
|
|
163
|
-
`),
|
|
164
|
-
${lT}`).configureOutput({writeOut:(l)=>e.io.stdout(l.replace(/\n$/u,"")),writeErr:(l)=>e.io.stderr(l.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(l)=>{if(i)return;let d=[];for(let m=l;m!==null;m=m.parent)d.push(m.name());if(d.includes("init")||d.includes("help"))return;let p=await Wi(n(),e.io),f=await Oh(p).catch(()=>{return});if(f===void 0)return;i=!0,e.io.stderr(f)}),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let l=await Uf({...n().apiKey===void 0?{}:{apiKey:n().apiKey},...n().baseUrl===void 0?{}:{baseUrl:n().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(l.output);try{let d=await Cf(e.environment);if(d===void 0)return;let p=e.injectedClient??nt(d);await Hi(p,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let l=await Bf(e.environment);e.io.stdout(l.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(l)=>{let d=n(),p=await yi(e.environment,d.apiKey??e.environment.POTATO_API_KEY),f=p.found?.credentials,m=await Wi(d,e.io),h=await $e(m),g=jc(d,e,f,h),y=e.injectedClient,P=await Vf({environment:e.environment,showToken:l.showToken,credentialLookup:p,...d.apiKey===void 0?{}:{flagApiKey:d.apiKey},...d.baseUrl===void 0?{}:{flagBaseUrl:d.baseUrl},...y===void 0?{}:{probe:()=>y},...g===void 0?{}:{project:g}});if(e.io.stdout(P.output),!P.authenticated){r.value=1;return}try{let v=rl(d,h,e.environment,f),w=e.injectedClient??nt({apiKey:v.apiKey,baseUrl:v.baseUrl});await Hi(w,e.analytics)}catch{}});let s=t.command("project").description("select and manage the current platform project");s.command("list").description("list remote projects this key can see").action(async()=>{let l=n(),{client:d,stored:p,state:f}=await te(l,e),m=jc(l,e,p,f);await Af({client:d,io:e.io,...m===void 0?{}:{context:m}})}),s.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??nt(f.credentials);await kf({environment:e.environment,flags:p,client:m,io:e.io,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d===void 0?{}:{projectId:d}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(l)=>{await Df({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let l=n(),d=await Fc(l,e),p=await Wi(l,e.io),f=await $e(p);if(Lf({flags:l,environment:e.environment,stored:d,...f===void 0?{}:{state:f},io:e.io}).project===void 0)r.value=1}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(l)=>{await Nf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??nt(f.credentials),h=await Wi(p,e.io);await qf({environment:e.environment,flags:p,client:m,io:e.io,sourceRoot:h,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d.name===void 0?{}:{name:d.name},...d.teamId===void 0?{}:{teamId:d.teamId}})}),t.command("init").description("initialize this project directory and install agent skills").action(async()=>{let l=n(),d=cT(l),p=await Fc(l,e),f=await $e(d),m=jc(l,e,p,f),h=await Fh(d,m===void 0?{}:{projectId:m.id});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=l??m;_(h,he);let g=await xg(f,{sourceRoot:p,projectId:h,...d?.force===!0?{force:!0}:{}});e.io.stdout(g.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Rg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Fg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});if(e.io.stdout(f.output),!f.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await jg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(l,d)=>{let{client:p,projectId:f}=await te(n(),e);_(f,he);let m=d.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[d.fromEnv];_(m!==void 0,`Missing secret value. Set ${d.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let h=await Mg(p,{projectId:f,name:l,value:m});e.io.stdout(h.output)}catch{e.io.stderr(`Failed to set secret ${l}.`),r.value=1}});let a=t.command("dataset").description("inspect and move dataset catalog and rows");a.command("list").description("list live datasets in the selected project").action(async()=>{let{client:l,projectId:d}=await te(n(),e);_(d,he);let p=await Lg(l,{projectId:d});e.io.stdout(p.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(l)=>{let{sourceRoot:d,client:p,projectId:f}=await te(n(),e),m=await Ng(p,{sourceRoot:d,datasetName:l,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),a.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",Lr).option("--timeout <ms>","how long to wait for the export",Lr).description("download live dataset rows into a JSONL file").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await qg(f,{sourceRoot:p,datasetName:l,outPath:Ji.resolve(d.out),...m===void 0?{}:{projectId:m},...d.limit===void 0?{}:{limit:d.limit},...d.timeout===void 0?{}:{timeoutMs:d.timeout}});e.io.stdout(h.output)}),a.command("upload").argument("<name>","dataset name or id").argument("<file>","JSONL file, one JSON object per line").description("append rows to a dataset").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Dg(f,{sourceRoot:p,datasetName:l,filePath:Ji.resolve(d),...m===void 0?{}:{projectId:m}});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)});let c="pipeline name or id; required unless a TTY picker can choose among several",u=t.command("pipeline").description("operate on a live pipeline in the selected project");return u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:l,projectId:d,state:p}=await te(n(),e);_(d,he);let f=await ky({client:l,projectId:d,state:p});e.io.stdout(f.output)}),u.command("run").argument("[name]",c).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Lr).description("start a run on a deployed pipeline").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await qy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},wait:d.wait,...d.timeout===void 0?{}:{timeoutMs:d.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Cc(h.outcome)}),u.command("status").argument("[name]",c).description("report the latest run's state and item counts").action(async(l)=>{let{client:d,state:p,projectId:f}=await te(n(),e);_(f,he);let m=await Uy(d,{projectId:f,state:p,...l===void 0?{}:{pipeline:l},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(m.output),r.value=Cc(m.outcome)}),u.command("runs").argument("[name]",c).option("--limit <n>","how many runs to list",Lr).description("list recent runs").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await My(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.limit===void 0?{}:{limit:d.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cost").argument("[name]",c).option("--item-limit <n>","cap how many items to price",Lr).description("forecast what a run of this pipeline would bill").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await zy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.itemLimit===void 0?{}:{itemLimit:d.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(l)=>{let{client:d}=await te(n(),e),p=await By(d,{runId:l});e.io.stdout(p.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Lr).option("--failed","only report failed items",!1).description("report a run's items").action(async(l,d)=>{let{client:p}=await te(n(),e),f=await Gy(p,{runId:l,failedOnly:d.failed,...d.limit===void 0?{}:{limit:d.limit}});e.io.stdout(f.output),r.value=Cc(f.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e);_(p,he);let f=await Cg(d,{sourceRoot:l,projectId:p});e.io.stdout(f.output)}),{program:t,exitCode:r}}var uT=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},pT=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:r,resolve:i,reject:n}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",l),process.stdin.off("end",c),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
|
|
165
|
-
`)},
|
|
166
|
-
`){a(),i(s);return}if(p==="\x03"||p==="\x04"){a(),n(Error(p==="\x03"?"Canceled.":"Standard input closed before an API key was entered."));return}if(p==="\x7F"||p==="\b"){if(s.length>0)s=s.slice(0,-1),process.stdout.write("\b \b");continue}s+=p,process.stdout.write("*")}};process.stdin.on("data",l),process.stdin.once("end",
|
|
167
|
-
${t}`}return e instanceof Error?e.message:String(e)},gT=async(e,t,r,i)=>{try{await e.parseAsync([...r],{from:"user"});let n=t.value;return{code:n,outcome:n===0?"succeeded":"failed"}}catch(n){if(n instanceof it){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(hT(n)),{code:1,outcome:"failed",error:n}}};async function Hy(e,t=process.env,r=mT(),i,n=kh({environment:t})){let{program:s,exitCode:o}=dT({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),c=await gT(s,o,e,r);try{n.captureCommand({command:Ah(e),durationMs:Date.now()-a,exitCode:c.code,outcome:c.outcome,...c.error===void 0?{}:{error:c.error}}),await n.shutdown()}catch{}return c.code}Hy(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
|
|
162
|
+
`)};throw n}}async function b_(e,t){let r=await tn({client:e,...t}),i=await e.runs.listPage({pipelineId:r.pipelineId,limit:t.limit??10});if(i.runs.length===0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let n=[];for(let s of i.runs){let o=await e.runs.get({runId:s.id});n.push(` ${o.id} ${o.status.padEnd(9)} ${s.createdAt}`)}return{outcome:"reported",output:[`Runs for ${r.name} (${i.pagination.total} total):`,...n].join(`
|
|
163
|
+
`)}}async function P_(e,t){let r=await tn({client:e,...t}),n=(await e.runs.listPage({pipelineId:r.pipelineId,limit:1})).runs[0];if(n===void 0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let s=await e.runs.get({runId:n.id}),o=t.itemScanLimit??500,a=new Map,d=0;for await(let l of e.runs.listAllItems({runId:s.id}))if(a.set(l.state.status,(a.get(l.state.status)??0)+1),d+=1,d>=o)break;let u=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([l],[c])=>l.localeCompare(c)).map(([l,c])=>` ${l.padEnd(12)} ${c}`);return{outcome:y_(s),output:[`Latest ${g_(s)} (started ${n.createdAt}).`,d>=o?`Items (first ${o}):`:"Items:",...u].join(`
|
|
164
|
+
`)}}async function v_(e,t){let r=await e.runs.cancel({runId:t.runId});return{outcome:"canceled",output:`Requested cancellation of run ${r.id}; it is now ${r.status}.`}}var VT=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
|
|
165
|
+
${qT}`;return e.state.error===null?t:`${t}
|
|
166
|
+
${e.state.error}`};async function w_(e,t){let r=t.limit??20,i=t.itemScanLimit??Math.max(500,r),n=[],s=0;for await(let d of e.runs.listAllItems({runId:t.runId})){if(s+=1,t.failedOnly!==!0||d.state.status==="failed")n.push(d);if(n.length>=r||s>=i)break}if(n.length===0)return{outcome:"reported",output:t.failedOnly===!0&&s>=i?`No failed items in the first ${i} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[s>=i&&n.length<r?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length} after scanning ${i}, limit ${r}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length}, limit ${r}):`,...n.map(VT)].join(`
|
|
167
|
+
`)}}var $_=(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},KT=(e)=>{let t=[0,0,0];for(let r of e)for(let i=0;i<3;i+=1){let n=r[i];t[i]=Math.max(t[i]??0,n?.length??0)}return e.map((r)=>r.map((i,n)=>n===0?i.padEnd(t[0]??0):i.padStart(t[n]??0)).join(" "))},E_=(e,t)=>{let i=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let n of e.subLines??[])if($_(n))i.push(...E_(n,t+1));return i},zT=(e)=>{let t=[],r=[];for(let i of e){if(i.kind==="priced"){t.push([i.nodeNameDisplay,i.expectedTotal,i.maxTotal]);for(let n of i.displayBreakdown)if($_(n))t.push(...E_(n,1));continue}r.push(i.kind==="validation-errors"?` ${i.nodeNameDisplay} skipped (validation errors)`:` ${i.nodeNameDisplay} not billed`)}return{billed:t,unpriced:r}},WT=(e)=>{let t=[["Total",e.expected,e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,""]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},HT=(e,t)=>{let{billed:r,unpriced:i}=zT(e.nodes),n=WT(e.total),s=KT([["Item","Expected","Maximum"],...r,...n]),o=s.slice(0,1+r.length),a=s.slice(1+r.length),d=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...o];if(r.length===0)d.push(" (no billed nodes)");if(d.push("",...a),i.length>0)d.push("","Not billed",...i);if(e.isInternalPricing===!0)d.push("","Internal-team pricing.");return d.push("",e.disclaimer),d.join(`
|
|
168
|
+
`)};async function I_(e,t){let r=await tn({client:e,...t}),i=await e.pipelines.estimateCost({pipelineId:r.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:HT(i,r.name)}}var S_=require("crypto"),Vc=require("fs"),Gs=require("fs/promises"),We=require("path"),JT=262144,QT=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),YT=async(e,t)=>{let r=We.relative(t,e);if(r===""||r===".."||r.startsWith(`..${We.sep}`)||We.isAbsolute(r))return;let i=r.split(We.sep);for(let n=1;n<i.length;n+=1){let s=We.join(t,...i.slice(0,n)),o=await Gs.lstat(s);y(!o.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${s}; select a path that does not traverse symbolic links.`)}},XT=async(e,t,r)=>{let i=We.resolve(r,e);await YT(i,t);let n;try{n=await Gs.open(i,Vc.constants.O_RDONLY|Vc.constants.O_NOFOLLOW)}catch(s){throw y(!(s instanceof Error&&("code"in s)&&s.code==="ELOOP"),`Report file ${i} is a symbolic link; select the file it points to directly.`),s}try{let s=await n.stat();return y(s.isFile(),`Report file ${i} is not a regular file.`),y(s.size>0,`Report file ${i} is empty.`),y(s.size<=JT,`Report file ${i} is ${s.size} bytes; the limit is 256 KiB.`),{handle:n,absolutePath:i,size:s.size}}catch(s){throw await n.close(),s}},ZT=async(e,t,r)=>{let i=await XT(e,t,r);try{let n=await i.handle.readFile();y(n.byteLength===i.size,`${i.absolutePath} changed while it was being read.`);try{return QT.decode(n)}catch{throw Error(`Report file ${i.absolutePath} is not valid UTF-8.`)}}finally{await i.handle.close()}},ek=async(e,t)=>{if(t)return!0;if(e.prompt===void 0)return!1;let r=(await e.prompt("Send this report to Toloka? [y/N] ")).trim().toLowerCase();return r==="y"||r==="yes"};async function x_(e){let{analytics:t,io:r}=e;y(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.");let i=await ZT(e.path,e.sourceRoot,e.cwd);if(r.stdout("Issue report preview:"),r.stdout(""),r.stdout(i.replace(/(?![\t\n])(?!\r\n)(?:\p{Cc}|\p{Bidi_Control})/gu,(s)=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`)),r.stdout(""),r.stdout(`Authored by: ${e.authoredBy}`),r.stdout(`Platform: ${e.platform}`),r.stdout(""),!await ek(r,e.confirm))return r.stderr("Refusing to submit without confirmation in a non-interactive environment. Pass --confirm after reviewing the preview above."),1;let n=S_.randomUUID();return await t.submitIssueReport({reportId:n,reportText:i,authoredBy:e.authoredBy,platform:e.platform}),r.stdout(`Submitted issue report: ${n}`),0}var tk=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. POTATO_API_KEY / POTATO_BASE_URL"," 3. the file written by toloka login",`The platform defaults to ${Vt}.`].join(`
|
|
169
|
+
`),rk=(e)=>{if(e!=="human"&&e!=="agent")throw new lt('Expected "human" or "agent".');return e},Wr=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new lt("Expected a positive integer.");return t},Kc=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},kt=async(e,t)=>{if(e.sourceRoot!==void 0)return nn.resolve(e.sourceRoot);let r=process.cwd(),i=await ry(r);if(i===void 0||i===r)return r;return t.stderr(`Using project root ${i} (found from ${r}).`),i},R_=(e)=>e.sourceRoot===void 0?process.cwd():nn.resolve(e.sourceRoot),Wc=async(e,t)=>{let{found:r,warning:i}=await Si(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(i!==void 0)t.io.stderr(i);return r?.credentials},rn=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},X=async(e,t)=>{let r=await kt(e,t.io),i=await Ie(r),n=await Wc(e,t),s=ul(e,i,t.environment,n),o=t.injectedClient??ct({apiKey:s.apiKey,baseUrl:s.baseUrl});return await rn(o,t.analytics),{sourceRoot:r,client:o,baseUrl:s.baseUrl,state:i,stored:n,...s.projectId===void 0?{}:{projectId:s.projectId}}},zc=(e,t,r,i)=>Ri({flags:e,environment:t.environment,stored:r,...i===void 0?{}:{state:i}});function ik(e){let t=new sr("toloka"),r={value:0},i=!1;t.description("Preview. Build and operate Toloka pipeline projects from TypeScript source. The public API may change.").version(Ve,"-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",`
|
|
170
|
+
${tk}`).configureOutput({writeOut:(c)=>e.io.stdout(c.replace(/\n$/u,"")),writeErr:(c)=>e.io.stderr(c.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(c,p)=>{if(i)return;let f=[];for(let g=p;g!==null;g=g.parent)f.push(g.name());if(f.includes("init")||f.includes("help")||f.includes("report")||f.includes("url")||f.includes("version"))return;let m=await kt(n(),e.io),h=await ug(m).catch(()=>{return});if(h===void 0)return;i=!0,e.io.stderr(h)}),t.command("version").description("print the current CLI version").action(()=>e.io.stdout(Ve)),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let c=await nm({...n().apiKey===void 0?{}:{apiKey:n().apiKey},...n().baseUrl===void 0?{}:{baseUrl:n().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(c.output);try{let p=await zf(e.environment);if(p===void 0)return;let f=e.injectedClient??ct(p);await rn(f,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let c=await sm(e.environment);e.io.stdout(c.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(c)=>{let p=n(),f=await Si(e.environment,p.apiKey??e.environment.POTATO_API_KEY),m=f.found?.credentials,h=await kt(p,e.io),g=await Ie(h),_=zc(p,e,m,g),b=e.injectedClient,v=await am({environment:e.environment,showToken:c.showToken,credentialLookup:f,...p.apiKey===void 0?{}:{flagApiKey:p.apiKey},...p.baseUrl===void 0?{}:{flagBaseUrl:p.baseUrl},...b===void 0?{}:{probe:()=>b},..._===void 0?{}:{project:_}});if(e.io.stdout(v.output),!v.authenticated){r.value=1;return}try{let w=ul(p,g,e.environment,m),I=e.injectedClient??ct({apiKey:w.apiKey,baseUrl:w.baseUrl});await rn(I,e.analytics)}catch{}});let s=t.command("project").description("select and manage the current platform project");s.command("list").description("list remote projects this key can see").action(async()=>{let c=n(),{client:p,stored:f,state:m}=await X(c,e),h=zc(c,e,f,m);await Yf({client:p,io:e.io,...h===void 0?{}:{context:h}})}),s.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(c,p)=>{let f=n(),m=await Ot(e.environment),h=e.injectedClient??ct(m.credentials);await Xf({environment:e.environment,flags:f,client:h,io:e.io,afterPreflight:async()=>rn(h,e.analytics),...c===void 0?{}:{alias:c},...p===void 0?{}:{projectId:p}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(c)=>{await Zf({environment:e.environment,flags:n(),alias:c,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let c=n(),p=await Wc(c,e),f=await kt(c,e.io),m=await Ie(f);if(tm({flags:c,environment:e.environment,stored:p,...m===void 0?{}:{state:m},io:e.io}).project===void 0)r.value=1}),s.command("url").description("print the current project URL").action(async()=>{let{baseUrl:c,client:p,projectId:f}=await X(n(),e);y(f,de);let m=await p.projects.get({projectId:f}),h=new URL(`/teams/${encodeURIComponent(m.teamId)}/projects/${encodeURIComponent(m.id)}`,c);e.io.stdout(h.href)}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(c)=>{await em({environment:e.environment,flags:n(),alias:c,io:e.io})}),s.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(c,p)=>{let f=n(),m=await Ot(e.environment),h=e.injectedClient??ct(m.credentials),g=await kt(f,e.io);await rm({environment:e.environment,flags:f,client:h,io:e.io,sourceRoot:g,afterPreflight:async()=>rn(h,e.analytics),...c===void 0?{}:{alias:c},...p.name===void 0?{}:{name:p.name},...p.teamId===void 0?{}:{teamId:p.teamId}})}),t.command("init").description("initialize this project directory and install the agent bootstrap").action(async()=>{let c=n(),p=R_(c),f=await Wc(c,e),m=await Ie(p),h=zc(c,e,f,m),g=await dg(p,h===void 0?{}:{projectId:h.id});if(e.io.stdout(g.output),g.warning!==void 0)e.io.stderr(g.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=c??h;y(g,de);let _=await oy(m,{sourceRoot:f,projectId:g,...p?.force===!0?{force:!0}:{}});e.io.stdout(_.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await ay(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await dy(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});if(e.io.stdout(m.output),!m.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await cy(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(c,p)=>{let{client:f,projectId:m}=await X(n(),e);y(m,de);let h=p.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[p.fromEnv];y(h!==void 0,`Missing secret value. Set ${p.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let g=await by(f,{projectId:m,name:c,value:h});e.io.stdout(g.output)}catch{e.io.stderr(`Failed to set secret ${c}.`),r.value=1}});let a=t.command("dataset").description("inspect and move dataset catalog and rows");a.command("list").description("list live datasets in the selected project").action(async()=>{let{client:c,projectId:p}=await X(n(),e);y(p,de);let f=await yy(c,{projectId:p});e.io.stdout(f.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(c)=>{let{sourceRoot:p,client:f,projectId:m}=await X(n(),e),h=await gy(f,{sourceRoot:p,datasetName:c,...m===void 0?{}:{projectId:m}});e.io.stdout(h.output)}),a.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",Wr).option("--timeout <ms>","how long to wait for the export",Wr).description("download live dataset rows into a JSONL file").action(async(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=await _y(m,{sourceRoot:f,datasetName:c,outPath:nn.resolve(p.out),...h===void 0?{}:{projectId:h},...p.limit===void 0?{}:{limit:p.limit},...p.timeout===void 0?{}:{timeoutMs:p.timeout}});e.io.stdout(g.output)}),a.command("upload").argument("<name>","dataset name or id").argument("<file>","JSONL file, one JSON object per line").description("append rows to a dataset").action(async(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=await hy(m,{sourceRoot:f,datasetName:c,filePath:nn.resolve(p),...h===void 0?{}:{projectId:h}});if(e.io.stdout(g.output),g.warning!==void 0)e.io.stderr(g.warning)});let d="pipeline name or id; required unless a TTY picker can choose among several",u=t.command("pipeline").description("operate on a live pipeline in the selected project");u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:c,projectId:p,state:f}=await X(n(),e);y(p,de);let m=await m_({client:c,projectId:p,state:f});e.io.stdout(m.output)}),u.command("run").argument("[name]",d).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Wr).description("start a run on a deployed pipeline").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await __(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},wait:p.wait,...p.timeout===void 0?{}:{timeoutMs:p.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output),r.value=Kc(g.outcome)}),u.command("status").argument("[name]",d).description("report the latest run's state and item counts").action(async(c)=>{let{client:p,state:f,projectId:m}=await X(n(),e);y(m,de);let h=await P_(p,{projectId:m,state:f,...c===void 0?{}:{pipeline:c},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Kc(h.outcome)}),u.command("runs").argument("[name]",d).option("--limit <n>","how many runs to list",Wr).description("list recent runs").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await b_(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},...p.limit===void 0?{}:{limit:p.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output)}),u.command("cost").argument("[name]",d).option("--item-limit <n>","cap how many items to price",Wr).description("forecast what a run of this pipeline would bill").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await I_(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},...p.itemLimit===void 0?{}:{itemLimit:p.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(c)=>{let{client:p}=await X(n(),e),f=await v_(p,{runId:c});e.io.stdout(f.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Wr).option("--failed","only report failed items",!1).description("report a run's items").action(async(c,p)=>{let{client:f}=await X(n(),e),m=await w_(f,{runId:c,failedOnly:p.failed,...p.limit===void 0?{}:{limit:p.limit}});e.io.stdout(m.output),r.value=Kc(m.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e);y(f,de);let m=await ly(p,{sourceRoot:c,projectId:f});e.io.stdout(m.output)}),t.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",rk,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(c,p)=>{y(e.analytics,"Issue reporting requires CLI analytics.");let f=R_(n()),m=n().baseUrl??e.environment.POTATO_BASE_URL??mt(e.environment)??Vt;r.value=await x_({path:c,authoredBy:p.authoredBy,platform:new URL(m).origin,confirm:p.confirm,sourceRoot:f,cwd:process.cwd(),analytics:e.analytics,io:e.io})});let l=t.command("skill").description("discover bundled agent skills and install them into .agents/skills");return l.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(c)=>{let p=await kt(n(),e.io);await tg({sourceRoot:p,json:c.json,io:e.io})}),l.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(c,p)=>{let f=await kt(n(),e.io);await rg({sourceRoot:f,query:c,json:p.json,io:e.io})}),l.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(c,p)=>{let f=await kt(n(),e.io);await ig({sourceRoot:f,skillId:c,force:p.force,io:e.io})}),{program:t,exitCode:r}}var nk=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},sk=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:r,resolve:i,reject:n}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",l),process.stdin.off("end",d),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
|
|
171
|
+
`)},d=()=>{a(),n(Error("Standard input closed before an API key was entered."))},u=(c)=>{a(),n(c)},l=(c)=>{for(let p of c){if(p==="\r"||p===`
|
|
172
|
+
`){a(),i(s);return}if(p==="\x03"||p==="\x04"){a(),n(Error(p==="\x03"?"Canceled.":"Standard input closed before an API key was entered."));return}if(p==="\x7F"||p==="\b"){if(s.length>0)s=s.slice(0,-1),process.stdout.write("\b \b");continue}s+=p,process.stdout.write("*")}};process.stdin.on("data",l),process.stdin.once("end",d),process.stdin.once("error",u);try{return await r}finally{o()}},ok=async(e,t={})=>{if(t.mask===!0)return sk(e);let r=C_.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await r.question(e)}finally{r.close()}},ak=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:nk,...process.stdin.isTTY?{prompt:ok,select:f_}:{}}),lk=async(e,t,r,i)=>{try{await e.parseAsync([...r],{from:"user"});let n=t.value;return{code:n,outcome:n===0?"succeeded":"failed"}}catch(n){if(n instanceof at){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(Gi(n)),{code:1,outcome:"failed",error:n}}};async function O_(e,t=process.env,r=ak(),i,n=mg({environment:t})){let{program:s,exitCode:o}=ik({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),d=await lk(s,o,e,r);try{n.captureCommand({command:fg(e),durationMs:Date.now()-a,exitCode:d.code,outcome:d.outcome,...d.error===void 0?{}:{error:d.error}}),await n.shutdown()}catch{}return d.code}O_(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
|