Reject incomplete tenant identity metadata (#13)

This commit is contained in:
gitea committed 2026-09-02 15:02:54 +08:00
1 parent ade7156c01
commit d6e9b505ea
3 files changed
+42 -23

No files matched your search

+22 -22
View File
@@ -1,14 +1,14 @@
import{createRequire as Ny}from"node:module";var cy=Object.create;var{getPrototypeOf:Uy,defineProperty:w$,getOwnPropertyNames:Dy}=Object;var Sy=Object.prototype.hasOwnProperty;function Ay(n){return this[n]}var Oy,ky,Z4=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Oy??=new WeakMap:ky??=new WeakMap,e=t.get(n);if(e)return e}r=n!=null?cy(Uy(n)):{};let u=i||!n||!n.__esModule?w$(r,"default",{value:n,enumerable:!0}):r;for(let l of Dy(n))if(!Sy.call(u,l))w$(u,l,{get:Ay.bind(n,l),enumerable:!0});if(o)t.set(n,u);return u};var P=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var dy=(n)=>n;function Ly(n,i){this[n]=dy.bind(null,i)}var pi=(n,i)=>{for(var r in i)w$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:Ly.bind(i,r)})};var m4=Ny(import.meta.url);var ne=P((kD)=>{Object.defineProperty(kD,"__esModule",{value:!0});kD.regexpCode=kD.getEsmExportName=kD.getProperty=kD.safeStringify=kD.stringify=kD.strConcat=kD.addCodeArg=kD.str=kD._=kD.nil=kD._Code=kD.Name=kD.IDENTIFIER=kD._CodeOrName=void 0;class Ql{}kD._CodeOrName=Ql;kD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Ql{constructor(n){super();if(!kD.IDENTIFIER.test(n))throw Error("CodeGen: name must be a valid identifier");this.str=n}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}kD.Name=Jr;class ci extends Ql{constructor(n){super();this._items=typeof n==="string"?[n]:n}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let n=this._items[0];return n===""||n==='""'}get str(){var n;return(n=this._str)!==null&&n!==void 0?n:this._str=this._items.reduce((i,r)=>`${i}${r}`,"")}get names(){var n;return(n=this._names)!==null&&n!==void 0?n:this._names=this._items.reduce((i,r)=>{if(r instanceof Jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}kD._Code=ci;kD.nil=new ci("");function AD(n,...i){let r=[n[0]],o=0;while(o<i.length)jc(r,i[o]),r.push(n[++o]);return new ci(r)}kD._=AD;var Gc=new ci("+");function OD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(Gc),jc(r,i[o]),r.push(Gc,so(n[++o]));return ZJ(r),new ci(r)}kD.str=OD;function jc(n,i){if(i instanceof ci)n.push(...i._items);else if(i instanceof Jr)n.push(i);else n.push(zJ(i))}kD.addCodeArg=jc;function ZJ(n){let i=1;while(i<n.length-1){if(n[i]===Gc){let r=mJ(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function mJ(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Jr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof Jr))return`"${n}${i.slice(1)}`;return}function MJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:OD`${n}${i}`}kD.strConcat=MJ;function zJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function CJ(n){return new ci(so(n))}kD.stringify=CJ;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}kD.safeStringify=so;function RJ(n){return typeof n=="string"&&kD.IDENTIFIER.test(n)?new ci(`.${n}`):AD`[${n}]`}kD.getProperty=RJ;function xJ(n){if(typeof n=="string"&&kD.IDENTIFIER.test(n))return new ci(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}kD.getEsmExportName=xJ;function aJ(n){return new ci(n.toString())}kD.regexpCode=aJ});var Xc=P((yD)=>{Object.defineProperty(yD,"__esModule",{value:!0});yD.ValueScope=yD.ValueScopeName=yD.Scope=yD.varKinds=yD.UsedValueState=void 0;var an=ne();class LD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var Kl;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(Kl||(yD.UsedValueState=Kl={}));yD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Jc{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof an.Name?n:this.name(n)}name(n){return new an.Name(this._newName(n))}_newName(n){let i=this._names[n]||this._nameGroup(n);return`${n}${i.index++}`}_nameGroup(n){var i,r;if(((r=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||r===void 0?void 0:r.has(n))||this._prefixes&&!this._prefixes.has(n))throw Error(`CodeGen: prefix "${n}" is not allowed in this scope`);return this._names[n]={prefix:n,index:0}}}yD.Scope=Jc;class Hc extends an.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=an._`.${new an.Name(i)}[${r}]`}}yD.ValueScopeName=Hc;var g8=an._`\n`;class ND extends Jc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?g8:an.nil}}get(){return this._scope}name(n){return new Hc(n,this._newName(n))}value(n,i){var r;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(n),{prefix:t}=o,e=(r=i.key)!==null&&r!==void 0?r:i.ref,u=this._values[t];if(u){let I=u.get(e);if(I)return I}else u=this._values[t]=newLine truncated
`:""},this._extScope=n,this._scope=new Ui.Scope({parent:n}),this._nodes=[new PD]}toString(){return this._root.render(this.opts)}name(n){return this._scope.name(n)}scopeName(n){return this._extScope.name(n)}scopeValue(n,i){let r=this._extScope.value(n,i);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(n,i){return this._extScope.getValue(n,i)}scopeRefs(n){return this._extScope.scopeRefs(n,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(n,i,r,o){let t=this._scope.toName(i);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new jD(n,t,r)),t}const(n,i,r){return this._def(Ui.varKinds.const,n,i,r)}let(n,i,r){return this._def(Ui.varKinds.let,n,i,r)}var(n,i,r){return this._def(Ui.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Yc(n,i,r))}add(n,i){return this._leafNode(new WD(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new hD(n));return this}object(...n){let i=["{"];for(let[r,o]of n){if(i.length>1)i.push(",");if(i.push(r),r!==o||this.opts.es5)i.push(":"),(0,s.addCodeArg)(i,o)}return i.push("}"),new s._Code(i)}if(n,i,r){if(this._blockNode(new Vi(n)),i&&r)this.code(i).else().code(r).endIf();else if(i)this.code(i).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(n){return this._elseNode(new Vi(n))}else(){return this._elseNode(new ie)}endIf(){return this._endBlockNode(Vi,ie)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new YD(n),i)}forRange(n,i,r,o,t=this.opts.es5?Ui.varKinds.var:Ui.varKinds.let){let e=this._scope.toName(n);return this._for(new pD(t,e,i,r),()=>o(e))}forOf(n,i,r,o=Ui.varKinds.const){let t=this._scope.toName(n);if(this.opts.es5){let e=i instanceof s.Name?i:this.var("_arr",i);return this.forRange("_i",0,s._`${e}.length`,(u)=>{this.var(t,s._`${e}[${u}]`),r(t)})}return this._for(new hc("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?Ui.varKinds.var:Ui.varKinds.const){if(this.opts.ownProperties)return this.forOf(n,s._`Object.keys(${i})`,r);let t=this._scope.toName(n);return this._for(new hc("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Hr)}label(n){return this._leafNode(new JD(n))}break(n){return this._leafNode(new HD(n))}return(n){let i=new Vl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Vl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new QD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Tl(t),i(t)}if(r)this._currNode=o.finally=new ql,this.code(r);return this._endBlockNode(Tl,ql)}throw(n){return this._leafNode(new XD(n))}block(n,i){if(this._blockStarts.push(this._nodes.length),n)this.code(n).endBlock(i);return this}endBlock(n){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-i;if(r<0||n!==void 0&&r!==n)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${n} expected`);return this._nodes.length=i,this}func(n,i=s.nil,r,o){if(this._blockNode(new Bl(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Bl)}optimize(n=1){while(n-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(n){return this._currNode.nodes.push(n),this}_blockNode(n){this._currNode.nodes.push(n),this._nodes.push(n)}_endBlockNode(n,i){let r=this._currNode;if(r instanceof n||i&&r instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${n.kind}/${i.kind}`:n.kind}"`)}_elseNode(n){let i=this._currNode;if(!(i instanceof Vi))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=n,this}get _root(){return this._nodes[0]}get _currNode(){let n=this._nodes;return n[n.length-1]}set _currNode(n){let i=this._nodes;i[i.length-1]=n}}sn.CodeGen=FD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function _l(n,i){return i instanceof s._CodeOrName?Xt(n,i.names):n}function Xr(n,i,r){if(n instanceof s.Name)return o(n);if(!t(n))return n;return new s._Code(n._items.reduce((e,u)=>{if(u instanceof s.Name)u=o(u);if(u instanceof s._Code)e.push(...u._items);else e.push(u);return e},[]));function o(e){let u=r[e.str];if(u===void 0||i[e.str]!==1)return e;return delete i[e.str],u}function t(e){return e instanceof s._Code&&e._items.some((u)=>u instanceof s.Name&&i[u.str]===1&&r[u.str]!==void 0)}}function c8(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function KD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Pc(n)}`}sn.not=KD;var U8=BD(sn.operators.AND);function D8(...n){return n.reduce(U8)}sn.and=D8;var S8=BD(sn.operators.OR);function A8(...n){return n.reduce(S8)}sn.or=A8;function BD(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${Pc(i)} ${n} ${Pc(r)}`}function Pc(n){return n instanceof s.Name?n:s._`(${n})`}});var nn=P((zD)=>{Object Line truncated
|| (${u} == "string" && ${t} && ${t} == +${t})`).assign(l,m._`+${t}`);return;case"integer":o.elseIf(m._`${u} === "boolean" || ${t} === null
|| (${u} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,m._`+${t}`);return;case"boolean":o.elseIf(m._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(m._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(m._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(m._`${u} === "string" || ${u} === "number"
|| ${u} === "boolean" || ${t} === null`).assign(l,m._`[${t}]`)}}}function hH({gen:n,parentData:i,parentDataProperty:r},o){n.if(m._`${i} !== undefined`,()=>n.assign(m._`${i}[${r}]`,o))}function Tc(n,i,r,o=hr.Correct){let t=o===hr.Correct?m.operators.EQ:m.operators.NEQ,e;switch(n){case"null":return m._`${i} ${t} null`;case"array":e=m._`Array.isArray(${i})`;break;case"object":e=m._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":e=u(m._`!(${i} % 1) && !isNaN(${i})`);break;case"number":e=u();break;default:return m._`typeof ${i} ${t} ${n}`}return o===hr.Correct?e:(0,m.not)(e);function u(l=m.nil){return(0,m.and)(m._`typeof ${i} == "number"`,l,r?m._`isFinite(${i})`:m.nil)}}c1.checkDataType=Tc;function qc(n,i,r,o){if(n.length===1)return Tc(n[0],i,r,o);let t,e=(0,b1.toHash)(n);if(e.array&&e.object){let u=m._`typeof ${i} != "object"`;t=e.null?u:m._`!${i} || ${u}`,delete e.null,delete e.array,delete e.object}else t=m.nil;if(e.number)delete e.integer;for(let u in e)t=(0,m.and)(t,Tc(u,i,r,o));return t}c1.checkDataTypes=qc;var PH={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?m._`{type: ${n}}`:m._`{type: ${i}}`};function _c(n){let i=YH(n);(0,jH.reportError)(i,PH)}c1.reportTypeError=_c;function YH(n){let{gen:i,data:r,schema:o}=n,t=(0,b1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var O1=P((S1)=>{Object.defineProperty(S1,"__esModule",{value:!0});S1.assignDefaults=void 0;var Pr=M(),TH=nn();function qH(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)D1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,e)=>D1(n,e,t.default))}S1.assignDefaults=qH;function D1(n,i,r){let{gen:o,compositeRule:t,data:e,opts:u}=n;if(r===void 0)return;let l=Pr._`${e}${(0,Pr.getProperty)(i)}`;if(t){(0,TH.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Pr._`${l} === undefined`;if(u.useDefaults==="empty")$=Pr._`${$} || ${l} === null || ${l} === ""`;o.if($,Pr._`${l} = ${(0,Pr.stringify)(r)}`)}});var Ii=P((L1)=>{Object.defineProperty(L1,"__esModule",{value:!0});L1.validateUnion=L1.validateArray=L1.usePattern=L1.callValidateCode=L1.schemaProperties=L1.allSchemaProperties=L1.noPropertyInData=L1.propertyInData=L1.isOwnProperty=L1.hasPropFunc=L1.reportMissingProp=L1.checkMissingProp=L1.checkReportMissingProp=void 0;var Sn=M(),Ec=nn(),gt=Ti(),_H=nn();function EH(n,i){let{gen:r,data:o,it:t}=n;r.if(mc(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Sn._`${i}`},!0),n.error()})}L1.checkReportMissingProp=EH;function ZH({gen:n,data:i,it:{opts:r}},o,t){return(0,Sn.or)(...o.map((e)=>(0,Sn.and)(mc(n,i,e,r.ownProperties),Sn._`${t} = ${e}`)))}L1.checkMissingProp=ZH;function mH(n,i){n.setParams({missingProperty:i},!0),n.error()}L1.reportMissingProp=mH;function k1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Sn._`Object.prototype.hasOwnProperty`})}L1.hasPropFunc=k1;function Zc(n,i,r){return Sn._`${k1(n)}.call(${i}, ${r})`}L1.isOwnProperty=Zc;function MH(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} !== undefined`;return o?Sn._`${t} && ${Zc(n,i,r)}`:t}L1.propertyInData=MH;function mc(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} === undefined`;return o?(0,Sn.or)(t,(0,Sn.not)(Zc(n,i,r))):t}L1.noPropertyInData=mc;function d1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}L1.allSchemaProperties=d1;function zH(n,i){return d1(i).filter((r)=>!(0,Ec.alwaysValidSchema)(n,i[r]))}L1.schemaProperties=zH;function CH({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:e},it:u},l,$,I){let g=I?Sn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Sn.strConcat)(gt.default.instancePath,e)],[gt.default.parentData,u.parentData],[gt.default.parentDataProperty,u.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(u.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let w=Sn._`${g}, ${r.object(...b)}`;return $!==Sn.nil?Sn._`${l}.call(${$}, ${w})`:Sn._`${l}(${w})`}L1.callValidateCode=CH;var RH=Sn._`new RegExp`;function xH({gen:n,it:{opts:i}},r){let o=i.unicodeRegExp?"u":"",{regExp:t}=i.code,e=t(r,o);return n.scopeValue("pattern",{key:e.toString(),ref:e,code:Sn._`${t.code==="new RegExp"?RH:(0,_H.useFunc)(n,t)}(${r}, ${o})`})}L1.usePattern=xH;function aH(n){let{gen:i,data:r,keyword:o,it:t}=n,e=i.name("valid");if(t.allErrors){let l=i.let("valid",!0);return u(()=>i.assign(l,!1)),l}return i.var(e,!0),u(()=>i.break()),e;function u(l){let $=i.const("len",Sn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:Ec.Type.Num},e),i.if((0,Sn.not)(e),l)})}}L1.validateArray=aH;function sH(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,Ec.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let u=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
import{createRequire as Ny}from"node:module";var cy=Object.create;var{getPrototypeOf:Uy,defineProperty:w$,getOwnPropertyNames:Dy}=Object;var Sy=Object.prototype.hasOwnProperty;function Ay(n){return this[n]}var Oy,ky,m4=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Oy??=new WeakMap:ky??=new WeakMap,e=t.get(n);if(e)return e}r=n!=null?cy(Uy(n)):{};let u=i||!n||!n.__esModule?w$(r,"default",{value:n,enumerable:!0}):r;for(let l of Dy(n))if(!Sy.call(u,l))w$(u,l,{get:Ay.bind(n,l),enumerable:!0});if(o)t.set(n,u);return u};var P=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var dy=(n)=>n;function Ly(n,i){this[n]=dy.bind(null,i)}var pi=(n,i)=>{for(var r in i)w$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:Ly.bind(i,r)})};var Z4=Ny(import.meta.url);var ne=P((kD)=>{Object.defineProperty(kD,"__esModule",{value:!0});kD.regexpCode=kD.getEsmExportName=kD.getProperty=kD.safeStringify=kD.stringify=kD.strConcat=kD.addCodeArg=kD.str=kD._=kD.nil=kD._Code=kD.Name=kD.IDENTIFIER=kD._CodeOrName=void 0;class Ql{}kD._CodeOrName=Ql;kD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Ql{constructor(n){super();if(!kD.IDENTIFIER.test(n))throw Error("CodeGen: name must be a valid identifier");this.str=n}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}kD.Name=Jr;class ci extends Ql{constructor(n){super();this._items=typeof n==="string"?[n]:n}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let n=this._items[0];return n===""||n==='""'}get str(){var n;return(n=this._str)!==null&&n!==void 0?n:this._str=this._items.reduce((i,r)=>`${i}${r}`,"")}get names(){var n;return(n=this._names)!==null&&n!==void 0?n:this._names=this._items.reduce((i,r)=>{if(r instanceof Jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}kD._Code=ci;kD.nil=new ci("");function AD(n,...i){let r=[n[0]],o=0;while(o<i.length)jc(r,i[o]),r.push(n[++o]);return new ci(r)}kD._=AD;var Gc=new ci("+");function OD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(Gc),jc(r,i[o]),r.push(Gc,so(n[++o]));return mJ(r),new ci(r)}kD.str=OD;function jc(n,i){if(i instanceof ci)n.push(...i._items);else if(i instanceof Jr)n.push(i);else n.push(zJ(i))}kD.addCodeArg=jc;function mJ(n){let i=1;while(i<n.length-1){if(n[i]===Gc){let r=ZJ(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function ZJ(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Jr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof Jr))return`"${n}${i.slice(1)}`;return}function MJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:OD`${n}${i}`}kD.strConcat=MJ;function zJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function CJ(n){return new ci(so(n))}kD.stringify=CJ;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}kD.safeStringify=so;function RJ(n){return typeof n=="string"&&kD.IDENTIFIER.test(n)?new ci(`.${n}`):AD`[${n}]`}kD.getProperty=RJ;function xJ(n){if(typeof n=="string"&&kD.IDENTIFIER.test(n))return new ci(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}kD.getEsmExportName=xJ;function aJ(n){return new ci(n.toString())}kD.regexpCode=aJ});var Xc=P((yD)=>{Object.defineProperty(yD,"__esModule",{value:!0});yD.ValueScope=yD.ValueScopeName=yD.Scope=yD.varKinds=yD.UsedValueState=void 0;var an=ne();class LD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var Kl;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(Kl||(yD.UsedValueState=Kl={}));yD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Jc{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof an.Name?n:this.name(n)}name(n){return new an.Name(this._newName(n))}_newName(n){let i=this._names[n]||this._nameGroup(n);return`${n}${i.index++}`}_nameGroup(n){var i,r;if(((r=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||r===void 0?void 0:r.has(n))||this._prefixes&&!this._prefixes.has(n))throw Error(`CodeGen: prefix "${n}" is not allowed in this scope`);return this._names[n]={prefix:n,index:0}}}yD.Scope=Jc;class Hc extends an.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=an._`.${new an.Name(i)}[${r}]`}}yD.ValueScopeName=Hc;var g8=an._`\n`;class ND extends Jc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?g8:an.nil}}get(){return this._scope}name(n){return new Hc(n,this._newName(n))}value(n,i){var r;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(n),{prefix:t}=o,e=(r=i.key)!==null&&r!==void 0?r:i.ref,u=this._values[t];if(u){let I=u.get(e);if(I)return I}else u=this._values[t]=newLine truncated
`:""},this._extScope=n,this._scope=new Ui.Scope({parent:n}),this._nodes=[new PD]}toString(){return this._root.render(this.opts)}name(n){return this._scope.name(n)}scopeName(n){return this._extScope.name(n)}scopeValue(n,i){let r=this._extScope.value(n,i);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(n,i){return this._extScope.getValue(n,i)}scopeRefs(n){return this._extScope.scopeRefs(n,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(n,i,r,o){let t=this._scope.toName(i);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new jD(n,t,r)),t}const(n,i,r){return this._def(Ui.varKinds.const,n,i,r)}let(n,i,r){return this._def(Ui.varKinds.let,n,i,r)}var(n,i,r){return this._def(Ui.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Yc(n,i,r))}add(n,i){return this._leafNode(new WD(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new hD(n));return this}object(...n){let i=["{"];for(let[r,o]of n){if(i.length>1)i.push(",");if(i.push(r),r!==o||this.opts.es5)i.push(":"),(0,s.addCodeArg)(i,o)}return i.push("}"),new s._Code(i)}if(n,i,r){if(this._blockNode(new Vi(n)),i&&r)this.code(i).else().code(r).endIf();else if(i)this.code(i).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(n){return this._elseNode(new Vi(n))}else(){return this._elseNode(new ie)}endIf(){return this._endBlockNode(Vi,ie)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new YD(n),i)}forRange(n,i,r,o,t=this.opts.es5?Ui.varKinds.var:Ui.varKinds.let){let e=this._scope.toName(n);return this._for(new pD(t,e,i,r),()=>o(e))}forOf(n,i,r,o=Ui.varKinds.const){let t=this._scope.toName(n);if(this.opts.es5){let e=i instanceof s.Name?i:this.var("_arr",i);return this.forRange("_i",0,s._`${e}.length`,(u)=>{this.var(t,s._`${e}[${u}]`),r(t)})}return this._for(new hc("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?Ui.varKinds.var:Ui.varKinds.const){if(this.opts.ownProperties)return this.forOf(n,s._`Object.keys(${i})`,r);let t=this._scope.toName(n);return this._for(new hc("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Hr)}label(n){return this._leafNode(new JD(n))}break(n){return this._leafNode(new HD(n))}return(n){let i=new Vl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Vl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new QD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Tl(t),i(t)}if(r)this._currNode=o.finally=new ql,this.code(r);return this._endBlockNode(Tl,ql)}throw(n){return this._leafNode(new XD(n))}block(n,i){if(this._blockStarts.push(this._nodes.length),n)this.code(n).endBlock(i);return this}endBlock(n){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-i;if(r<0||n!==void 0&&r!==n)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${n} expected`);return this._nodes.length=i,this}func(n,i=s.nil,r,o){if(this._blockNode(new Bl(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Bl)}optimize(n=1){while(n-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(n){return this._currNode.nodes.push(n),this}_blockNode(n){this._currNode.nodes.push(n),this._nodes.push(n)}_endBlockNode(n,i){let r=this._currNode;if(r instanceof n||i&&r instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${n.kind}/${i.kind}`:n.kind}"`)}_elseNode(n){let i=this._currNode;if(!(i instanceof Vi))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=n,this}get _root(){return this._nodes[0]}get _currNode(){let n=this._nodes;return n[n.length-1]}set _currNode(n){let i=this._nodes;i[i.length-1]=n}}sn.CodeGen=FD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function _l(n,i){return i instanceof s._CodeOrName?Xt(n,i.names):n}function Xr(n,i,r){if(n instanceof s.Name)return o(n);if(!t(n))return n;return new s._Code(n._items.reduce((e,u)=>{if(u instanceof s.Name)u=o(u);if(u instanceof s._Code)e.push(...u._items);else e.push(u);return e},[]));function o(e){let u=r[e.str];if(u===void 0||i[e.str]!==1)return e;return delete i[e.str],u}function t(e){return e instanceof s._Code&&e._items.some((u)=>u instanceof s.Name&&i[u.str]===1&&r[u.str]!==void 0)}}function c8(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function KD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Pc(n)}`}sn.not=KD;var U8=BD(sn.operators.AND);function D8(...n){return n.reduce(U8)}sn.and=D8;var S8=BD(sn.operators.OR);function A8(...n){return n.reduce(S8)}sn.or=A8;function BD(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${Pc(i)} ${n} ${Pc(r)}`}function Pc(n){return n instanceof s.Name?n:s._`(${n})`}});var nn=P((zD)=>{Object Line truncated
|| (${u} == "string" && ${t} && ${t} == +${t})`).assign(l,Z._`+${t}`);return;case"integer":o.elseIf(Z._`${u} === "boolean" || ${t} === null
|| (${u} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,Z._`+${t}`);return;case"boolean":o.elseIf(Z._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(Z._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(Z._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(Z._`${u} === "string" || ${u} === "number"
|| ${u} === "boolean" || ${t} === null`).assign(l,Z._`[${t}]`)}}}function hH({gen:n,parentData:i,parentDataProperty:r},o){n.if(Z._`${i} !== undefined`,()=>n.assign(Z._`${i}[${r}]`,o))}function Tc(n,i,r,o=hr.Correct){let t=o===hr.Correct?Z.operators.EQ:Z.operators.NEQ,e;switch(n){case"null":return Z._`${i} ${t} null`;case"array":e=Z._`Array.isArray(${i})`;break;case"object":e=Z._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":e=u(Z._`!(${i} % 1) && !isNaN(${i})`);break;case"number":e=u();break;default:return Z._`typeof ${i} ${t} ${n}`}return o===hr.Correct?e:(0,Z.not)(e);function u(l=Z.nil){return(0,Z.and)(Z._`typeof ${i} == "number"`,l,r?Z._`isFinite(${i})`:Z.nil)}}c1.checkDataType=Tc;function qc(n,i,r,o){if(n.length===1)return Tc(n[0],i,r,o);let t,e=(0,b1.toHash)(n);if(e.array&&e.object){let u=Z._`typeof ${i} != "object"`;t=e.null?u:Z._`!${i} || ${u}`,delete e.null,delete e.array,delete e.object}else t=Z.nil;if(e.number)delete e.integer;for(let u in e)t=(0,Z.and)(t,Tc(u,i,r,o));return t}c1.checkDataTypes=qc;var PH={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?Z._`{type: ${n}}`:Z._`{type: ${i}}`};function _c(n){let i=YH(n);(0,jH.reportError)(i,PH)}c1.reportTypeError=_c;function YH(n){let{gen:i,data:r,schema:o}=n,t=(0,b1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var O1=P((S1)=>{Object.defineProperty(S1,"__esModule",{value:!0});S1.assignDefaults=void 0;var Pr=M(),TH=nn();function qH(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)D1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,e)=>D1(n,e,t.default))}S1.assignDefaults=qH;function D1(n,i,r){let{gen:o,compositeRule:t,data:e,opts:u}=n;if(r===void 0)return;let l=Pr._`${e}${(0,Pr.getProperty)(i)}`;if(t){(0,TH.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Pr._`${l} === undefined`;if(u.useDefaults==="empty")$=Pr._`${$} || ${l} === null || ${l} === ""`;o.if($,Pr._`${l} = ${(0,Pr.stringify)(r)}`)}});var Ii=P((L1)=>{Object.defineProperty(L1,"__esModule",{value:!0});L1.validateUnion=L1.validateArray=L1.usePattern=L1.callValidateCode=L1.schemaProperties=L1.allSchemaProperties=L1.noPropertyInData=L1.propertyInData=L1.isOwnProperty=L1.hasPropFunc=L1.reportMissingProp=L1.checkMissingProp=L1.checkReportMissingProp=void 0;var Sn=M(),Ec=nn(),gt=Ti(),_H=nn();function EH(n,i){let{gen:r,data:o,it:t}=n;r.if(Zc(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Sn._`${i}`},!0),n.error()})}L1.checkReportMissingProp=EH;function mH({gen:n,data:i,it:{opts:r}},o,t){return(0,Sn.or)(...o.map((e)=>(0,Sn.and)(Zc(n,i,e,r.ownProperties),Sn._`${t} = ${e}`)))}L1.checkMissingProp=mH;function ZH(n,i){n.setParams({missingProperty:i},!0),n.error()}L1.reportMissingProp=ZH;function k1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Sn._`Object.prototype.hasOwnProperty`})}L1.hasPropFunc=k1;function mc(n,i,r){return Sn._`${k1(n)}.call(${i}, ${r})`}L1.isOwnProperty=mc;function MH(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} !== undefined`;return o?Sn._`${t} && ${mc(n,i,r)}`:t}L1.propertyInData=MH;function Zc(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} === undefined`;return o?(0,Sn.or)(t,(0,Sn.not)(mc(n,i,r))):t}L1.noPropertyInData=Zc;function d1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}L1.allSchemaProperties=d1;function zH(n,i){return d1(i).filter((r)=>!(0,Ec.alwaysValidSchema)(n,i[r]))}L1.schemaProperties=zH;function CH({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:e},it:u},l,$,I){let g=I?Sn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Sn.strConcat)(gt.default.instancePath,e)],[gt.default.parentData,u.parentData],[gt.default.parentDataProperty,u.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(u.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let w=Sn._`${g}, ${r.object(...b)}`;return $!==Sn.nil?Sn._`${l}.call(${$}, ${w})`:Sn._`${l}(${w})`}L1.callValidateCode=CH;var RH=Sn._`new RegExp`;function xH({gen:n,it:{opts:i}},r){let o=i.unicodeRegExp?"u":"",{regExp:t}=i.code,e=t(r,o);return n.scopeValue("pattern",{key:e.toString(),ref:e,code:Sn._`${t.code==="new RegExp"?RH:(0,_H.useFunc)(n,t)}(${r}, ${o})`})}L1.usePattern=xH;function aH(n){let{gen:i,data:r,keyword:o,it:t}=n,e=i.name("valid");if(t.allErrors){let l=i.let("valid",!0);return u(()=>i.assign(l,!1)),l}return i.var(e,!0),u(()=>i.break()),e;function u(l){let $=i.const("len",Sn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:Ec.Type.Num},e),i.if((0,Sn.not)(e),l)})}}L1.validateArray=aH;function sH(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,Ec.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let u=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
missingProperty: ${o},
depsCount: ${i},
deps: ${r}}`};var SY={keyword:"dependencies",type:"object",schemaType:"object",error:VA.error,code(n){let[i,r]=AY(n);KA(n,i),BA(n,r)}};function AY({schema:n}){let i={},r={};for(let o in n){if(o==="__proto__")continue;let t=Array.isArray(n[o])?i:r;t[o]=n[o]}return[i,r]}function KA(n,i=n.schema){let{gen:r,data:o,it:t}=n;if(Object.keys(i).length===0)return;let e=r.let("missing");for(let u in i){let l=i[u];if(l.length===0)continue;let $=(0,Ae.propertyInData)(r,o,u,t.opts.ownProperties);if(n.setParams({property:u,depsCount:l.length,deps:l.join(", ")}),t.allErrors)r.if($,()=>{for(let I of l)(0,Ae.checkReportMissingProp)(n,I)});else r.if(c6._`${$} && (${(0,Ae.checkMissingProp)(n,l,e)})`),(0,Ae.reportMissingProp)(n,e),r.else()}}VA.validatePropertyDeps=KA;function BA(n,i=n.schema){let{gen:r,data:o,keyword:t,it:e}=n,u=r.name("valid");for(let l in i){if((0,DY.alwaysValidSchema)(e,i[l]))continue;r.if((0,Ae.propertyInData)(r,o,l,e.opts.ownProperties),()=>{let $=n.subschema({keyword:t,schemaProp:l},u);n.mergeValidEvaluated($,u)},()=>r.var(u,!0)),n.ok(u)}}VA.validateSchemaDeps=BA;VA.default=SY});var mA=P((ZA)=>{Object.defineProperty(ZA,"__esModule",{value:!0});var EA=M(),dY=nn(),LY={message:"property name must be valid",params:({params:n})=>EA._`{propertyName: ${n.propertyName}}`},NY={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:LY,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,dY.alwaysValidSchema)(t,r))return;let e=i.name("valid");i.forIn("key",o,(u)=>{n.setParams({propertyName:u}),n.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},e),i.if((0,EA.not)(e),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(e)}};ZA.default=NY});var U6=P((MA)=>{Object.defineProperty(MA,"__esModule",{value:!0});var gv=Ii(),Ai=M(),GY=Ti(),bv=nn(),jY={message:"must NOT have additional properties",params:({params:n})=>Ai._`{additionalProperty: ${n.additionalProperty}}`},WY={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jY,code(n){let{gen:i,schema:r,parentSchema:o,data:t,errsCount:e,it:u}=n;if(!e)throw Error("ajv implementation error");let{allErrors:l,opts:$}=u;if(u.props=!0,$.removeAdditional!=="all"&&(0,bv.alwaysValidSchema)(u,r))return;let I=(0,gv.allSchemaProperties)(o.properties),g=(0,gv.allSchemaProperties)(o.patternProperties);b(),n.ok(Ai._`${e} === ${GY.default.errors}`);function b(){i.forIn("key",t,(k)=>{if(!I.length&&!g.length)c(k);else i.if(w(k),()=>c(k))})}function w(k){let d;if(I.length>8){let p=(0,bv.schemaRefOrVal)(u,o.properties,"properties");d=(0,gv.isOwnProperty)(i,p,k)}else if(I.length)d=(0,Ai.or)(...I.map((p)=>Ai._`${k} === ${p}`));else d=Ai.nil;if(g.length)d=(0,Ai.or)(d,...g.map((p)=>Ai._`${(0,gv.usePattern)(n,p)}.test(${k})`));return(0,Ai.not)(d)}function f(k){i.code(Ai._`delete ${t}[${k}]`)}function c(k){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(k);return}if(r===!1){if(n.setParams({additionalProperty:k}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,bv.alwaysValidSchema)(u,r)){let d=i.name("valid");if($.removeAdditional==="failing")S(k,d,!1),i.if((0,Ai.not)(d),()=>{n.reset(),f(k)});else if(S(k,d),!l)i.if((0,Ai.not)(d),()=>i.break())}}function S(k,d,p){let h={keyword:"additionalProperties",dataProp:k,dataPropType:bv.Type.Str};if(p===!1)Object.assign(h,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(h,d)}}};MA.default=WY});var xA=P((RA)=>{Object.defineProperty(RA,"__esModule",{value:!0});var HY=le(),zA=Ii(),D6=nn(),CA=U6(),XY={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,parentSchema:o,data:t,it:e}=n;if(e.opts.removeAdditional==="all"&&o.additionalProperties===void 0)CA.default.code(new HY.KeywordCxt(e,CA.default,"additionalProperties"));let u=(0,zA.allSchemaProperties)(r);for(let b of u)e.definedProperties.add(b);if(e.opts.unevaluated&&u.length&&e.props!==!0)e.props=D6.mergeEvaluated.props(i,(0,D6.toHash)(u),e.props);let l=u.filter((b)=>!(0,D6.alwaysValidSchema)(e,r[b]));if(l.length===0)return;let $=i.name("valid");for(let b of l){if(I(b))g(b);else{if(i.if((0,zA.propertyInData)(i,t,b,e.opts.ownProperties)),g(b),!e.allErrors)i.else().var($,!0);i.endIf()}n.it.definedProperties.add(b),n.ok($)}function I(b){return e.opts.useDefaults&&!e.compositeRule&&r[b].default!==void 0}function g(b){n.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};RA.default=XY});var tO=P((iO)=>{Object.defineProperty(iO,"__esModule",{value:!0});var aA=Ii(),wv=M(),sA=nn(),nO=nn(),PY={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,data:o,parentSchema:t,it:e}=n,{opts:u}=e,l=(0,aA.allSchemaProperties)(r),$=l.filter((S)=>(0,sA.alwaysValidSchema)(e,r[S]));if(l.length===0||$.length===l.length&&(!e.opts.unevaluated||e.props===!0))return;let I=u.strictSchema&&!u.allowMatchingProperties&&t.properties,g=i.name("valid");if(e.props!==!0&&!(e.props instanceof wv.Name))e.props=(0,nO. Line truncated
`)}var Ct=(n)=>(i,r,o,t)=>{let e=o?{...o,async:!1}:{async:!1},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)throw new Ni;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},Io=Ct(Rn),Rt=(n)=>async(i,r,o,t)=>{let e=o?{...o,async:!0}:{async:!0},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)u=await u;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},go=Rt(Rn),xt=(n)=>(i,r,o)=>{let t=o?{...o,async:!1}:{async:!1},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)throw new Ni;return e.issues.length?{success:!1,error:new(n??lo)(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},at=xt(Rn),st=(n)=>async(i,r,o)=>{let t=o?{...o,async:!0}:{async:!0},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)e=await e;return e.issues.length?{success:!1,error:new n(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},bo=st(Rn),ze=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Ct(n)(i,r,t)},n0=ze(Rn),Ce=(n)=>(i,r,o)=>{return Ct(n)(i,r,o)},i0=Ce(Rn),Re=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},t0=Re(Rn),xe=(n)=>async(i,r,o)=>{return Rt(n)(i,r,o)},r0=xe(Rn),ae=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return xt(n)(i,r,t)},o0=ae(Rn),se=(n)=>(i,r,o)=>{return xt(n)(i,r,o)},e0=se(Rn),nu=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return st(n)(i,r,t)},u0=nu(Rn),iu=(n)=>async(i,r,o)=>{return st(n)(i,r,o)},l0=iu(Rn);var oi={};pi(oi,{xid:()=>X$,uuid7:()=>nG,uuid6:()=>sy,uuid4:()=>ay,uuid:()=>yt,uppercase:()=>tI,unicodeEmail:()=>v0,undefined:()=>nI,ulid:()=>H$,time:()=>M$,string:()=>C$,sha512_hex:()=>kG,sha512_base64url:()=>LG,sha512_base64:()=>dG,sha384_hex:()=>SG,sha384_base64url:()=>OG,sha384_base64:()=>AG,sha256_hex:()=>cG,sha256_base64url:()=>DG,sha256_base64:()=>UG,sha1_hex:()=>bG,sha1_base64url:()=>fG,sha1_base64:()=>wG,rfc5322Email:()=>tG,number:()=>wo,null:()=>s$,nanoid:()=>P$,md5_hex:()=>$G,md5_base64url:()=>gG,md5_base64:()=>IG,mac:()=>V$,lowercase:()=>iI,ksuid:()=>h$,ipv6:()=>B$,ipv4:()=>K$,integer:()=>x$,idnEmail:()=>rG,httpProtocol:()=>E$,html5Email:()=>iG,hostname:()=>uG,hex:()=>vG,guid:()=>p$,extendedDuration:()=>xy,emoji:()=>F$,email:()=>Q$,e164:()=>Z$,duration:()=>Y$,domain:()=>lG,datetime:()=>z$,date:()=>m$,cuid2:()=>J$,cuid:()=>W$,cidrv6:()=>q$,cidrv4:()=>T$,browserEmail:()=>oG,boolean:()=>a$,bigint:()=>R$,base64url:()=>tu,base64:()=>_$});var W$=/^[cC][0-9a-z]{6,}$/,J$=/^[0-9a-z]+$/,H$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X$=/^[0-9a-vA-V]{20}$/,h$=/^[A-Za-z0-9]{27}$/,P$=/^[a-zA-Z0-9_-]{21}$/,Y$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,p$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yt=(n)=>{if(!n)return/^([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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},ay=yt(4),sy=yt(6),nG=yt(7),Q$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,tG=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,v0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,rG=v0,oG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,eG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function F$(){return new RegExp(eG,"u")}var K$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,V$=(n)=>{let i=li(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},T$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
deps: ${r}}`};var SY={keyword:"dependencies",type:"object",schemaType:"object",error:VA.error,code(n){let[i,r]=AY(n);KA(n,i),BA(n,r)}};function AY({schema:n}){let i={},r={};for(let o in n){if(o==="__proto__")continue;let t=Array.isArray(n[o])?i:r;t[o]=n[o]}return[i,r]}function KA(n,i=n.schema){let{gen:r,data:o,it:t}=n;if(Object.keys(i).length===0)return;let e=r.let("missing");for(let u in i){let l=i[u];if(l.length===0)continue;let $=(0,Ae.propertyInData)(r,o,u,t.opts.ownProperties);if(n.setParams({property:u,depsCount:l.length,deps:l.join(", ")}),t.allErrors)r.if($,()=>{for(let I of l)(0,Ae.checkReportMissingProp)(n,I)});else r.if(c6._`${$} && (${(0,Ae.checkMissingProp)(n,l,e)})`),(0,Ae.reportMissingProp)(n,e),r.else()}}VA.validatePropertyDeps=KA;function BA(n,i=n.schema){let{gen:r,data:o,keyword:t,it:e}=n,u=r.name("valid");for(let l in i){if((0,DY.alwaysValidSchema)(e,i[l]))continue;r.if((0,Ae.propertyInData)(r,o,l,e.opts.ownProperties),()=>{let $=n.subschema({keyword:t,schemaProp:l},u);n.mergeValidEvaluated($,u)},()=>r.var(u,!0)),n.ok(u)}}VA.validateSchemaDeps=BA;VA.default=SY});var ZA=P((mA)=>{Object.defineProperty(mA,"__esModule",{value:!0});var EA=M(),dY=nn(),LY={message:"property name must be valid",params:({params:n})=>EA._`{propertyName: ${n.propertyName}}`},NY={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:LY,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,dY.alwaysValidSchema)(t,r))return;let e=i.name("valid");i.forIn("key",o,(u)=>{n.setParams({propertyName:u}),n.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},e),i.if((0,EA.not)(e),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(e)}};mA.default=NY});var U6=P((MA)=>{Object.defineProperty(MA,"__esModule",{value:!0});var gv=Ii(),Ai=M(),GY=Ti(),bv=nn(),jY={message:"must NOT have additional properties",params:({params:n})=>Ai._`{additionalProperty: ${n.additionalProperty}}`},WY={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jY,code(n){let{gen:i,schema:r,parentSchema:o,data:t,errsCount:e,it:u}=n;if(!e)throw Error("ajv implementation error");let{allErrors:l,opts:$}=u;if(u.props=!0,$.removeAdditional!=="all"&&(0,bv.alwaysValidSchema)(u,r))return;let I=(0,gv.allSchemaProperties)(o.properties),g=(0,gv.allSchemaProperties)(o.patternProperties);b(),n.ok(Ai._`${e} === ${GY.default.errors}`);function b(){i.forIn("key",t,(k)=>{if(!I.length&&!g.length)c(k);else i.if(w(k),()=>c(k))})}function w(k){let d;if(I.length>8){let p=(0,bv.schemaRefOrVal)(u,o.properties,"properties");d=(0,gv.isOwnProperty)(i,p,k)}else if(I.length)d=(0,Ai.or)(...I.map((p)=>Ai._`${k} === ${p}`));else d=Ai.nil;if(g.length)d=(0,Ai.or)(d,...g.map((p)=>Ai._`${(0,gv.usePattern)(n,p)}.test(${k})`));return(0,Ai.not)(d)}function f(k){i.code(Ai._`delete ${t}[${k}]`)}function c(k){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(k);return}if(r===!1){if(n.setParams({additionalProperty:k}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,bv.alwaysValidSchema)(u,r)){let d=i.name("valid");if($.removeAdditional==="failing")S(k,d,!1),i.if((0,Ai.not)(d),()=>{n.reset(),f(k)});else if(S(k,d),!l)i.if((0,Ai.not)(d),()=>i.break())}}function S(k,d,p){let h={keyword:"additionalProperties",dataProp:k,dataPropType:bv.Type.Str};if(p===!1)Object.assign(h,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(h,d)}}};MA.default=WY});var xA=P((RA)=>{Object.defineProperty(RA,"__esModule",{value:!0});var HY=le(),zA=Ii(),D6=nn(),CA=U6(),XY={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,parentSchema:o,data:t,it:e}=n;if(e.opts.removeAdditional==="all"&&o.additionalProperties===void 0)CA.default.code(new HY.KeywordCxt(e,CA.default,"additionalProperties"));let u=(0,zA.allSchemaProperties)(r);for(let b of u)e.definedProperties.add(b);if(e.opts.unevaluated&&u.length&&e.props!==!0)e.props=D6.mergeEvaluated.props(i,(0,D6.toHash)(u),e.props);let l=u.filter((b)=>!(0,D6.alwaysValidSchema)(e,r[b]));if(l.length===0)return;let $=i.name("valid");for(let b of l){if(I(b))g(b);else{if(i.if((0,zA.propertyInData)(i,t,b,e.opts.ownProperties)),g(b),!e.allErrors)i.else().var($,!0);i.endIf()}n.it.definedProperties.add(b),n.ok($)}function I(b){return e.opts.useDefaults&&!e.compositeRule&&r[b].default!==void 0}function g(b){n.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};RA.default=XY});var tO=P((iO)=>{Object.defineProperty(iO,"__esModule",{value:!0});var aA=Ii(),wv=M(),sA=nn(),nO=nn(),PY={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,data:o,parentSchema:t,it:e}=n,{opts:u}=e,l=(0,aA.allSchemaProperties)(r),$=l.filter((S)=>(0,sA.alwaysValidSchema)(e,r[S]));if(l.length===0||$.length===l.length&&(!e.opts.unevaluated||e.props===!0))return;let I=u.strictSchema&&!u.allowMatchingProperties&&t.properties,g=i.name("valid");if(e.props!==!0&&!(e.props instanceof wv.Name))e.props=(0,nO. Line truncated
`)}var Ct=(n)=>(i,r,o,t)=>{let e=o?{...o,async:!1}:{async:!1},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)throw new Ni;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},Io=Ct(Rn),Rt=(n)=>async(i,r,o,t)=>{let e=o?{...o,async:!0}:{async:!0},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)u=await u;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},go=Rt(Rn),xt=(n)=>(i,r,o)=>{let t=o?{...o,async:!1}:{async:!1},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)throw new Ni;return e.issues.length?{success:!1,error:new(n??lo)(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},at=xt(Rn),st=(n)=>async(i,r,o)=>{let t=o?{...o,async:!0}:{async:!0},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)e=await e;return e.issues.length?{success:!1,error:new n(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},bo=st(Rn),ze=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Ct(n)(i,r,t)},n0=ze(Rn),Ce=(n)=>(i,r,o)=>{return Ct(n)(i,r,o)},i0=Ce(Rn),Re=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},t0=Re(Rn),xe=(n)=>async(i,r,o)=>{return Rt(n)(i,r,o)},r0=xe(Rn),ae=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return xt(n)(i,r,t)},o0=ae(Rn),se=(n)=>(i,r,o)=>{return xt(n)(i,r,o)},e0=se(Rn),nu=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return st(n)(i,r,t)},u0=nu(Rn),iu=(n)=>async(i,r,o)=>{return st(n)(i,r,o)},l0=iu(Rn);var oi={};pi(oi,{xid:()=>X$,uuid7:()=>nG,uuid6:()=>sy,uuid4:()=>ay,uuid:()=>yt,uppercase:()=>tI,unicodeEmail:()=>v0,undefined:()=>nI,ulid:()=>H$,time:()=>M$,string:()=>C$,sha512_hex:()=>kG,sha512_base64url:()=>LG,sha512_base64:()=>dG,sha384_hex:()=>SG,sha384_base64url:()=>OG,sha384_base64:()=>AG,sha256_hex:()=>cG,sha256_base64url:()=>DG,sha256_base64:()=>UG,sha1_hex:()=>bG,sha1_base64url:()=>fG,sha1_base64:()=>wG,rfc5322Email:()=>tG,number:()=>wo,null:()=>s$,nanoid:()=>P$,md5_hex:()=>$G,md5_base64url:()=>gG,md5_base64:()=>IG,mac:()=>V$,lowercase:()=>iI,ksuid:()=>h$,ipv6:()=>B$,ipv4:()=>K$,integer:()=>x$,idnEmail:()=>rG,httpProtocol:()=>E$,html5Email:()=>iG,hostname:()=>uG,hex:()=>vG,guid:()=>p$,extendedDuration:()=>xy,emoji:()=>F$,email:()=>Q$,e164:()=>m$,duration:()=>Y$,domain:()=>lG,datetime:()=>z$,date:()=>Z$,cuid2:()=>J$,cuid:()=>W$,cidrv6:()=>q$,cidrv4:()=>T$,browserEmail:()=>oG,boolean:()=>a$,bigint:()=>R$,base64url:()=>tu,base64:()=>_$});var W$=/^[cC][0-9a-z]{6,}$/,J$=/^[0-9a-z]+$/,H$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X$=/^[0-9a-vA-V]{20}$/,h$=/^[A-Za-z0-9]{27}$/,P$=/^[a-zA-Z0-9_-]{21}$/,Y$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,p$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yt=(n)=>{if(!n)return/^([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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},ay=yt(4),sy=yt(6),nG=yt(7),Q$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,tG=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,v0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,rG=v0,oG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,eG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function F$(){return new RegExp(eG,"u")}var K$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,V$=(n)=>{let i=li(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},T$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((e)=>e),o=Math.min(...r.map((e)=>e.length-e.trimStart().length)),t=r.map((e)=>e.slice(o)).map((e)=>" ".repeat(this.indent*2)+e);for(let e of t)this.content.push(e)}compile(){let n=Function,i=this?.args,o=[...(this?.content??[""]).map((t)=>` ${t}`)];return new n(...i,o.join(`
`))}}var kI={major:4,minor:4,patch:3};var B=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=kI;let o=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))o.unshift(n);for(let t of o)for(let e of t._zod.onattach)e(n);if(o.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let t=(u,l,$)=>{let I=ai(u),g;for(let b of l){if(b._zod.def.when){if(y$(u))continue;if(!b._zod.def.when(u))continue}else if(I)continue;let w=u.issues.length,f=b._zod.check(u);if(f instanceof Promise&&$?.async===!1)throw new Ni;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,u.issues.length===w)return;if(!I)I=ai(u,w)});else{if(u.issues.length===w)continue;if(!I)I=ai(u,w)}}if(g)return g.then(()=>{return u});return u},e=(u,l,$)=>{if(ai(u))return u.aborted=!0,u;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Ni;return I.then((g)=>n._zod.parse(g,$))}return n._zod.parse(I,$)};n._zod.run=(u,l)=>{if(l.skipChecks)return n._zod.parse(u,l);if(l.direction==="backward"){let I=n._zod.parse({value:u.value,issues:[]},{...l,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return e(g,u,l)});return e(I,u,l)}let $=n._zod.parse(u,l);if($ instanceof Promise){if(l.async===!1)throw new Ni;return $.then((I)=>t(I,o,l))}return t($,o,l)}}z(n,"~standard",()=>({validate:(t)=>{try{let e=at(n,t);return e.success?{value:e.data}:{issues:e.error?.issues}}catch(e){return bo(n,t).then((u)=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Gt=U("$ZodString",(n,i)=>{B.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??C$(n._zod.bag),n._zod.parse=(r,o)=>{if(i.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),$n=U("$ZodStringFormat",(n,i)=>{nr.init(n,i),Gt.init(n,i)}),LI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=p$),$n.init(n,i)}),NI=U("$ZodUUID",(n,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=yt(o))}else i.pattern??(i.pattern=yt());$n.init(n,i)}),yI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=Q$),$n.init(n,i)}),GI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===E$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:n,continue:!i.abort});return}}let t=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:r.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:r.value,inst:n,continue:!i.abort})}if(i.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!i.abort})}}}),jI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=F$()),$n.init(n,i)}),WI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),JI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=W$),$n.init(n,i)}),HI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=J$),$n.init(n,i)}),XI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=H$),$n.init(n,i)}),hI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=X$),$n.init(n,i)}),PI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=h$),$n.init(n,i)}),YI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=z$(i)),$n.init(n,i)}),pI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=m$),$n.init(n,i)}),QI=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=M$(i)),$n.init(n,i)}),FI=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=Y$),$n.init(n,i)}),KI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i),n._zod.bag.format="ipv4"}),BI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!i.abort})}}}),VI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=V$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),TI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),qI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i),n._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,e]=o;if(!e)throw Error();let u=Number(e);if(`${u}`!==e)throw Error();if(u<0||u>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!i.abort})}}});function _I(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Line truncated
`))}}var kI={major:4,minor:4,patch:3};var B=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=kI;let o=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))o.unshift(n);for(let t of o)for(let e of t._zod.onattach)e(n);if(o.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let t=(u,l,$)=>{let I=ai(u),g;for(let b of l){if(b._zod.def.when){if(y$(u))continue;if(!b._zod.def.when(u))continue}else if(I)continue;let w=u.issues.length,f=b._zod.check(u);if(f instanceof Promise&&$?.async===!1)throw new Ni;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,u.issues.length===w)return;if(!I)I=ai(u,w)});else{if(u.issues.length===w)continue;if(!I)I=ai(u,w)}}if(g)return g.then(()=>{return u});return u},e=(u,l,$)=>{if(ai(u))return u.aborted=!0,u;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Ni;return I.then((g)=>n._zod.parse(g,$))}return n._zod.parse(I,$)};n._zod.run=(u,l)=>{if(l.skipChecks)return n._zod.parse(u,l);if(l.direction==="backward"){let I=n._zod.parse({value:u.value,issues:[]},{...l,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return e(g,u,l)});return e(I,u,l)}let $=n._zod.parse(u,l);if($ instanceof Promise){if(l.async===!1)throw new Ni;return $.then((I)=>t(I,o,l))}return t($,o,l)}}z(n,"~standard",()=>({validate:(t)=>{try{let e=at(n,t);return e.success?{value:e.data}:{issues:e.error?.issues}}catch(e){return bo(n,t).then((u)=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Gt=U("$ZodString",(n,i)=>{B.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??C$(n._zod.bag),n._zod.parse=(r,o)=>{if(i.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),$n=U("$ZodStringFormat",(n,i)=>{nr.init(n,i),Gt.init(n,i)}),LI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=p$),$n.init(n,i)}),NI=U("$ZodUUID",(n,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=yt(o))}else i.pattern??(i.pattern=yt());$n.init(n,i)}),yI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=Q$),$n.init(n,i)}),GI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===E$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:n,continue:!i.abort});return}}let t=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:r.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:r.value,inst:n,continue:!i.abort})}if(i.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!i.abort})}}}),jI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=F$()),$n.init(n,i)}),WI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),JI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=W$),$n.init(n,i)}),HI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=J$),$n.init(n,i)}),XI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=H$),$n.init(n,i)}),hI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=X$),$n.init(n,i)}),PI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=h$),$n.init(n,i)}),YI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=z$(i)),$n.init(n,i)}),pI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=Z$),$n.init(n,i)}),QI=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=M$(i)),$n.init(n,i)}),FI=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=Y$),$n.init(n,i)}),KI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i),n._zod.bag.format="ipv4"}),BI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!i.abort})}}}),VI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=V$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),TI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),qI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i),n._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,e]=o;if(!e)throw Error();let u=Number(e);if(`${u}`!==e)throw Error();if(u<0||u>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!i.abort})}}});function _I(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Line truncated
if (${j}.issues.length) {
if (${L} in input) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
@@ -67,13 +67,13 @@ import{createRequire as Ny}from"node:module";var cy=Object.create;var{getPrototy
newResult[${L}] = ${j}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let p=f.compile();return(h,j)=>p(w,h,j)},e,u=Nt,l=!dt.jitless,I=l&&A$.value,g=i.catchall,b;n._zod.parse=(w,f)=>{b??(b=o.value);let c=w.value;if(!u(c))return w.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),w;if(l&&I&&f?.async===!1&&f.jitless!==!0){if(!e)e=t(i.shape);if(w=e(w,f),!g)return w;return X0([],c,w,f,b,n)}return r(w,f)}});function c0(n,i,r,o){for(let e of n)if(e.issues.length===0)return i.value=e.value,i;let t=n.filter((e)=>!ai(e));if(t.length===1)return i.value=t[0].value,t[0];return i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))}),i}var Do=U("$ZodUnion",(n,i)=>{B.init(n,i),z(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),z(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),z(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),z(n._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>ro(t.source)).join("|")})$`)}return});let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else{if($.issues.length===0)return $;u.push($)}}if(!e)return c0(u,o,n,t);return Promise.all(u).then((l)=>{return c0(l,o,n,t)})}});function U0(n,i,r,o){let t=n.filter((e)=>e.issues.length===0);if(t.length===1)return i.value=t[0].value,i;if(t.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var lg=U("$ZodXor",(n,i)=>{Do.init(n,i),i.inclusive=!1;let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else u.push($)}if(!e)return U0(u,o,n,t);return Promise.all(u).then((l)=>{return U0(l,o,n,t)})}}),vg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;z(n._zod,"propValues",()=>{let t={};for(let e of i.options){let u=e._zod.propValues;if(!u||Object.keys(u).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(e)}"`);for(let[l,$]of Object.entries(u)){if(!t[l])t[l]=new Set;for(let I of $)t[l].add(I)}}return t});let o=Mt(()=>{let t=i.options,e=new Map;for(let u of t){let l=u._zod.propValues?.[i.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(u)}"`);for(let $ of l){if(e.has($))throw Error(`Duplicate discriminator value "${String($)}"`);e.set($,u)}}return e});n._zod.parse=(t,e)=>{let u=t.value;if(!Nt(u))return t.issues.push({code:"invalid_type",expected:"object",input:u,inst:n}),t;let l=o.value.get(u?.[i.discriminator]);if(l)return l._zod.run(t,e);if(i.unionFallback||e.direction==="backward")return r(t,e);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:u,path:[i.discriminator],inst:n}),t}}),$g=U("$ZodIntersection",(n,i)=>{B.init(n,i),n._zod.parse=(r,o)=>{let t=r.value,e=i.left._zod.run({value:t,issues:[]},o),u=i.right._zod.run({value:t,issues:[]},o);if(e instanceof Promise||u instanceof Promise)return Promise.all([e,u]).then(([$,I])=>{return D0(r,$,I)});return D0(r,e,u)}});function dI(n,i){if(n===i)return{valid:!0,data:n};if(n instanceof Date&&i instanceof Date&&+n===+i)return{valid:!0,data:n};if(xi(n)&&xi(i)){let r=Object.keys(i),o=Object.keys(n).filter((e)=>r.indexOf(e)!==-1),t={...n,...i};for(let e of o){let u=dI(n[e],i[e]);if(!u.valid)return{valid:!1,mergeErrorPath:[e,...u.mergeErrorPath]};t[e]=u.data}return{valid:!0,data:t}}if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<n.length;o++){let t=n[o],e=i[o],u=dI(t,e);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};r.push(u.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function D0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let e=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(e.length&&t)n.issues.push({...t,keys:e});if(ai(n))return n;let u=dI(i.value,r.value);if(!u.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return n.value=u.data,n}var bu=U("$ZodTuple",(n,i)=>{B.init(n,i Line truncated
`)}f.write("payload.value = newResult;"),f.write("return payload;");let p=f.compile();return(h,j)=>p(w,h,j)},e,u=Nt,l=!dt.jitless,I=l&&A$.value,g=i.catchall,b;n._zod.parse=(w,f)=>{b??(b=o.value);let c=w.value;if(!u(c))return w.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),w;if(l&&I&&f?.async===!1&&f.jitless!==!0){if(!e)e=t(i.shape);if(w=e(w,f),!g)return w;return X0([],c,w,f,b,n)}return r(w,f)}});function c0(n,i,r,o){for(let e of n)if(e.issues.length===0)return i.value=e.value,i;let t=n.filter((e)=>!ai(e));if(t.length===1)return i.value=t[0].value,t[0];return i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))}),i}var Do=U("$ZodUnion",(n,i)=>{B.init(n,i),z(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),z(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),z(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),z(n._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>ro(t.source)).join("|")})$`)}return});let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else{if($.issues.length===0)return $;u.push($)}}if(!e)return c0(u,o,n,t);return Promise.all(u).then((l)=>{return c0(l,o,n,t)})}});function U0(n,i,r,o){let t=n.filter((e)=>e.issues.length===0);if(t.length===1)return i.value=t[0].value,i;if(t.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var lg=U("$ZodXor",(n,i)=>{Do.init(n,i),i.inclusive=!1;let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else u.push($)}if(!e)return U0(u,o,n,t);return Promise.all(u).then((l)=>{return U0(l,o,n,t)})}}),vg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;z(n._zod,"propValues",()=>{let t={};for(let e of i.options){let u=e._zod.propValues;if(!u||Object.keys(u).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(e)}"`);for(let[l,$]of Object.entries(u)){if(!t[l])t[l]=new Set;for(let I of $)t[l].add(I)}}return t});let o=Mt(()=>{let t=i.options,e=new Map;for(let u of t){let l=u._zod.propValues?.[i.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(u)}"`);for(let $ of l){if(e.has($))throw Error(`Duplicate discriminator value "${String($)}"`);e.set($,u)}}return e});n._zod.parse=(t,e)=>{let u=t.value;if(!Nt(u))return t.issues.push({code:"invalid_type",expected:"object",input:u,inst:n}),t;let l=o.value.get(u?.[i.discriminator]);if(l)return l._zod.run(t,e);if(i.unionFallback||e.direction==="backward")return r(t,e);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:u,path:[i.discriminator],inst:n}),t}}),$g=U("$ZodIntersection",(n,i)=>{B.init(n,i),n._zod.parse=(r,o)=>{let t=r.value,e=i.left._zod.run({value:t,issues:[]},o),u=i.right._zod.run({value:t,issues:[]},o);if(e instanceof Promise||u instanceof Promise)return Promise.all([e,u]).then(([$,I])=>{return D0(r,$,I)});return D0(r,e,u)}});function dI(n,i){if(n===i)return{valid:!0,data:n};if(n instanceof Date&&i instanceof Date&&+n===+i)return{valid:!0,data:n};if(xi(n)&&xi(i)){let r=Object.keys(i),o=Object.keys(n).filter((e)=>r.indexOf(e)!==-1),t={...n,...i};for(let e of o){let u=dI(n[e],i[e]);if(!u.valid)return{valid:!1,mergeErrorPath:[e,...u.mergeErrorPath]};t[e]=u.data}return{valid:!0,data:t}}if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<n.length;o++){let t=n[o],e=i[o],u=dI(t,e);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};r.push(u.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function D0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let e=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(e.length&&t)n.issues.push({...t,keys:e});if(ai(n))return n;let u=dI(i.value,r.value);if(!u.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return n.value=u.data,n}var bu=U("$ZodTuple",(n,i)=>{B.init(n,i Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of n.seen.entries()){let l=u[1];if(i===u[0]){e(u);continue}if(n.external){let I=n.external.registry.get(u[0])?.id;if(i!==u[0]&&I){e(u);continue}}if(n.metadataRegistry.get(u[0])?.id){e(u);continue}if(l.cycle){e(u);continue}if(l.count>1){if(n.reused==="ref"){e(u);continue}}}}function rt(n,i){let r=n.seen.get(i);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(l)=>{let $=n.seen.get(l);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=n.seen.get(b),c=f.schema;if(c.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(c);else Object.assign(I,c);if(Object.assign(I,g),l._zod.parent===b)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(!(k in g))delete I[k]}if(c.$ref&&f.def)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(k in f.def&&JSON.stringify(I[k])===JSON.stringify(f.def[k]))delete I[k]}}let w=l._zod.parent;if(w&&w!==b){o(w);let f=n.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in f.def&&JSON.stringify(I[c])===JSON.stringify(f.def[c]))delete I[c]}}}n.override({zodSchema:l,jsonSchema:I,path:$.path??[]})};for(let l of[...n.seen.entries()].reverse())o(l[0]);let t={};if(n.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let l=n.external.registry.get(i)?.id;if(!l)throw Error("Schema is missing an `id` property");t.$id=n.external.uri(l)}Object.assign(t,r.def??r.schema);let e=n.metadataRegistry.get(i)?.id;if(e!==void 0&&t.id===e)delete t.id;let u=n.external?.defs??{};for(let l of n.seen.entries()){let $=l[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;u[$.defId]=$.def}}if(n.external);else if(Object.keys(u).length>0)if(n.target==="draft-2020-12")t.$defs=u;else t.definitions=u;try{let l=JSON.parse(JSON.stringify(t));return Object.defineProperty(l,"~standard",{value:{...i["~standard"],jsonSchema:{input:cr(i,"input",n.processors),output:cr(i,"output",n.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw Error("Error converting schema to JSON.")}}function Zn(n,i){let r=i??{seen:new Set};if(r.seen.has(n))return!1;r.seen.add(n);let o=n._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Zn(o.element,r);if(o.type==="set")return Zn(o.valueType,r);if(o.type==="lazy")return Zn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Zn(o.innerType,r);if(o.type==="intersection")return Zn(o.left,r)||Zn(o.right,r);if(o.type==="record"||o.type==="map")return Zn(o.keyType,r)||Zn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return Zn(o.in,r)||Zn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(Zn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(Zn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(Zn(t,r))return!0;if(o.rest&&Zn(o.rest,r))return!0;return!1}return!1}var cw=(n,i={})=>(r)=>{let o=it({...r,processors:i});return un(n,o),tt(o,n),rt(o,n)},cr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:e}=o??{},u=it({...t??{},target:e,io:i,processors:r});return un(n,u),tt(u,n),rt(u,n)};var Zj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Uw=(n,i,r,o)=>{let t=r;t.type="string";let{minimum:e,maximum:u,format:l,patterns:$,contentEncoding:I}=n._zod.bag;if(typeof e==="number")t.minLength=e;if(typeof u==="number")t.maxLength=u;if(l){if(t.format=Zj[l]??l,t.format==="")delete t.format;if(l==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},Dw=(n,i,r,o)=>{let t=r,{minimum:e,maximum:u,format:l,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=n._zod.bag;if(typeof l==="string"&&l.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(e??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(u??Number.POSITIVE_INFINITY),f=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof e==="number")t.minimum=e;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof u==="number")t.maximum=u;if(typeof $==="number")t.multipleOf=$},Sw=(n,i,r,o)=>{r.type="boolean"},Aw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Ow=(n,i,r,o)=>{if(i.unrepresentable==="Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of n.seen.entries()){let l=u[1];if(i===u[0]){e(u);continue}if(n.external){let I=n.external.registry.get(u[0])?.id;if(i!==u[0]&&I){e(u);continue}}if(n.metadataRegistry.get(u[0])?.id){e(u);continue}if(l.cycle){e(u);continue}if(l.count>1){if(n.reused==="ref"){e(u);continue}}}}function rt(n,i){let r=n.seen.get(i);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(l)=>{let $=n.seen.get(l);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=n.seen.get(b),c=f.schema;if(c.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(c);else Object.assign(I,c);if(Object.assign(I,g),l._zod.parent===b)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(!(k in g))delete I[k]}if(c.$ref&&f.def)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(k in f.def&&JSON.stringify(I[k])===JSON.stringify(f.def[k]))delete I[k]}}let w=l._zod.parent;if(w&&w!==b){o(w);let f=n.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in f.def&&JSON.stringify(I[c])===JSON.stringify(f.def[c]))delete I[c]}}}n.override({zodSchema:l,jsonSchema:I,path:$.path??[]})};for(let l of[...n.seen.entries()].reverse())o(l[0]);let t={};if(n.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let l=n.external.registry.get(i)?.id;if(!l)throw Error("Schema is missing an `id` property");t.$id=n.external.uri(l)}Object.assign(t,r.def??r.schema);let e=n.metadataRegistry.get(i)?.id;if(e!==void 0&&t.id===e)delete t.id;let u=n.external?.defs??{};for(let l of n.seen.entries()){let $=l[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;u[$.defId]=$.def}}if(n.external);else if(Object.keys(u).length>0)if(n.target==="draft-2020-12")t.$defs=u;else t.definitions=u;try{let l=JSON.parse(JSON.stringify(t));return Object.defineProperty(l,"~standard",{value:{...i["~standard"],jsonSchema:{input:cr(i,"input",n.processors),output:cr(i,"output",n.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw Error("Error converting schema to JSON.")}}function mn(n,i){let r=i??{seen:new Set};if(r.seen.has(n))return!1;r.seen.add(n);let o=n._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return mn(o.element,r);if(o.type==="set")return mn(o.valueType,r);if(o.type==="lazy")return mn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return mn(o.innerType,r);if(o.type==="intersection")return mn(o.left,r)||mn(o.right,r);if(o.type==="record"||o.type==="map")return mn(o.keyType,r)||mn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return mn(o.in,r)||mn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(mn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(mn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(mn(t,r))return!0;if(o.rest&&mn(o.rest,r))return!0;return!1}return!1}var cw=(n,i={})=>(r)=>{let o=it({...r,processors:i});return un(n,o),tt(o,n),rt(o,n)},cr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:e}=o??{},u=it({...t??{},target:e,io:i,processors:r});return un(n,u),tt(u,n),rt(u,n)};var mj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Uw=(n,i,r,o)=>{let t=r;t.type="string";let{minimum:e,maximum:u,format:l,patterns:$,contentEncoding:I}=n._zod.bag;if(typeof e==="number")t.minLength=e;if(typeof u==="number")t.maxLength=u;if(l){if(t.format=mj[l]??l,t.format==="")delete t.format;if(l==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},Dw=(n,i,r,o)=>{let t=r,{minimum:e,maximum:u,format:l,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=n._zod.bag;if(typeof l==="string"&&l.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(e??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(u??Number.POSITIVE_INFINITY),f=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof e==="number")t.minimum=e;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof u==="number")t.maximum=u;if(typeof $==="number")t.multipleOf=$},Sw=(n,i,r,o)=>{r.type="boolean"},Aw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Ow=(n,i,r,o)=>{if(i.unrepresentable==="Line truncated
`);if(n===-1)return null;let i=this._buffer.toString("utf8",0,n).replace(/\r$/,"");return this._buffer=this._buffer.subarray(n+1),w7(i)}clear(){this._buffer=void 0}}function w7(n){return vD.parse(JSON.parse(n))}function ok(n){return JSON.stringify(n)+`
`}class Y6{constructor(n=ek.stdin,i=ek.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new P6,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let n=this._readBuffer.readMessage();if(n===null)break;this.onmessage?.(n)}catch(n){this.onerror?.(n)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(n){return new Promise((i)=>{let r=ok(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as q4,join as JF}from"node:path";import{fileURLToPath as HF}from"node:url";class Ei extends Error{name="KyError";get isKyError(){return!0}}class ti extends Ei{name="HTTPError";response;request;options;data;constructor(n,i,r){let o=n.status||n.status===0?n.status:"",t=n.statusText??"",e=`${o} ${t}`.trim(),u=e?`status code ${e}`:"an unknown error";super(`Request failed with ${u}: ${i.method} ${i.url}`);this.response=n,this.request=i,this.options=r}}class de extends Ei{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Le extends Error{name="NonError";value;constructor(n){let i="Non-error value was thrown";try{if(typeof n==="string")i=n;else if(n&&typeof n==="object"&&"message"in n&&typeof n.message==="string")i=n.message}catch{}super(i);this.value=n}}class qr extends Ei{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Le(n.cause):void 0;super(n?.code?`Forced retry: ${n.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=n?.delay,this.code=n?.code,this.customRequest=n?.request}}class p6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class ki extends Ei{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var Q6=(()=>{let n=!1,i=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return n&&!i})(),uk=typeof globalThis.AbortController==="function",Sv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",lk=typeof globalThis.ReadableStream==="function",vk=typeof globalThis.FormData==="function",Av=["get","post","put","patch","head","delete"],f7=()=>{return};f7();var $k={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},_r=2147483647,Ik=40,Ov=Symbol("stop");class kv{options;constructor(n){this.options=n}}var gk=(n)=>new kv(n),bk={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},wk={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var dv=new TextEncoder,c7=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=Ik,i+=dv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?dv.encode(o).byteLength:o.size;return i}if(n instanceof Blob)return n.size;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(typeof n==="string")return dv.encode(n).byteLength;if(n instanceof URLSearchParams)return dv.encode(n.toString()).byteLength;return 0},fk=(n,i,r)=>{let o,t=0;return n.pipeThrough(new TransformStream({transform(e,u){if(u.enqueue(e),o){t+=o.byteLength;let l=i===0?0:t/i;if(l>=1)l=1-Number.EPSILON;r?.({percent:l,totalBytes:Math.max(i,t),transferredBytes:t},o)}o=e},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(i,t),transferredBytes:t},o)}}))},ck=(n,i)=>{if(!n.body)return n;let r={status:n.status,statusText:n.statusText,headers:n.headers};if(n.status===204)return new Response(null,r);let o=Math.max(0,Number(n.headers.get("content-length"))||0);return new Response(fk(n.body,o,i),r)},Uk=(n,i,r)=>{if(!n.body)return n;let o=c7(r??n.body);return new Request(n,{duplex:"half",body:fk(n.body,o,i)})};var Xi=(n)=>n!==null&&typeof n==="object";var U7=Symbol("replaceOption"),F6=(n)=>Xi(n)&&n[U7]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var ye=(...n)=>{for(let i of n)if((!Xi(i)| Line truncated
`,{mode:384}),i}function zr(n,i,r=[]){let o=i.corpId?.trim()||void 0,t=i.stateful?i.defaultCorpId?.trim()||void 0:void 0,e=o??t;if(e){let l=n.find(($)=>$.id===e);if(l)return l;throw Error(`No enterprise config found for ${e}`)}if(!i.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let u=n[0];if(u)return u;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as R5}from"node:fs";import{randomBytes as x5}from"node:crypto";import{randomBytes as dd}from"node:crypto";var f5=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),c5=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:f5.optional()}),U5=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),D5=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:U5.optional()}),nd=v.object({user:c5,tenant:D5}),S5=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),A5=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),id=v.object({user:S5,session:A5}),Fv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),td=v.object({rules:v.array(Fv),hasPendingDeletes:v.boolean().default(!1)}),O5=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Kv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(O5).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),rd=v.object({version:Kv,rulesCount:v.number()}),Xe=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),od=v.object({articles:v.array(Xe),total:v.number().optional()}),k5=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),d5=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),L5=v.enum(["assisted","semi_automatic","fully_automatic"]),sk=v.object({id:v.string(),url:v.string().url()}).passthrough(),he=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:L5,incomingDocumentWebhook:sk,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:sk,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),i4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,document:Dt({id:i?.id,sn:i?.sn??i?.sourceDocumentSN??n.sourceDocumentSN,title:i?.title??i?.name,template:zv(i,["template.name","templateName","form.name","formName","formTitle"]),amount:mv(r,["金额","报销金额","付款金额","合计","价税合计"])??zv(i,["amount","totalAmount","expenseAmount"]),expenseType:mv(r,["费用类型","费用类别","报销类型"]),costCompany:mv(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:mv(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:cQ(n),attachments:JL(n,{summary:!0}).attachments,aiResult:Rv(n),manualResult:_t(n)?.value,hints:Dt({amountMentions:DL(o,["金额","合计","税率"],8),partyMentions:DL(o,["买方","卖方","甲方","乙方","收款"],8)})}}function JL(n,i={}){let r=[["document",n.document],["result",n.result],["pipelineData",n.pipelineData],["sourceExtendData",n.sourceExtendData]],o=[],t=new Set;for(let[e,u]of r)A4(u,e,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((e)=>Dt({path:e.path,kind:e.kind,fileName:e.fileName,mimeType:e.mimeType,fileId:e.fileId,sourceField:e.sourceField})):o}}function $Q(n){let i=[["result.citedRules",mi(n,"result.citedRules")],["result.matchedRules",mi(n,"result.matchedRules")],["result.ruleResults",mi(n,"result.ruleResults")],["result.rules",mi(n,"result.rules")],["pipelineData.citedRules",mi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",mi(n,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,e]of i)(Array.isArray(e)?e:e&&typeof e==="object"?Object.values(e):[]).forEach((l,$)=>{let I=Rr(l);if(!I)return;let g=T(I.runtimeRuleId)??T(I.runtimeId)??T(I.id)??T(I.ruleId),b=T(I.ruleCode)??T(I.code)??(g?SQ(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:wQ(I.versionNumber)??n.ruleSetVersionNumber,scope:T(I.scope),strictness:T(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function A4(n,i,r,o){if(Array.isArray(n)){n.forEach((e,u)=>A4(e,`${i}.${u}`,r,o));return}let t=Rr(n);if(!t)return;if(IQ(t,i)){let e=Dt({path:i,fieldPath:i,kind:gQ(i,t),fileName:T(t.fileName)??T(t.filename)??T(t.name)??T(t.originalName),mimeType:T(t.mimeType)??T(t.mimetype)??T(t.contentType),fileId:T(t.fileId)??T(t.id)??T(t.attachmentId),ossPath:T(t.ossPath)??T(t.ossKey)??T(t.key),url:T(t.url)??T(t.signedUrl)??T(t.downloadUrl)??T(t.previewUrl),invoiceId:T(t.invoiceId),sourceField:T(t.fieldName)??T(t.label)}),u=JSON.stringify(e);if(!o.has(u))o.add(u),r.push(e)}for(let[e,u]of Object.entries(t))A4(u,`${i}.${e}`,r,o)}function IQ(n,i){let r=Object.keys(n).map((e)=>e.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(i)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((e)=>r.includes(e.toLowerCase()))}function gQ(n,i){let r=`${n} ${T(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function zv(n,i){if(!n)return;for(let r of i){let o=mi(n,r);if(o!==void 0)return o}return}function UL(n,i){if(!n)return 0;for(let r of i){let o=mi(n,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function mi(n,i){return i.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},n)}function bQ(n,i,r){let o=i.split("."),t=n;for(let e of o.slice(0,-1)){let u=t[e];if(!u||typeof u!=="object"||Array.isArray(u))t[e]={};t=t[e]}t[o[o.length-1]??i]=r}function Dt(n){return Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0))}function Rr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function wQ(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function fQ(n){let i=[];return O4(n,"document",i),i}function O4(n,i,r){if(Array.isArray(n)){n.forEach((u,l)=>O4(u,`${i}.${l}`,r));return}let o=Rr(n);if(!o)return;let t=T(o.label)??T(o.name)??T(o.title)??T(o.fieldName),e=o.value??o.displayValue??o.text??o.content;if(t&&e!==void 0&&typeof e!=="object")r.push(Dt({path:i,label:t,value:e,type:T(o.type)??T(o.fieldType)}));for(let[u,l]of Object.entries(o)){if(u==="attachments")continue;O4(l,`${i}.${u}`,r)}}function mv(n,i){return n.find((o)=>{let t=T(o.label)??"";return i.some((e)=>t.includes(e)) Line truncated
`}class Y6{constructor(n=ek.stdin,i=ek.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new P6,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let n=this._readBuffer.readMessage();if(n===null)break;this.onmessage?.(n)}catch(n){this.onerror?.(n)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(n){return new Promise((i)=>{let r=ok(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as q4,join as JF}from"node:path";import{fileURLToPath as HF}from"node:url";class Ei extends Error{name="KyError";get isKyError(){return!0}}class ti extends Ei{name="HTTPError";response;request;options;data;constructor(n,i,r){let o=n.status||n.status===0?n.status:"",t=n.statusText??"",e=`${o} ${t}`.trim(),u=e?`status code ${e}`:"an unknown error";super(`Request failed with ${u}: ${i.method} ${i.url}`);this.response=n,this.request=i,this.options=r}}class de extends Ei{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Le extends Error{name="NonError";value;constructor(n){let i="Non-error value was thrown";try{if(typeof n==="string")i=n;else if(n&&typeof n==="object"&&"message"in n&&typeof n.message==="string")i=n.message}catch{}super(i);this.value=n}}class qr extends Ei{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Le(n.cause):void 0;super(n?.code?`Forced retry: ${n.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=n?.delay,this.code=n?.code,this.customRequest=n?.request}}class p6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class ki extends Ei{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var Q6=(()=>{let n=!1,i=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return n&&!i})(),uk=typeof globalThis.AbortController==="function",Sv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",lk=typeof globalThis.ReadableStream==="function",vk=typeof globalThis.FormData==="function",Av=["get","post","put","patch","head","delete"],f7=()=>{return};f7();var $k={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},_r=2147483647,Ik=40,Ov=Symbol("stop");class kv{options;constructor(n){this.options=n}}var gk=(n)=>new kv(n),bk={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},wk={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var dv=new TextEncoder,c7=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=Ik,i+=dv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?dv.encode(o).byteLength:o.size;return i}if(n instanceof Blob)return n.size;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(typeof n==="string")return dv.encode(n).byteLength;if(n instanceof URLSearchParams)return dv.encode(n.toString()).byteLength;return 0},fk=(n,i,r)=>{let o,t=0;return n.pipeThrough(new TransformStream({transform(e,u){if(u.enqueue(e),o){t+=o.byteLength;let l=i===0?0:t/i;if(l>=1)l=1-Number.EPSILON;r?.({percent:l,totalBytes:Math.max(i,t),transferredBytes:t},o)}o=e},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(i,t),transferredBytes:t},o)}}))},ck=(n,i)=>{if(!n.body)return n;let r={status:n.status,statusText:n.statusText,headers:n.headers};if(n.status===204)return new Response(null,r);let o=Math.max(0,Number(n.headers.get("content-length"))||0);return new Response(fk(n.body,o,i),r)},Uk=(n,i,r)=>{if(!n.body)return n;let o=c7(r??n.body);return new Request(n,{duplex:"half",body:fk(n.body,o,i)})};var Xi=(n)=>n!==null&&typeof n==="object";var U7=Symbol("replaceOption"),F6=(n)=>Xi(n)&&n[U7]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var ye=(...n)=>{for(let i of n)if((!Xi(i)| Line truncated
`,{mode:384}),i}function zr(n,i,r=[]){let o=i.corpId?.trim()||void 0,t=i.stateful?i.defaultCorpId?.trim()||void 0:void 0,e=o??t;if(e){let l=n.find(($)=>$.id===e);if(l)return l;throw Error(`No enterprise config found for ${e}`)}if(!i.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let u=n[0];if(u)return u;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as R5}from"node:fs";import{randomBytes as x5}from"node:crypto";import{randomBytes as dd}from"node:crypto";var f5=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),c5=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:f5.optional()}),U5=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),D5=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:U5.optional()}),nd=v.object({user:c5,tenant:D5}),S5=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),A5=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),id=v.object({user:S5,session:A5}),Fv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),td=v.object({rules:v.array(Fv),hasPendingDeletes:v.boolean().default(!1)}),O5=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Kv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(O5).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),rd=v.object({version:Kv,rulesCount:v.number()}),Xe=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),od=v.object({articles:v.array(Xe),total:v.number().optional()}),k5=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),d5=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),L5=v.enum(["assisted","semi_automatic","fully_automatic"]),sk=v.object({id:v.string(),url:v.string().url()}).passthrough(),he=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:L5,incomingDocumentWebhook:sk,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:sk,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),i4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,document:Dt({id:i?.id,sn:i?.sn??i?.sourceDocumentSN??n.sourceDocumentSN,title:i?.title??i?.name,template:zv(i,["template.name","templateName","form.name","formName","formTitle"]),amount:Zv(r,["金额","报销金额","付款金额","合计","价税合计"])??zv(i,["amount","totalAmount","expenseAmount"]),expenseType:Zv(r,["费用类型","费用类别","报销类型"]),costCompany:Zv(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:Zv(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:cQ(n),attachments:JL(n,{summary:!0}).attachments,aiResult:Rv(n),manualResult:_t(n)?.value,hints:Dt({amountMentions:DL(o,["金额","合计","税率"],8),partyMentions:DL(o,["买方","卖方","甲方","乙方","收款"],8)})}}function JL(n,i={}){let r=[["document",n.document],["result",n.result],["pipelineData",n.pipelineData],["sourceExtendData",n.sourceExtendData]],o=[],t=new Set;for(let[e,u]of r)A4(u,e,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((e)=>Dt({path:e.path,kind:e.kind,fileName:e.fileName,mimeType:e.mimeType,fileId:e.fileId,sourceField:e.sourceField})):o}}function $Q(n){let i=[["result.citedRules",Zi(n,"result.citedRules")],["result.matchedRules",Zi(n,"result.matchedRules")],["result.ruleResults",Zi(n,"result.ruleResults")],["result.rules",Zi(n,"result.rules")],["pipelineData.citedRules",Zi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",Zi(n,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,e]of i)(Array.isArray(e)?e:e&&typeof e==="object"?Object.values(e):[]).forEach((l,$)=>{let I=Rr(l);if(!I)return;let g=T(I.runtimeRuleId)??T(I.runtimeId)??T(I.id)??T(I.ruleId),b=T(I.ruleCode)??T(I.code)??(g?SQ(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:wQ(I.versionNumber)??n.ruleSetVersionNumber,scope:T(I.scope),strictness:T(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function A4(n,i,r,o){if(Array.isArray(n)){n.forEach((e,u)=>A4(e,`${i}.${u}`,r,o));return}let t=Rr(n);if(!t)return;if(IQ(t,i)){let e=Dt({path:i,fieldPath:i,kind:gQ(i,t),fileName:T(t.fileName)??T(t.filename)??T(t.name)??T(t.originalName),mimeType:T(t.mimeType)??T(t.mimetype)??T(t.contentType),fileId:T(t.fileId)??T(t.id)??T(t.attachmentId),ossPath:T(t.ossPath)??T(t.ossKey)??T(t.key),url:T(t.url)??T(t.signedUrl)??T(t.downloadUrl)??T(t.previewUrl),invoiceId:T(t.invoiceId),sourceField:T(t.fieldName)??T(t.label)}),u=JSON.stringify(e);if(!o.has(u))o.add(u),r.push(e)}for(let[e,u]of Object.entries(t))A4(u,`${i}.${e}`,r,o)}function IQ(n,i){let r=Object.keys(n).map((e)=>e.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(i)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((e)=>r.includes(e.toLowerCase()))}function gQ(n,i){let r=`${n} ${T(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function zv(n,i){if(!n)return;for(let r of i){let o=Zi(n,r);if(o!==void 0)return o}return}function UL(n,i){if(!n)return 0;for(let r of i){let o=Zi(n,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function Zi(n,i){return i.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},n)}function bQ(n,i,r){let o=i.split("."),t=n;for(let e of o.slice(0,-1)){let u=t[e];if(!u||typeof u!=="object"||Array.isArray(u))t[e]={};t=t[e]}t[o[o.length-1]??i]=r}function Dt(n){return Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0))}function Rr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function wQ(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function fQ(n){let i=[];return O4(n,"document",i),i}function O4(n,i,r){if(Array.isArray(n)){n.forEach((u,l)=>O4(u,`${i}.${l}`,r));return}let o=Rr(n);if(!o)return;let t=T(o.label)??T(o.name)??T(o.title)??T(o.fieldName),e=o.value??o.displayValue??o.text??o.content;if(t&&e!==void 0&&typeof e!=="object")r.push(Dt({path:i,label:t,value:e,type:T(o.type)??T(o.fieldType)}));for(let[u,l]of Object.entries(o)){if(u==="attachments")continue;O4(l,`${i}.${u}`,r)}}function Zv(n,i){return n.find((o)=>{let t=T(o.label)??"";return i.some((e)=>t.includes(e)) Line truncated
`)}
`}function Ve(n){return n.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function K(n,i={}){XQ(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){jQ(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function XQ(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>HQ)throw Error(`Output is large (${r} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function qL(n,i){if(i)return;let r=n&&typeof n==="object"?n:{},o=typeof r.count==="number"?r.count:void 0,t=Array.isArray(r.rules)?r.rules.length:void 0,e=Buffer.byteLength(JSON.stringify(n),"utf-8"),u=o??t??0;if(u>WQ||e>JQ)throw Error(`Rule list is large (${u} rules, ${e} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`)}function J(n){return{allowFull:_(n.full)===!0,outputFile:D(n.outputFile)??D(n["output-file"])}}function _L(){console.log(`seal-home CLI
@@ -176,7 +176,7 @@ Usage:
seal-home simulation templates [--corp <corpId>]
seal-home simulation integrations [--corp <corpId>]
seal-home simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function Nn(n){let i=hi(),r=bi();return zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function xv(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Mr()}}async function H(n,i,r,o,t={}){K(await xr(n,i,r,o),t)}async function xr(n,i,r,o){let t=St.find((l)=>l.name===n);if(!t)throw Error(`Unknown Seal tool: ${n}`);let e=Object.fromEntries(Object.entries(o).filter(([,l])=>l!==void 0)),u=t.handler;return u(i,e,{corp:r})}async function EL(n,i,r,o,t){if(n==="summary"){let e=await xr("seal_approval_runs_summary",r,o,{date:D(t.options.date),timezone:D(t.options.timezone),limit:ln(t.options.limit),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query)});if(e?.matched===0&&e?.total>0)console.error(`提示:在 ${e.date} 未匹配到记录(该企业共有 ${e.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);K(e,J(t.options));return}if(n==="stats"){await H("seal_approval_runs_stats",r,o,{since:D(t.options.since),dedupeBy:D(t.options.dedupeBy)??D(t.options["dedupe-by"]),status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"])},J(t.options));return}if(n==="count"){await H("seal_approval_runs_count",r,o,{status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"]),search:D(t.options.search)??D(t.options.query)},J(t.options));return}if(n==="search"||n==="list"){await H("seal_approval_runs_search",r,o,{limit:ln(t.options.limit),offset:ln(t.options.offset),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await H("seal_approval_run_langfuse_bridge_get",r,o,{recordId:D(t.options.recordId),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),simulationBatchId:D(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let e=i??D(t.options.query)??D(t.options.sn);if(!e)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await H("seal_approval_run_pick",r,o,{query:e,sn:D(t.options.sn),batchId:D(t.options.batch)??D(t.options.batchId),latest:_(t.options.latest),fields:D(t.options.fields),limit:ln(t.options.limit),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="get"){let e=t.command[2];if(!e)throw Error("Missing approval run recordId");await H("seal_approval_run_get",r,o,{recordId:e,fields:D(t.options.fields),summary:_(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await H("seal_approval_run_cited_rules_get",r,o,{recordId:e},J(t.options));return}if(n==="document-summary"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await H("seal_approval_run_document_summary_get",r,o,{recordId:e},J(t.options));return}if(n==="attachments"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs attachments <recordId>");await H("seal_approval_run_attachments_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="result"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await H("seal_approval_run_result_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="url"){await H("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-home help' for available commands.`)}async function ML(n,i,r){if(n==="diagnose"){K(await hQ(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;K(await qk(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-home help' for available commands.`)}async function hQ(n){if(n.source.type!=="hose"){let c=await An(n),S=await Yi(c);return{corp:{id:n.id,name:n.name,sourceType:n.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Gv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.passw Line truncated
`)}function Nn(n){let i=hi(),r=bi();return zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function xv(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Mr()}}async function H(n,i,r,o,t={}){K(await xr(n,i,r,o),t)}async function xr(n,i,r,o){let t=St.find((l)=>l.name===n);if(!t)throw Error(`Unknown Seal tool: ${n}`);let e=Object.fromEntries(Object.entries(o).filter(([,l])=>l!==void 0)),u=t.handler;return u(i,e,{corp:r})}async function EL(n,i,r,o,t){if(n==="summary"){let e=await xr("seal_approval_runs_summary",r,o,{date:D(t.options.date),timezone:D(t.options.timezone),limit:ln(t.options.limit),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query)});if(e?.matched===0&&e?.total>0)console.error(`提示:在 ${e.date} 未匹配到记录(该企业共有 ${e.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);K(e,J(t.options));return}if(n==="stats"){await H("seal_approval_runs_stats",r,o,{since:D(t.options.since),dedupeBy:D(t.options.dedupeBy)??D(t.options["dedupe-by"]),status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"])},J(t.options));return}if(n==="count"){await H("seal_approval_runs_count",r,o,{status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"]),search:D(t.options.search)??D(t.options.query)},J(t.options));return}if(n==="search"||n==="list"){await H("seal_approval_runs_search",r,o,{limit:ln(t.options.limit),offset:ln(t.options.offset),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await H("seal_approval_run_langfuse_bridge_get",r,o,{recordId:D(t.options.recordId),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),simulationBatchId:D(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let e=i??D(t.options.query)??D(t.options.sn);if(!e)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await H("seal_approval_run_pick",r,o,{query:e,sn:D(t.options.sn),batchId:D(t.options.batch)??D(t.options.batchId),latest:_(t.options.latest),fields:D(t.options.fields),limit:ln(t.options.limit),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="get"){let e=t.command[2];if(!e)throw Error("Missing approval run recordId");await H("seal_approval_run_get",r,o,{recordId:e,fields:D(t.options.fields),summary:_(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await H("seal_approval_run_cited_rules_get",r,o,{recordId:e},J(t.options));return}if(n==="document-summary"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await H("seal_approval_run_document_summary_get",r,o,{recordId:e},J(t.options));return}if(n==="attachments"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs attachments <recordId>");await H("seal_approval_run_attachments_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="result"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await H("seal_approval_run_result_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="url"){await H("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-home help' for available commands.`)}async function ML(n,i,r){if(n==="diagnose"){K(await hQ(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;K(await qk(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-home help' for available commands.`)}async function hQ(n){if(n.source.type!=="hose"){let c=await An(n),S=await Yi(c);return{corp:{id:n.id,name:n.name,sourceType:n.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Gv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.passw Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Wn.length} candidate administrators:
- ${On}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&e)S=e;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators.");let k=Un(n,"id")??w,d=f??w,p=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,h={id:k,name:d,seal:{url:p,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)Gv(k),await ar(h);let j=n4();nN(j,{recursive:!0,mode:448});let L=tN(j,`${j4(k)}.json`);if(sL(L)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${L}. Pass "overwrite": true to replace it.`);iN(L,`${JSON.stringify(h,null,2)}
@@ -211,12 +211,12 @@ selection, source authentication, response compaction, and diagnostics-friendly
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function Hn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function IN(n,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),n.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=n.headers.host||"localhost",o=n.headers["x-forwarded-proto"]||"http",t=new EQ(n.url||"/",`${o}://${r}`),e=t.pathname.replace(/\/+$/,"")||"/",u=(n.method||"GET").toUpperCase();try{if(u==="GET"&&e==="/"){Dn(i,200,{name:"seal-home",version:R,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(u==="GET"&&e==="/docs"){mQ(i,200,$N());return}if(u==="GET"&&(e==="/openapi.json"||e==="/openapi")){let l=n$();Dn(i,200,l);return}if(u==="GET"&&(e==="/health"||e==="/version")){Dn(i,200,{status:"ok",name:"seal-home",version:R,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(u==="GET"&&e==="/api/tools"){Dn(i,200,{count:St.length,tools:St.map((l)=>({name:l.name,description:l.description}))});return}if(u==="POST"&&e==="/api/cli"){let l=await t$(n),$=typeof l?.command==="string"?l.command.trim():"";if(!$){i$(i,400,"Missing or empty 'command' field in request body");return}let I=P4($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await qe(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Dn(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(u==="POST"&&e.startsWith("/api/tool/")){let l=e.slice(10).trim(),$=jn(l,{includeMcpAliases:!0});if(!$){i$(i,404,`Tool not found: '${l}'`);return}let I=await t$(n)||{},g=zn(n,t,I),b=Nn(g),w=await An(b),f={...I};delete f.corp;let c=await Hn($,w,f,b);Dn(i,200,c);return}if(e.startsWith("/v1/")){if(await ZQ(n,i,u,e,t))return}i$(i,404,`Cannot ${u} ${e}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);i$(i,500,$)}}async function ZQ(n,i,r,o,t){let e=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let u=hi(),l=bi();return Dn(i,200,{count:u.length,mode:l.stateful?"stateful":"stateless",defaultCorpId:l.defaultCorpId,corps:u.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_whoami"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_session_get"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_summary"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_stats"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_pick"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_url_get"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let u=o.slice(18).split("/"),l=u[0],$=u[1];if(l&&!["summary","pick","stats","url","bridge"].includes(l)){let I=zn(n,t,e),g=Nn(I),b=await An(g);if(!$){let w=jn("seal_approval_run_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="attachments"){let w=jn("seal_approval_run_attachments_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="cited-rules"){let w=jn("seal_approval_run_cited_rules_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="document-summary"){let w=jn("seal_approval_run_document_summary_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="result"){let w=jn("seal_approval_run_result_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_search"),g=await Hn(I,$,{...e,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,includeBridge:e.includeBridge==="true"},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_rules_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_simulation_batches_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let u=await t$(n)||{},l=zn(n,t,u),$=Nn(l),I=await An($),g=jn("seal_simulaLine truncated
</html>`}async function Hn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function IN(n,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),n.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=n.headers.host||"localhost",o=n.headers["x-forwarded-proto"]||"http",t=new EQ(n.url||"/",`${o}://${r}`),e=t.pathname.replace(/\/+$/,"")||"/",u=(n.method||"GET").toUpperCase();try{if(u==="GET"&&e==="/"){Dn(i,200,{name:"seal-home",version:R,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(u==="GET"&&e==="/docs"){ZQ(i,200,$N());return}if(u==="GET"&&(e==="/openapi.json"||e==="/openapi")){let l=n$();Dn(i,200,l);return}if(u==="GET"&&(e==="/health"||e==="/version")){Dn(i,200,{status:"ok",name:"seal-home",version:R,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(u==="GET"&&e==="/api/tools"){Dn(i,200,{count:St.length,tools:St.map((l)=>({name:l.name,description:l.description}))});return}if(u==="POST"&&e==="/api/cli"){let l=await t$(n),$=typeof l?.command==="string"?l.command.trim():"";if(!$){i$(i,400,"Missing or empty 'command' field in request body");return}let I=P4($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await qe(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Dn(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(u==="POST"&&e.startsWith("/api/tool/")){let l=e.slice(10).trim(),$=jn(l,{includeMcpAliases:!0});if(!$){i$(i,404,`Tool not found: '${l}'`);return}let I=await t$(n)||{},g=zn(n,t,I),b=Nn(g),w=await An(b),f={...I};delete f.corp;let c=await Hn($,w,f,b);Dn(i,200,c);return}if(e.startsWith("/v1/")){if(await mQ(n,i,u,e,t))return}i$(i,404,`Cannot ${u} ${e}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);i$(i,500,$)}}async function mQ(n,i,r,o,t){let e=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let u=hi(),l=bi();return Dn(i,200,{count:u.length,mode:l.stateful?"stateful":"stateless",defaultCorpId:l.defaultCorpId,corps:u.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_whoami"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_session_get"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_summary"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_stats"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_pick"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_url_get"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let u=o.slice(18).split("/"),l=u[0],$=u[1];if(l&&!["summary","pick","stats","url","bridge"].includes(l)){let I=zn(n,t,e),g=Nn(I),b=await An(g);if(!$){let w=jn("seal_approval_run_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="attachments"){let w=jn("seal_approval_run_attachments_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="cited-rules"){let w=jn("seal_approval_run_cited_rules_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="document-summary"){let w=jn("seal_approval_run_document_summary_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="result"){let w=jn("seal_approval_run_result_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_search"),g=await Hn(I,$,{...e,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,includeBridge:e.includeBridge==="true"},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_rules_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_simulation_batches_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let u=await t$(n)||{},l=zn(n,t,u),$=Nn(l),I=await An($),g=jn("seal_simulaLine truncated
\uD83D\uDE80 seal-home HTTP Server (v${R}) started`),console.error(` URL: http://${r}:${i}`),console.error(` Docs: http://${r}:${i}/docs`),console.error(` OpenAPI: http://${r}:${i}/openapi.json`),console.error(` CLI Exec: POST http://${r}:${i}/api/cli`),console.error(` REST API: http://${r}:${i}/v1/...
`);t(o)})})}async function bN(n){let i=ln(n.options.port)??ln(n.options.p),r=D(n.options.host)??D(n.options.h),o=await gN({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function wN(n,i,r,o){if(n==="config"||n==="get"){await H("seal_llm_config_get",i,r,{},J(o.options));return}if(n==="providers"||n==="list"){await H("seal_llm_providers_list",i,r,{},J(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-home help' for available commands.`)}async function fN(n,i){if(n==="config"||n==="json"){Y4();return}await p4()}function Y4(){K({mcpServers:{"seal-home":{type:"stdio",command:"seal-home",args:["mcp"],env:{SEAL_HOME_MCP_ENABLED:"true"}}}})}function cN(n){let i=n$();K(i,{...J(n.options),allowFull:!0})}async function UN(n,i,r,o){if(n==="available"){await H("seal_permissions_available_list",i,r,{},J(o.options));return}if(n==="configs"||n==="list"){await H("seal_permissions_configs_list",i,r,{},J(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as DN}from"node:fs";async function SN(n,i,r,o,t,e,u){if(!n||n==="get"){await H("seal_preference_get",t,e,{},J(u.options));return}if(n==="decision"){if(i==="update"||!i){let l=D(u.options.input),$=l?JSON.parse(DN(l,"utf8")):ri(u.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-home preference decision update --json '{"explicitApprove":"..."}'`);await H("seal_preference_decision_update",t,e,$,J(u.options));return}}if(n==="thinking-depth"||n==="thinkingDepth"){if(i==="set"){let l=D(u.options.default)??D(u.options.level)??o;if(l!=="medium"&&l!=="high")throw Error("Usage: seal-home preference thinking-depth set --default <medium|high>");await H("seal_preference_thinking_depth_set",t,e,{defaultLevel:l},J(u.options));return}if(i==="policies"){if(r==="list"||!r){await H("seal_preference_thinking_depth_policies_list",t,e,{},J(u.options));return}if(r==="upsert"){let l=D(u.options.input),$=l?JSON.parse(DN(l,"utf8")):ri(u.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-home preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await H("seal_preference_thinking_depth_policies_upsert",t,e,$,J(u.options));return}if(r==="remove"||r==="delete"){let l=o??D(u.options.id)??D(u.options.policyId);if(!l)throw Error("Usage: seal-home preference thinking-depth policies remove <policyId>");await H("seal_preference_thinking_depth_policies_remove",t,e,{policyId:l},J(u.options));return}}}throw Error(`Unknown preference action: ${n??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function AN(n={}){let i=hi(),r=bi(),o=zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await ar(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let e=await An(o),u=await _v(e,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:u.rules.rules.length,hasPendingRuleDeletes:u.rules.hasPendingDeletes,documents:u.documents.articles.length,documentsTotal:u.documents.total,stylePreferences:u.stylePreferences.ok?"ok":`error: ${u.stylePreferences.error}`},null,2))}async function ON(n,i,r){let o=i??D(r.options.corp)??(n&&n!=="--corp"?n:void 0);await AN({corpId:o})}async function kN(n,i,r,o,t){if(n==="count"){await H("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}if(n==="list"){if(_(t.options.count)){await H("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}let e=ln(t.options.limit),u=ln(t.options.offset);if(_(t.options.summary)){await H("seal_approval_rules_list",r,o,{fields:TL,limit:e,offset:u},J(t.options));return}let l=await xr("seal_approval_rules_list",r,o,{limit:e,offset:u});qL(l,_(t.options.full)===!0),K(l);return}if(n==="clear"){let e=_(t.options.yes)===!0,u=_(t.options.dryRun)??_(t.options["dry-run"])??!e;if(!e&&!u)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await xr("seal_approval_rules_clear",r,o,{dryRun:u,recode:_(t.options.recode)});if(!e&&u&&l&&typeof l==="object"){K({...l,nextCommand:`seal-home rules clear --corp ${o.id} --yes`},J(t.options));return}K(l,J(t.options));return}if(n==="versions"){await H("seal_approval_rule_versions_list",r,o,{},J(t.options));return}if(n==="version"){let e=i??D(t.options.version);if(!e)throw Error("Usage: seal-home rules version <versionId|versionNumber|latest>");await H("seal_approval_rule_version_get",r,o,Ke(e),J(t.options));return}if(n==="get"){await H("seal_approval_rule_get",r,o,{...VL(D(t.options.version)),code:D(t.options.code),runtimeId:D(t.options.runtimeId)??D(t.options["runtime-id"]),recordId:D(t.options.recordId)??D(t.options["record-id"])},J(t.options)) Line truncated
`,{mode:384}),o$(r,`running pid=${process.pid}`);let o=()=>{if(F4(i)===process.pid)r$(i,{force:!0});o$(r,`stopped pid=${process.pid}`)};await new Promise((t)=>{let e=!1,u=setInterval(()=>{},60000),l=()=>{if(e)return;e=!0,o(),clearInterval(u),process.off("SIGTERM",l),process.off("SIGINT",l),t()};process.once("SIGTERM",l),process.once("SIGINT",l)})}function dN(n){GN(n.stateDir);let i=sr(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=zQ(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=e$(n);return Q4(t,`${o.pid}
`,{mode:384}),o$(u$(n),`started pid=${o.pid}`),{started:!0,...sr(n)}}function LN(n,i={}){let r=e$(n),o=F4(r);if(!o||!yN(o,n.appRoot))return r$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),r$(r,{force:!0}),o$(u$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function yN(n,i){if(!nF(n))return!1;try{let r=CQ("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-home")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function nF(n){try{return process.kill(n,0),!0}catch{return!1}}function e$(n){return NN(n.stateDir,"service.pid")}function u$(n){return NN(n.stateDir,"service.log")}function F4(n){if(!RQ(n))return;let i=Number(aQ(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function GN(n){xQ(n,{recursive:!0,mode:448})}function o$(n,i){Q4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var K4=tF(iF(),".config","seal-home");async function jN(n,i){let r=await Et(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:K4,version:R,launcher:i.launcher});if(r!==void 0)K(r)}import{existsSync as rF,readFileSync as WN}from"node:fs";async function JN(n,i,r,o,t){if(n==="batch-records"||n==="records"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation batch-records <batchId>");await H("seal_simulation_batch_records_get",r,o,{batchId:e,query:D(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let e=D(t.options.mode)??D(t.options.sourceSystem)??D(t.options["source-system"])??"hosecloud",u=e==="material-pack"?"material_pack":e,l=D(t.options.schemaConfig)??D(t.options["schema-config"]),$=l?JSON.parse(WN(l,"utf8")):void 0,I=D(t.options.input),g=I?JSON.parse(WN(I,"utf8")):ri(t.json),b=D(t.options.packageId)??D(t.options["package-id"]),w=Tn(t.options.packageIds)??Tn(t.options["package-ids"])??(b?[b]:void 0),f=Tn(t.options.flowIds)??Tn(t.options["flow-ids"])??Tn(t.options.documentSn)??Tn(t.options["document-sn"]),c=D(t.options.signKey)??D(t.options["sign-key"])??D(t.options.integration);await H("seal_simulation_batch_create",r,o,{mode:u,sourceSystem:u,flowIds:f,documentSn:f,rejectNodeName:D(t.options.rejectNode)??D(t.options["reject-node"])??null,thinkingDepthOverride:D(t.options.thinkingDepth)??D(t.options["thinking-depth"]),skipInvoiceGeneration:_(t.options.skipInvoiceGeneration)??_(t.options["skip-invoice-generation"]),skipExpenseExtraction:_(t.options.skipExpenseExtraction)??_(t.options["skip-expense-extraction"]),disableAttachmentCache:_(t.options.disableAttachmentCache)??_(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:D(t.options.templateId)??D(t.options["template-id"]),schemaConfig:$,requestIds:Tn(t.options.requestIds)??Tn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:Tn(t.options.flowStatusList)?.map(Number)??Tn(t.options["flow-status-list"])?.map(Number),businessCodes:Tn(t.options.businessCodes)??Tn(t.options["business-codes"]),documentType:D(t.options.documentType)??D(t.options["document-type"]),startTime:ln(t.options.startTime)??ln(t.options["start-time"]),endTime:ln(t.options.endTime)??ln(t.options["end-time"]),status:Tn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await H("seal_simulation_batch_wait",r,o,{batchId:e,timeout:D(t.options.timeout),pollInterval:D(t.options.pollInterval)??D(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation clean <batchId>");await H("seal_simulation_batch_clean",r,o,{batchId:e},J(t.options));return}if(n==="specifications"){let e=i??D(t.options.integration)??D(t.options.signKey)??D(t.options["sign-key"]);await H("seal_simulation_specifications_list",r,o,{signKey:e},J(t.options));return}if(n==="list"){await H("seal_simulation_batches_list",r,o,{limit:ln(t.options.limit)},J(t.options));return}if(n==="get"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation get <batchId>");await H("seal_simulation_batch_get",r,o,{batchId:e},J(t.options));return}if(n==="templates"){await H("seal_simulation_templates_get",r,o,{},J(t.options));return}if(n==="integrations"){await H("seal_simulation_integrations_get",r,o,{},J(t.options));return}if(n==="package-upload"){let e=i??D(t.options.file);if(!e)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!rF(e))throw Error(`File not found: ${e}`);await H("seal_simulation_material_package_upload",r,o,{filePath:e},J(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{existsSync as mN}from"node:fs";import{join as l$}from"node:path";import{mkdirSync as TN,writeFileSync as cF}from"node:fs";import{homedir as UF}from"node:os";import{dirname as DF,join as qN}from"node:path";var HN=`---
`,{flag:"a",mode:384})}var K4=tF(iF(),".config","seal-home");async function jN(n,i){let r=await Et(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:K4,version:R,launcher:i.launcher});if(r!==void 0)K(r)}import{existsSync as rF,readFileSync as WN}from"node:fs";async function JN(n,i,r,o,t){if(n==="batch-records"||n==="records"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation batch-records <batchId>");await H("seal_simulation_batch_records_get",r,o,{batchId:e,query:D(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let e=D(t.options.mode)??D(t.options.sourceSystem)??D(t.options["source-system"])??"hosecloud",u=e==="material-pack"?"material_pack":e,l=D(t.options.schemaConfig)??D(t.options["schema-config"]),$=l?JSON.parse(WN(l,"utf8")):void 0,I=D(t.options.input),g=I?JSON.parse(WN(I,"utf8")):ri(t.json),b=D(t.options.packageId)??D(t.options["package-id"]),w=Tn(t.options.packageIds)??Tn(t.options["package-ids"])??(b?[b]:void 0),f=Tn(t.options.flowIds)??Tn(t.options["flow-ids"])??Tn(t.options.documentSn)??Tn(t.options["document-sn"]),c=D(t.options.signKey)??D(t.options["sign-key"])??D(t.options.integration);await H("seal_simulation_batch_create",r,o,{mode:u,sourceSystem:u,flowIds:f,documentSn:f,rejectNodeName:D(t.options.rejectNode)??D(t.options["reject-node"])??null,thinkingDepthOverride:D(t.options.thinkingDepth)??D(t.options["thinking-depth"]),skipInvoiceGeneration:_(t.options.skipInvoiceGeneration)??_(t.options["skip-invoice-generation"]),skipExpenseExtraction:_(t.options.skipExpenseExtraction)??_(t.options["skip-expense-extraction"]),disableAttachmentCache:_(t.options.disableAttachmentCache)??_(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:D(t.options.templateId)??D(t.options["template-id"]),schemaConfig:$,requestIds:Tn(t.options.requestIds)??Tn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:Tn(t.options.flowStatusList)?.map(Number)??Tn(t.options["flow-status-list"])?.map(Number),businessCodes:Tn(t.options.businessCodes)??Tn(t.options["business-codes"]),documentType:D(t.options.documentType)??D(t.options["document-type"]),startTime:ln(t.options.startTime)??ln(t.options["start-time"]),endTime:ln(t.options.endTime)??ln(t.options["end-time"]),status:Tn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await H("seal_simulation_batch_wait",r,o,{batchId:e,timeout:D(t.options.timeout),pollInterval:D(t.options.pollInterval)??D(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation clean <batchId>");await H("seal_simulation_batch_clean",r,o,{batchId:e},J(t.options));return}if(n==="specifications"){let e=i??D(t.options.integration)??D(t.options.signKey)??D(t.options["sign-key"]);await H("seal_simulation_specifications_list",r,o,{signKey:e},J(t.options));return}if(n==="list"){await H("seal_simulation_batches_list",r,o,{limit:ln(t.options.limit)},J(t.options));return}if(n==="get"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation get <batchId>");await H("seal_simulation_batch_get",r,o,{batchId:e},J(t.options));return}if(n==="templates"){await H("seal_simulation_templates_get",r,o,{},J(t.options));return}if(n==="integrations"){await H("seal_simulation_integrations_get",r,o,{},J(t.options));return}if(n==="package-upload"){let e=i??D(t.options.file);if(!e)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!rF(e))throw Error(`File not found: ${e}`);await H("seal_simulation_material_package_upload",r,o,{filePath:e},J(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{existsSync as ZN}from"node:fs";import{join as l$}from"node:path";import{mkdirSync as TN,writeFileSync as cF}from"node:fs";import{homedir as UF}from"node:os";import{dirname as DF,join as qN}from"node:path";var HN=`---
name: seal-home
description: "v0.9.8: Use for Seal Home first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
@@ -1529,12 +1529,12 @@ seal-home corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var _N={"SKILL.md":HN,"agents/openai.yaml":XN,"references/rule-lightweight.md":hN,"references/approval-bad-cases.md":PN,"references/cli.md":YN,"references/approval-run-lightweight.md":pN,"references/approval-attachment-trace.md":QN,"references/customer-feedback-rule-remediation.md":FN,"references/enterprise-onboarding.md":KN,"references/hose-enterprise-auth.md":BN,"references/hose-enterprise-init.md":VN};function EN(){return _N["SKILL.md"]||""}function _e(){return qN(UF(),".agents","skills","seal-home")}function B4(n=_e()){TN(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(_N)){let t=qN(n,r);TN(DF(t),{recursive:!0}),cF(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function ZN(){let n=_e();return B4(n),{synced:!0,targetDir:n}}function MN(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${EN()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(r.options.workspace),t=D(r.options.dir)??D(r.options.target)??i,e=t?t:o?l$(process.cwd(),".agents","skills","seal-home"):_e(),u=B4(e);K({installed:!0,targetDir:u.targetDir,fileCount:u.files.length,files:u.files});return}if(n==="status"||n==="get"||!n){let o=_e(),t=l$(process.cwd(),".agents","skills","seal-home");K({global:{dir:o,installed:mN(l$(o,"SKILL.md"))},local:{dir:t,installed:mN(l$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-home help' for available commands.`)}async function zN(n,i){if(n==="config"){K(await ar(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-home help' for available commands.`)}async function CN(n,i,r,o){if(!n)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await H(n,i,r,ri(o.json),J(o.options))}function RN(){K(St.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as SF,mkdirSync as AF,renameSync as V4,rmSync as OF,unlinkSync as iy,writeFileSync as xN}from"node:fs";import{dirname as kF,join as aN}from"node:path";import{spawnSync as Zt}from"node:child_process";function v$(n=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let r=n.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")}var ty="yunyingk/seal-home";var dF="SEAL_HOME_GITHUB_REPO";async function ry(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:K4,version:R,launcher:n.launcher},o=i.repo||process.env[dF]?.trim()||ty,t=i.targetVersion?.trim(),e=t&&t.toLowerCase()!=="latest"?t:void 0;if(e){let j=e.replace(/^v/,""),L=oy(j,R);if(L<0){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`Cannot downgrade seal-home from v${R} to older version v${j}. Updates must be forward-only.`});return}if(L===0&&!i.force){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`seal-home is already at version v${R}. Use --force to reinstall.`});return}}if(i.changelogOnly){let j=await T4(o,i.limit??10);K({currentVersion:R,totalQueried:j.length,releases:j.map((L)=>({version:L.version,tagName:L.tagName,publishedAt:L.publishedAt,author:L.author,releaseNotes:L.notes,releaseUrl:L.htmlUrl,isCurrent:L.version===R,isNewer:Ee(L.version,R)}))});return}if(!v$()){if(i.checkOnly){let L=await T4(o,30),q=L[0],x=q?.version??R,yn=L.find((en)=>en.version===R),Wn=Ee(x,R),On=L.filter((en)=>Ee(en.version,R));K({updated:!1,updateAvailable:Wn,currentVersion:R,currentVersionPublishedAt:yn?.publishedAt,latestVersion:x,latestVersionPublishedAt:q?.publishedAt,behindCount:On.length,pendingReleases:On.map((en)=>({version:en.version,tagName:en.tagName,publishedAt:en.publishedAt,author:en.author,releaseNotes:en.notes,releaseUrl:en.htmlUrl})),releaseNotes:q?.notes??"",releaseUrl:q?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let j=sr(r).running;if(j)await Et("stop",r);try{ny("git",["-C",n.appRoot,"pull","--ff-only"])}catch(L){console.error(`git pull skipped: ${L instanceof Error?L.message:String(L)}`)}if(ny("bun",["install"],{cwd:n.appRoot}),j)await Et("start",r);K({updated:!0,serviceRestarted:j,version:R,mode:"source"});return}let u=LF(),l=NF(),$=await T4(o,30),I=e?$.find((j)=>j.version===e||j.tagName===e||j.tagName===`v${e}`)??await sN(o,e):$[0]??await sN(o);if(!I){K({updated:!1,currentVersion:R,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((j)=>j.version===R),w=Ee(g,R),f=w||Boolean(i.force),c=$.filter((j)=>Ee(j.version,R));if(i.checkOnly){K({updated:!1,updateAvailable:w,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((j)=>({version:j.version,tagName:j.tagName,publishedAt:j.publishedAt,author:j.author,releaseNotes:j.notes,releaseUrl:j.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){K({updated:!1,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${R})`});return}let S=yF(I.assets,u,l);if(!S)throw Error(`No compatible binary found for ${u}-${l} in release v${g}. Available assets: ${I.assets.map((j)=>j.name).join(", ")}`);let k=sr(r).running;if(k)await Et("stop",r);let d=process.execPath,p=kF(d),h=aN(p,`.tmp-update-${Date.now()}`);AF(h,{recursive:!0});try{let j=aN(h,S.name);await GF(S.downloadUrl,j,I.tagName,S.name);let L=j;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))L=jF(j,h,u);else if(S.name.endsWith(".zip"))L=WF(j,h,u);if(SF(L,493),process.platform==="darwin")try{Zt("/usr/bin/codesign",["--remove-signature",L],{stdio:"ignore"}),Zt("/usr/bin/codesign",["--force","--sign","-",L],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x=`${Line truncated
`;var _N={"SKILL.md":HN,"agents/openai.yaml":XN,"references/rule-lightweight.md":hN,"references/approval-bad-cases.md":PN,"references/cli.md":YN,"references/approval-run-lightweight.md":pN,"references/approval-attachment-trace.md":QN,"references/customer-feedback-rule-remediation.md":FN,"references/enterprise-onboarding.md":KN,"references/hose-enterprise-auth.md":BN,"references/hose-enterprise-init.md":VN};function EN(){return _N["SKILL.md"]||""}function _e(){return qN(UF(),".agents","skills","seal-home")}function B4(n=_e()){TN(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(_N)){let t=qN(n,r);TN(DF(t),{recursive:!0}),cF(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function mN(){let n=_e();return B4(n),{synced:!0,targetDir:n}}function MN(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${EN()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(r.options.workspace),t=D(r.options.dir)??D(r.options.target)??i,e=t?t:o?l$(process.cwd(),".agents","skills","seal-home"):_e(),u=B4(e);K({installed:!0,targetDir:u.targetDir,fileCount:u.files.length,files:u.files});return}if(n==="status"||n==="get"||!n){let o=_e(),t=l$(process.cwd(),".agents","skills","seal-home");K({global:{dir:o,installed:ZN(l$(o,"SKILL.md"))},local:{dir:t,installed:ZN(l$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-home help' for available commands.`)}async function zN(n,i){if(n==="config"){K(await ar(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-home help' for available commands.`)}async function CN(n,i,r,o){if(!n)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await H(n,i,r,ri(o.json),J(o.options))}function RN(){K(St.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as SF,mkdirSync as AF,renameSync as V4,rmSync as OF,unlinkSync as iy,writeFileSync as xN}from"node:fs";import{dirname as kF,join as aN}from"node:path";import{spawnSync as mt}from"node:child_process";function v$(n=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let r=n.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")}var ty="yunyingk/seal-home";var dF="SEAL_HOME_GITHUB_REPO";async function ry(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:K4,version:R,launcher:n.launcher},o=i.repo||process.env[dF]?.trim()||ty,t=i.targetVersion?.trim(),e=t&&t.toLowerCase()!=="latest"?t:void 0;if(e){let j=e.replace(/^v/,""),L=oy(j,R);if(L<0){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`Cannot downgrade seal-home from v${R} to older version v${j}. Updates must be forward-only.`});return}if(L===0&&!i.force){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`seal-home is already at version v${R}. Use --force to reinstall.`});return}}if(i.changelogOnly){let j=await T4(o,i.limit??10);K({currentVersion:R,totalQueried:j.length,releases:j.map((L)=>({version:L.version,tagName:L.tagName,publishedAt:L.publishedAt,author:L.author,releaseNotes:L.notes,releaseUrl:L.htmlUrl,isCurrent:L.version===R,isNewer:Ee(L.version,R)}))});return}if(!v$()){if(i.checkOnly){let L=await T4(o,30),q=L[0],x=q?.version??R,yn=L.find((en)=>en.version===R),Wn=Ee(x,R),On=L.filter((en)=>Ee(en.version,R));K({updated:!1,updateAvailable:Wn,currentVersion:R,currentVersionPublishedAt:yn?.publishedAt,latestVersion:x,latestVersionPublishedAt:q?.publishedAt,behindCount:On.length,pendingReleases:On.map((en)=>({version:en.version,tagName:en.tagName,publishedAt:en.publishedAt,author:en.author,releaseNotes:en.notes,releaseUrl:en.htmlUrl})),releaseNotes:q?.notes??"",releaseUrl:q?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let j=sr(r).running;if(j)await Et("stop",r);try{ny("git",["-C",n.appRoot,"pull","--ff-only"])}catch(L){console.error(`git pull skipped: ${L instanceof Error?L.message:String(L)}`)}if(ny("bun",["install"],{cwd:n.appRoot}),j)await Et("start",r);K({updated:!0,serviceRestarted:j,version:R,mode:"source"});return}let u=LF(),l=NF(),$=await T4(o,30),I=e?$.find((j)=>j.version===e||j.tagName===e||j.tagName===`v${e}`)??await sN(o,e):$[0]??await sN(o);if(!I){K({updated:!1,currentVersion:R,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((j)=>j.version===R),w=Ee(g,R),f=w||Boolean(i.force),c=$.filter((j)=>Ee(j.version,R));if(i.checkOnly){K({updated:!1,updateAvailable:w,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((j)=>({version:j.version,tagName:j.tagName,publishedAt:j.publishedAt,author:j.author,releaseNotes:j.notes,releaseUrl:j.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){K({updated:!1,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${R})`});return}let S=yF(I.assets,u,l);if(!S)throw Error(`No compatible binary found for ${u}-${l} in release v${g}. Available assets: ${I.assets.map((j)=>j.name).join(", ")}`);let k=sr(r).running;if(k)await Et("stop",r);let d=process.execPath,p=kF(d),h=aN(p,`.tmp-update-${Date.now()}`);AF(h,{recursive:!0});try{let j=aN(h,S.name);await GF(S.downloadUrl,j,I.tagName,S.name);let L=j;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))L=jF(j,h,u);else if(S.name.endsWith(".zip"))L=WF(j,h,u);if(SF(L,493),process.platform==="darwin")try{mt("/usr/bin/codesign",["--remove-signature",L],{stdio:"ignore"}),mt("/usr/bin/codesign",["--force","--sign","-",L],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x=`${Line truncated
`)}catch{}}async function GF(n,i,r,o){let t=[],e=r?r.startsWith("v")?r:`v${r}`:void 0,u=o||n.split("/").pop()||"";if(e&&u)t.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${e}/${u}`);if(n.startsWith("https://git.ying-qing.cn"))t.push(n);if(e&&u){let c=`https://github.com/${ty}/releases/download/${e}/${u}`;t.push(`https://ghfast.top/${c}`),t.push(`https://gh.ddlc.top/${c}`),t.push(c)}else if(n.includes("github.com"))t.push(`https://ghfast.top/${n}`),t.push(`https://gh.ddlc.top/${n}`),t.push(n);else t.push(n);let l=Array.from(new Set(t)),$,I=6000,g=6000,b=307200,w=1e4,f=180000;for(let c=0;c<l.length;c++){let S=l[c],k=new AbortController,d="",p=(q)=>{d=q;try{k.abort()}catch{}},h=setTimeout(()=>{p("Connection timed out (no response headers within 6s)")},I),j,L;try{$$(`==> [${c+1}/${l.length}] Downloading via: ${S}`);let q=await fetch(S,{signal:k.signal});if(h)clearTimeout(h),h=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);j=setTimeout(()=>{p("Overall download time exceeded 3 minutes")},f);let x=Number(q.headers.get("content-length"))||0,yn=q.body?.getReader();if(!yn){let wi=Buffer.from(await q.arrayBuffer());if(wi.length<1000)throw Error(`Downloaded content is suspiciously small (${wi.length} bytes)`);xN(i,wi),$$(`✓ Download succeeded (${(wi.length/1024/1024).toFixed(1)} MB)`);return}let Wn=[],On=0,en=0;L=setTimeout(()=>{if(On<b){let wi=(On/1024).toFixed(1);p(`Initial transfer too slow (${wi} KB < 300 KB in 6s), switching mirror...`)}},g);while(!0){let wi=yn.read(),no,gy=new Promise((g$,b$)=>{no=setTimeout(()=>{b$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),E4;try{E4=await Promise.race([wi,gy])}finally{if(no)clearTimeout(no)}let{done:by,value:I$}=E4;if(by)break;if(I$){if(Wn.push(I$),On+=I$.length,L&&On>=b)clearTimeout(L),L=void 0;let g$=Date.now();if(g$-en>200){en=g$;let b$=x?Math.round(On/x*100):0,wy=(On/1048576).toFixed(1),fy=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${b$}% (${wy} / ${fy} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let kt=Buffer.concat(Wn);if(kt.length<1000)throw Error(`Downloaded content is suspiciously small (${kt.length} bytes)`);xN(i,kt),$$(`✓ Download completed successfully (${(kt.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(h)clearTimeout(h);if(L)clearTimeout(L);if(j)clearTimeout(j);let x=d||(q instanceof Error?q.message:String(q));$=Error(x),$$(`
↳ Mirror failed: ${$.message}`)}finally{if(h)clearTimeout(h);if(L)clearTimeout(L);if(j)clearTimeout(j)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function jF(n,i,r){let o=Zt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=Zt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function WF(n,i,r){let o=Zt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=Zt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function oy(n,i){let r=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let e=r[t]??0,u=o[t]??0;if(e>u)return 1;if(e<u)return-1}return 0}function Ee(n,i){return oy(n,i)>0}function ny(n,i,r={}){let o=Zt(n,i,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${n} ${i.join(" ")} failed with status ${o.status}`)}async function ey(n,i,r,o,t){if(n==="create"){let e=D(t.options.name)??i,u=D(t.options.phone);if(!e||!u)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let l=D(t.options.dept)??D(t.options.departmentId);await H("seal_user_create",r,o,{name:e,phone:u,departmentIds:l?[l]:void 0},J(t.options));return}if(n==="reset-password"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users reset-password <userId>");await H("seal_user_reset_password",r,o,{userId:e},J(t.options));return}if(n==="search"||n==="list"){let e=i??D(t.options.keyword)??D(t.options.query)??"";await H("seal_user_search",r,o,{keyword:e},J(t.options));return}if(n==="get"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users get <userId>");await H("seal_user_get",r,o,{userId:e},J(t.options));return}if(n==="delete"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users delete <userId>");await H("seal_user_delete",r,o,{userId:e},J(t.options));return}if(n==="activate"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users activate <userId>");await H("seal_user_activate",r,o,{userId:e},J(t.options));return}if(n==="delegation"||n==="impersonate"){let e=i??D(t.options.userId)??D(t.options.phone);if(!e)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let u=D(t.options.note);await H("seal_user_delegation_create",r,o,{userIdOrPhone:e,note:u},J(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-home help' for available commands.`)}async function uy(n,i,r,o,t){if(n==="list"){await H("seal_webhook_list",r,o,{query:D(t.options.query)??D(t.options.keyword),includeSecret:H4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await H("seal_webhook_get",r,o,{selector:e,includeSecret:H4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let e=D(t.options.name)??i,u=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]);if(!e||!u)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=J4(t.options);await H("seal_webhook_add",r,o,{name:e,mode:W4(D(t.options.mode)),outgoingResultWebhook:u,autoApprovalRate:l,secret:D(t.options.secret)},J(t.options));return}if(n==="update"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook update <idOrName> [options]");let u=D(t.options.secret),l=_(t.options.rotateSecret)??_(t.options["rotate-secret"]);if(u!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=D(t.options.name),I=W4(D(t.options.mode)),g=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]),b=J4(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&u===void 0&&!l)throw Error("Webhook update requires at least one field option");await H("seal_webhook_update",r,o,{selector:e,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:u,rotateSecret:l},J(t.options));return}if(n==="delete"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(_(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await H("seal_webhook_delete",r,o,{selector:e,confirm:!0},J(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-home help' for available commands.`)}var ly=q4(q4(q4(HF(import.meta.url)))),XF=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),vy=Promise.resolve();function qe(n,i={}){let r=vy.then(()=>hF(n,i));return vy=r.then(()=>{return},()=>{return}),r}async function hF(n,i){let r=[],o=[],t=console.log,e=console.error,u={appRoot:i.appRoot??ly,entryFile:i.entryFile??JF(i.appRoot??ly,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.pu Line truncated
↳ Mirror failed: ${$.message}`)}finally{if(h)clearTimeout(h);if(L)clearTimeout(L);if(j)clearTimeout(j)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function jF(n,i,r){let o=mt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=mt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function WF(n,i,r){let o=mt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=mt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function oy(n,i){let r=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let e=r[t]??0,u=o[t]??0;if(e>u)return 1;if(e<u)return-1}return 0}function Ee(n,i){return oy(n,i)>0}function ny(n,i,r={}){let o=mt(n,i,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${n} ${i.join(" ")} failed with status ${o.status}`)}async function ey(n,i,r,o,t){if(n==="create"){let e=D(t.options.name)??i,u=D(t.options.phone);if(!e||!u)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let l=D(t.options.dept)??D(t.options.departmentId);await H("seal_user_create",r,o,{name:e,phone:u,departmentIds:l?[l]:void 0},J(t.options));return}if(n==="reset-password"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users reset-password <userId>");await H("seal_user_reset_password",r,o,{userId:e},J(t.options));return}if(n==="search"||n==="list"){let e=i??D(t.options.keyword)??D(t.options.query)??"";await H("seal_user_search",r,o,{keyword:e},J(t.options));return}if(n==="get"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users get <userId>");await H("seal_user_get",r,o,{userId:e},J(t.options));return}if(n==="delete"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users delete <userId>");await H("seal_user_delete",r,o,{userId:e},J(t.options));return}if(n==="activate"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users activate <userId>");await H("seal_user_activate",r,o,{userId:e},J(t.options));return}if(n==="delegation"||n==="impersonate"){let e=i??D(t.options.userId)??D(t.options.phone);if(!e)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let u=D(t.options.note);await H("seal_user_delegation_create",r,o,{userIdOrPhone:e,note:u},J(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-home help' for available commands.`)}async function uy(n,i,r,o,t){if(n==="list"){await H("seal_webhook_list",r,o,{query:D(t.options.query)??D(t.options.keyword),includeSecret:H4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await H("seal_webhook_get",r,o,{selector:e,includeSecret:H4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let e=D(t.options.name)??i,u=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]);if(!e||!u)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=J4(t.options);await H("seal_webhook_add",r,o,{name:e,mode:W4(D(t.options.mode)),outgoingResultWebhook:u,autoApprovalRate:l,secret:D(t.options.secret)},J(t.options));return}if(n==="update"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook update <idOrName> [options]");let u=D(t.options.secret),l=_(t.options.rotateSecret)??_(t.options["rotate-secret"]);if(u!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=D(t.options.name),I=W4(D(t.options.mode)),g=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]),b=J4(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&u===void 0&&!l)throw Error("Webhook update requires at least one field option");await H("seal_webhook_update",r,o,{selector:e,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:u,rotateSecret:l},J(t.options));return}if(n==="delete"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(_(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await H("seal_webhook_delete",r,o,{selector:e,confirm:!0},J(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-home help' for available commands.`)}var ly=q4(q4(q4(HF(import.meta.url)))),XF=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),vy=Promise.resolve();function qe(n,i={}){let r=vy.then(()=>hF(n,i));return vy=r.then(()=>{return},()=>{return}),r}async function hF(n,i){let r=[],o=[],t=console.log,e=console.error,u={appRoot:i.appRoot??ly,entryFile:i.entryFile??JF(i.appRoot??ly,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.pu Line truncated
`)?"":`
`}`);process.exitCode=n.exitCode}var TF=Boolean(m4.main==m4.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&$y(process.argv[1])===$y(zi));if(TF)if(process.argv[2]==="--seal-home-cli")await VF();else p4().catch((n)=>{console.error(n),process.exitCode=1});export{P4 as tokenizeCommand,p4 as startServer,FF as resolveMcpEnabled,KF as createServer,QF as SEAL_MCP_ENABLED_ENV,pF as SEAL_CLI_TOOL_NAME};
`}`);process.exitCode=n.exitCode}var TF=Boolean(Z4.main==Z4.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&$y(process.argv[1])===$y(zi));if(TF)if(process.argv[2]==="--seal-home-cli")await VF();else p4().catch((n)=>{console.error(n),process.exitCode=1});export{P4 as tokenizeCommand,p4 as startServer,FF as resolveMcpEnabled,KF as createServer,QF as SEAL_MCP_ENABLED_ENV,pF as SEAL_CLI_TOOL_NAME};
+12
View File
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { CorpConfig, HoseSealSource } from "../config/types.js";
import {
HOSE_STANDARD_DOMAINS,
assertHoseAssistTenantMatches,
defaultSealUrl,
exchangeHoseAssistLink,
fetchHoseStaffDetails,
@@ -182,4 +183,15 @@ describe("hose auth helpers", () => {
expiresIn: 1800
});
});
test("requires complete and consistent tenant identity metadata", () => {
expect(() => assertHoseAssistTenantMatches("acme-01", {})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("acme-01", {
tenantSlug: "acme-01",
hoseCorpConfig: { corporationId: "other-corp" }
})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("Acme-01", {
hoseCorpConfig: { corporationId: " ACME-01 " }
})).not.toThrow();
});
});
+8 -1
View File
@@ -198,7 +198,14 @@ export function assertHoseAssistTenantMatches(corpId: string, tenant: Record<str
: undefined;
const candidates = [tenant.tenantSlug, hoseCorpConfig?.corporationId]
.filter((value): value is string => typeof value === "string" && Boolean(value));
if (candidates.length > 0 && !candidates.some((value) => value.toLowerCase() === corpId)) {
const expectedCorpId = corpId.trim().toLowerCase();
const normalizedCandidates = candidates
.map((value) => value.trim().toLowerCase())
.filter(Boolean);
if (
normalizedCandidates.length === 0 ||
normalizedCandidates.some((value) => value !== expectedCorpId)
) {
throw new Error("Hose assistance link tenant mismatch: the Seal tenant does not match ekbCorpId");
}
}